PPS Course Material
PPS Course Material
COURSE MATERIAL
Faculty Details
Course Details
Name of the Course : BE
Branch : ECE / EEE / EIE / MECT
Year : I
Subject Code : CESCS18T40
Title of the Subject : PROGRAMMING FOR PROBLEM SOLVING
Batch : 2020-2021
1
Course Code:
L T P Credit CIA Marks 40
CESCS18T40 PROGRAMMING FOR
PROBLEM SOLVING
Course Category:
2 1 0 3 SEE Marks 60
ESC
COURSE OBJECTIVES:
COURSE OUTCOMES:
2
Mapping of Course Outcome to Program Outcomes:
Program Outcomes
Course
Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 S S S S S M L L M M - M
CO2 S S S S S M L L M M - M
CO3 S S M M S M L L M M - M
CO4 S S S S S M L L S S - S
SYLLABUS:
MODULE I
MODULE II
Arrays and its types-Functions –Parameter passing in functions-call by value- call by reference –
Passing array to functions-Recursive function.
MODULE IV
Structures and array of structures –Union, Basic searching –Linear and Binary, Basic sorting,
String operations.
MODULE V
Introduction to Pointer, Pointer arithmetic-notion of linked list (no implementation) - File handling.
3
LEARNING RESOURCES:
Text Books:
th
1. Byron Gottfried, Schaum‟s Outline of Programming with C, McGraw-Hill.4 Edition july 2018.
2. Balagurusamy. E, “Programming in ANSI C”, Tata McGraw Hill, Third edition, 2008
3. Fundamentals of Computing and Programming- V.Ramesh Babu, R.Samyuktha, M.Muniratham by VRB
Publishers Sep 2018 edition.
References:
th
1. Let Us 'C' - Yashawant Kanetkar, (Unit 2 to 5), BPB publications, 16 Edition, 2017.
2. Ashok N Kamthane, “Computer Programming”, Pearson education, Second Impression, 2011.
3. Venugopal. K and Kavichithra.C, “Computer Programming”, New Age International Publishers,
nd
2 Edition,Jan 2008.
4. Kernighan B.W and Ritchie,D.M , The C programming language: second edition, Pearson
education, 2015.
Online resources:
1. www.nptl.co.in
2. www.electrical4u.com
ASSESSMENT PATTERN:
Continuous Assessment
Bloom’s Tests Assignment Terminal Examination
Category (10) (60)
(15) (15)
Remember 7 0 20
Understand 8 - 15
Apply 0 8 10
10
Analysis 0 4 10
Evaluate 0 3 5
Create 0 0 0
Total 15 15 60
A B C D
A+B+C+D = 100
4
COURSE PLAN
1. Objectives
To Study the Basics of Computers, its organization and its Generations
2. Outcomes
Students will acquire knowledge on Basics of computers, Evolution of Computers, Organization of
computers, Generation of Computers
3. Pre-requisites
Nil
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations
1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation
2. How to explain the definition and terms with in it
Describe the functions of computers and history of Computers.
3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
Understand the concept of various parts of the computer is useful for when writing
program.
5
6. What is the final conclusion?
Understand how computer works and how number system used in computer
7. How to put it in a nut shell
Types of computers, Generations of Computers, Numbers System, Algorithm, Flow
chart
8. Important points for understanding / memorizing / make it long lasting
Computer is a Calculating Device, First Generation, second Generation, third Generation,
fourth Generation and Fifth Generation, Number System Decimal , Binary, Octal,
Hexadecimal. Algorithm is Step by Step solution to the Problem, Flow Chart is a
Pictorial representation of algorithm.
9. Questions and cross questions in that topic to make them think beyond the topic.
6
Introduction to digital Computers:
1Parts of Computer
Performance
Features that affect the performance of the computer include:
Microprocessor Operating System
RAM
Diskdrives
display input/output ports
The microprocessor:
Has a set of internal instructions stored in memory, and can access memory for its own
use while working.
Can receive instructions or data from you through a keyboard in combination with
another device
(Mouse, touchpad, trackball, and joystick).
Can receive and store data through several data storage devices (hard drive, floppy
drive, Zip drive, CD/DVD drive).
Can display data to you on computer monitors (cathode ray monitors, LCD displays).
Can send data to printers, modems, networks and wireless networks through various
input/output ports. Is powered by AC power and/or batteries.
7
Characteristics of Computers
2. Accuracy: The computers are perfect, accurate and precise. Accuracy signifies the
reliability of the hardware components of computers.
3. Automatic: A computer works automatically, once programs are stored and data are
given to it, constant supervision is not required.
4. Endurance: A computer works continuously and will not get tired and will not suffer
from lack of concentration.
6. Reduction of cost: Though initial investment may be high, computer substantially reduces
the cost of transaction.
Evolution of Computers
ABACUS:
ABACUS uses movable beads stung on wires above and below a cross bar and its operation
are based on the idea of the place value notation. The beads of the counter represent digits.
The value of the digit in each position is determined by adding the values of the beads
pressed against the cross piece.
It was the first real desktop calculating device that could add and subtract. It consists of a set
of toothed wheels or gears with each wheel or gear having digits 0 to 9 engraved on it.
Arithmetic operation could be performed by tunings these wheels.
The presence and absence of the holes in the card represent the digits.
The machine took input from the punched card. The Analytical engine had a memory which
will perform arithmetic operations.
8
Computer Generations
There are totally five computer generations known till date. Each generation has been
discussed in detail along with their time period, characteristics. We've used approximate dates
against each generations which are normally accepted.
1 First Generation
The period of first generation : 1946-1959. Vaccum tube based.
2 Second Generation
The period of second generation : 1959-1965. Transistor based.
3 Third Generation
The period of third generation : 1965-1971. Integrated Circuit based.
4 Fourth Generation
The period of fourth generation : 1971-1980. VLSI microprocessor based.
5 Fifth Generation
The period of fifth generation : 1980-onwards.ULSI microprocessor based
First Generation
ii. First generation of computer started with using vacuum tubes as the basic components for
memory and circuitry for CPU (Central Processing Unit). These tubes like electric bulbs
produced a lot of heat and were prone to frequent fusing of the installations, therefore, were
very expensive and could be afforded only by very large organisations.
iii. In this generation mainly batch processing operating system were used. In this generation
Punched cards, Paper tape, Magnetic tape Input & Output device were used.
iv. There were Machine code and electric wired board languages used.
9
Fig: First Generation
Unreliable
Very costly
Huge size
Need of A.C.
Non portable
ENIAC
EDVAC
UNIVAC
IBM-701
IBM-650
10
Second Generation
ii. This generation using the transistor were cheaper, consumed less power, more compact in size,
more reliable and faster than the first generation machines made of vaccum tubes. In this
generation, magnetic cores were
iii. used as primary memory and magnetic tape and magnetic disks as secondary storage devices.
iv. In this generation assembly language and high level programming language like FORTRAN,
COBOL were used.
Use of transistors
A.C. needed
11
IBM 1620
IBM 7094
CDC 1604
CDC 3600
UNIVAC 1108
Third Generation
ii. The third generation of computer is marked by the use of Integrated Circuits (IC's) in place of
transistors. A
iii. Single I.C has many transistors, resistors and capacitors along with the associated circuitry. The
I.C was invented by Jack Kilby . This development made computers smaller in size, reliable and
efficient.
IC used
More reliable
Smaller size
Faster
Lesser maintenance
12
Still costly
A.C needed
IBM-360 series
Honeywell-6000 series
IBM-370/168
TDC-316
Fourth Generation
iii. In this generation Time sharing, Real time, Networks, Distributed Operating System were used.
iv. All the Higher level languages like C and C++, DBASE etc. were used in this generation.
13
Very cheap
Use of PC's
Pipeline processing
No A.C. needed
DEC 10
STAR 1000
CRAY-1(Super Computer)
Fifth Generation
ii. In the fifth generation, the VLSI technology became ULSI (Ultra Large Scale Integration)
technology, resulting in the production of microprocessor chips having ten million electronic
components.
iii. This generation is based on parallel processing hardware and AI (Artificial Intelligence) software.
iv. AI is an emerging branch in computer science, which interprets means and method of making
computers think like human beings.
v. All the Higher level languages like C and C++, Java, .Net etc. are used in
this generation.
14
AI includes:
Robotics
Neural networks
Game Playing
ULSI technology
Availability of very powerful and compact computers at cheaper rates Some computer types of
Desktop
Laptop
NoteBook
UltraBook
ChromeBook
15
1.5 Basic Computer Organization:
The architecture of the computers has not changed but the technology used to accomplish those
operations may vary from one computer to another computer. The basic computer organization remains
the same for all computer systems. In 1950’s, it took a room full of vacuum tubes and equipment to
perform the tasks that are now replaced with a single chip, not bigger than a child’s thumb nail.
Advances in semiconductor technology have reduced the Size of the chip.
Control Unit
Memory Unit
Output unit
Input Unit
Secondary Storage
The block diagram of the digital computer system has the following three units.
1. Input unit
2. Central processing unit
3. Output unit
16
1. Input unit
Computers need data and instructions in order to solve any problem. We need to put the
data and instructions into the computers. The input unit consists of one or more input devices.
There are number of devices that perform the function of input devices. The keyboard of the
computer is one of the most commonly used and standardized input device. Regardless of the
type of input device used in a computer system, all input devices perform the following
functions:
The input unit is used to send information or instructions or commands to the computer. The input
received from the input unit is immediately stored in main memory and the processed. Input may be
processed. Input may be pressing a key in a keyboard or moving of mouse or movement of a joystick.
Following are few of the important input devices which are used in Computer Systems
Keyboard
Mouse
Joy Stick
Light pen
Track Ball
Scanner
Graphic Tablet
Microphone
17
Keyboard
Most common and very popular input device is keyboard. The keyboard helps in inputting the
data to the computer. The layout of the keyboard is like that of traditional typewriter, although there
are some additional keys provided for performing some additional functions.
Keyboards are of two sizes 84 keys or 101/102 keys, but now 104 keys or 108 keys keyboard is
also available for Windows and Internet.
Fig: Keyboard
1 Typing Keys These keys include the letter keys (A-Z) and dig its keys (0-9) which
are generally give same layout as that of typewriters.
3 Function Keys The twelve functions keys are present on the keyboard. These are
arranged in a row along the top of the keyboard. Each function key has
unique meaning and is used for some specific purpose.
4 Control keys These keys provides cursor and screen control. It includes four
directional arrow key. Control keys also include Home, End,Insert,
Delete, Page Up, Page Down, Control(Ctrl), Alternate(Alt),
Escape(Esc).
Special Purpose
5 Keys Keyboard also contains some special purpose keys such as Enter,
Shift, Caps Lock, Num Lock, Space bar, Tab, and Print Screen.
18
Mouse
Mouse is most popular Pointing device. It is a very famous cursor-control device. It is a small
palm size box with a round ball at its base which senses the movement of mouse and sends
corresponding signals to CPU on pressing the buttons. Generally it has two buttons called left and right
button and scroll bar is present at the mid. Mouse can be used to control the position of cursor on
screen, but it cannot be used to enter text into the computer.
Fig: Mouse
Joystick
Joystick is also a pointing device which is used to move cursor position on a monitor screen. It is
a stick having a spherical ball at its both lower and upper ends. The lower spherical ball moves in a
socket. The Joystick can be moved in all four directions.
The function of joystick is similar to that of a mouse. It is mainly used in Computer Aided
Designing (CAD) and playing computer games.
Fig: Joystick
Light Pen
Light pen is a pointing device which is similar to a pen. It is used to select a displayed menu item
or draw pictures on the monitor screen. It consists of a photocell and an optical system placed in a small
tube.
When light pen's tip is moved over the monitor screen and pen button is pressed, its photocell
sensing element detects the screen location and sends the corresponding signal to the CPU.
Track Ball
19
Track ball is an input device that is mostly used in notebook or laptop computer, instead of a
mouse. This is a ball which is half inserted and by moving fingers on ball, pointer can be moved.
Since the whole device is not moved, a track ball requires less space than a mouse. A track ball
comes in various shapes like a ball, a button and a square.
Scanner
Scanner is an input device which works more like a photocopy machine. It is used when
some information is available on a paper and it is to be transferred to the hard disc of the
computer for further manipulation.
Scanner captures images from the source which are then converted into the digital form that
can be stored on the disc. These images can be edited before they are printed.
Fig: Scanner
Digitizer
Digitizer is an input device which converts analog information into a digital form. Digitizer can
convert a signal from the television camera into a series of numbers that could be stored in a
computer. They can be used by the computer to create a picture of whatever the camera had been
pointed at. Digitizer is also known as Tablet or Graphics Tablet because it converts graphics and
pictorial data into binary inputs. A graphic tablet as digitizer is used for doing fine works of drawing and
images manipulation applications.
Fig: Digitizer
20
Microphone
Microphone is an input device to input sound that is then stored in dig ital form. The
microphone is used for various applications like adding sound to a multimedia presentation or for mixing
music.
Fig: MicroPhone
MICR input device is generally used in banks because of a large number of cheques to be
processed every day. The bank's code number and cheque number are printed on the cheques with a
special type of ink that contains particles of magnetic material that are machine readable.
This reading process is called Magnetic Ink Character Recognition(MICR). The main
advantages of MICR are that it is fast and less error prone.
OCR is an input device used to read a printed text. OCR scans text optically character by
character, converts them into a machine readable code and stores the text on the system memory.
21
Bar Code Readers
Bar Code Reader is a device used for reading bar coded data (data in form of light and dark
lines). Bar coded data is generally used in labelling goods, numbering the books etc. It may be a hand
held scanner or may be embedded in a stationary scanner.
Bar Code Reader scans a bar code image, converts it into an alphanumeric value which is
then fed to the computer to which bar code reader is connected.
OMR is a special type of optical scanner used to recognize the type of mark made by pen or
pencil. It is used where one out of a few alternatives is to be selected and marked. It is specially used
for checking the answer sheets of examinations having multiple choice questions.
Control unit
Arithmetic and logical unit (ALU)
Memory unit
Secondary storage devices.
22
(i) Control unit
The control unit instructs the computer how to carry out program instructions. It directs the
flow of data between memory and arithmetic logical unit. It controls and coordinates the entire
computer system.
The control unit controls all other parts of the computer. The input unit does not know when to
receive data and where to put the data in the storage unit after receiving it. The control unit gives the
necessary instructions to the input unit, the control unit instructs the input unit where to store the data
after receiving it from user. In the same way, it controls the flow of data and instructions from the
storage unit to ALU. It also controls the flow of the results from the ALU to the storage unit. The control
unit also controls what should be sent to the output unit.
Arithmetic and logical unit performs all the arithmetic and logical operations, arithmetic
operations like addition, subtraction, multiplication and logical operations such as comparisons.
All calculations are performed in the arithmetic and logical unit (ALU) of the computer. ALU also
does comparisons and takes decision. Whenever any calculation has to be done, the control unit
transfers the required data from the storage unit to the ALU.
Memory unit is the part of computer which holds data for processing and other information. It
also called as main memory. It is a temporary storage (volatile). The values stored in the processor with
the help of the many register like accumulator, base register. This registers store the value at the time of
calculation.
The secondary storage is used like an archive. It may store several programs, documents, database,
etc. The program that you want to run on the computer is first transferred to the primary memory
before it can run. The secondary memory is slower than the primary memory. Some of the commonly
used secondary memory devices are hard disk, compact disk (CD), digital video disk (DVD). It is the
permanent storage; the data stored in this storage will not be erased when the power is lost. It is a non-
volatile memory.
23
3. Output unit
These devices used to get the response or result from the processor. Output unit is the
communication between the user and the computer. The output unit of a computer provides the
information and results of a computation to the outside world. Commonly used output devices are
printer, plotter, and monitor.
Following are few of the important output devices which are used in Computer Systems
Monitors
Graphic Plotter
Printer
Monitors
Monitor commonly called as Visual Display Unit (VDU) is the main output device of a
computer. It forms images from tiny dots, called pixels, that are arranged in a rectangular form. The
sharpness of the image depends upon the no. of the pixels.
In the CRT display is made up of small picture elements called pixels for short. The smaller the
pixels, the better the image clarity, or resolution. It takes more than one illuminated pixel to form
whole character, such as the letter e in the word help.
A finite number of character can be displayed on a screen at once. The screen can be
divided into a series of character boxes - fixed location on the screen where a standard character
can be placed.
The most screens are capable of displaying 80 characters of data horizontally and 25 lines
vertically. There are some disadvantage of CRT
Large in Size
High Power consumption
24
Flat-Panel Display Monitor
The flat-panel display refers to a class of video devices that have reduced volume, weight and
power requirement compare to the CRT. You can hang them on walls or wear them on your wrists.
Current uses for flat-panel displays include calculators, videogames, monitors, laptop computer,
graphics display.
Emissive Displays - The emissive displays are devices that convert electrical energy into
light. Example are plasma panel and LED (Light-Emitting Diodes).
Non-Emissive Displays - The Non-emissive displays use optical effects to convert sunlight or
light from some other source into graphics patterns. Example is LCD (Liquid-Crystal Device)
Printers
Printer is the most important output device, which is used to print information on paper.
Impact Printers
Non-Impact Printers
Impact Printers
The printers that print the characters by striking against the ribbon and onto the paper are
called impact printers.
25
Character printers
Line printers
Character Printers:
Daisy Wheel
In the market one of the most popular printer is Dot Matrix Printer because of their ease of
printing features and economical price. Each character printed is in form of pattern of Dot's and head
consists of a Matrix of Pins of size(5*7, 7*9, 9*7 or 9*9) which comes out to form a character that is
why it is called Dot Matrix Printer.
Advantages
Inexpensive
Widely Used
26
Daisy Wheel
Head is lying on a wheel and Pins corresponding to characters are like petals of Daisy (flower name) that
is why it is called Daisy Wheel Printer. These printers are generally used for word-processing in offices
which require a few letters to be send here and there with very nice quality representation.
Advantages
Better quality
Disadvantages
Noisy
Line Printers
Drum Printer
Chain Printer
27
Drum Printer
This printer is like a drum in shape so it called drum printer. The surface of drum is divided into
number of tracks. Total tracks are equal to size of paper i.e for a paper width of 132 characters, Drum
will have 132 tracks. A character set is embossed on track. The different characters sets are available in
market 48 character set, 64 and 96 characters set. One rotation of drum prints one line. Drum Printers
are fast in speed and speed in between 300 to 2000 lines per minute.
Advantages
Disadvantages
Very expensive
Characters fonts cannot be changed
Chain Printer
In this printer chain of character sets are used so it called Chain Printers. A standard character set may
have 48, 64, 96 characters.
Advantages
Disadvantages
Noisy
Non-impact Printers
The printers that print the characters without striking against the ribbon and onto the paper are
called Non-impact Printers. These printers print a complete page at a time, also called as Page
Printers.
Laser Printers
Inkjet Printers
28
Characteristics of Non-impact Printers
High quality.
Laser Printers
These are non-impact page printers. They use laser lights to produces the dots needed to form the
characters to be printed on a page.
Advantages
Disadvantage
Expensive.
29
Inkjet Printers
Inkjet printers are non-impact character printers based on a relatively new technology. They
print characters by spraying small drops of ink onto paper. Inkjet printers produce high quality output
with presentable features.
They make less noise because no hammering is done and these have many styles of printing
modes available. Colour printing is also possible. Some models of Inkjet printers can produce multiple
copies of printing also.
Advantages
More reliable
Disadvantages
30
2 Types of computers
The computers come in many sizes and capabilities. It can be classified into the following based on
hardware, utility, size and capacity.
Analog Computer
Analog is Greek word which means similar. So in analog computes, any two quantities
are measured by electrical voltage or current. The analog computer operates by measuring
instead of counting. The analog computer works on the supply of continuous electrical signals.
The display is also continuous and its output is in the form of graphs. Today analog computers
are obsolete.
31
Digital computer
Hybrid computer
In hybrid computer, an attempt is made to combine the qualities of both analog and
digital computer. In a hybrid computer, the measuring functions are performed by the analog
way while control and logic functions are digital in nature. Weather-monitoring system and
devices used in intensive care units of the hospitals are examples of hybrid computer.
32
These are designed and constructed to cater to almost all the needs of the society. They can
perform various operations. They are able to perform according to the programs created to
meet different needs.
These can be used for a variety of tasks form financial accounting to mathematical calculations,
form designing textile prints to controlling machinery. They are also flexible and can be used to
work on business and scientific problems.
Based on size and capacity, computers are classified into the following:
1. Micro computer
2. Mini computer
3. Mainframe computer
4. Super computer
Micro computers
In view of its small size and the use of Microprocessor, this computer is called Micro computer.
A microprocessor is a processor whose components namely Input, Output and CPU are on a single
integrated-circuit chip. It is a low-cost and the word length of a microcomputer lies in the range of 8 to
32 bits.
Fig:Micro computer
They are normally single-microprocessor, single-user systems designed for performing basic
operations like general purpose calculations, industrial control, instrumentation, educational, training,
33
small business applications, home applications, commercial equipment control, watches, fuel injection
of a car, office automation, playing games etc.
Mini computer
Minicomputer is larger than the micro computers and is more powerful in terms of processing power.
Minicomputer is mainly multiprocessor systems where many users simultaneously work on the systems.
Minicomputer possesses greater storage capacity and larger memories as compared to microcomputer.
Their word length is 32 bits.
Fig:Mini computer
Mainframe computers
Mainframe computer are larger, faster and more expensive than other general purpose
computers. These are used to handle huge volumes of data. Their word length may be 48 to 64
bit memory capacity. These computers even possess and work with more than one processor at
the same time.
Fig:Mainframe computer
Super computers
Super computers are the most powerful of all computers. They have a high processing speed.
Their processing speed lies in the range of 400 to 10,000 MIPS. Word length 64 to 96 bit. It is
specially designed to maximize the number of FLOPS. Their FLOPS rating is usually more than 1
gigaflop per second.
34
Fig:Super computer
However with the rapidly developing technology, such classifications are no more relevant.
After a few months of introduction of a new computer in the marker, the new models of computers are
rapidly introduced with less cost and higher performance than the earliest. Thus, today’s computers are
classified based on their mode of use.
Palmtop pc’s
The palmtop computers accept handwritten inputs using an electronic pen, which can
be used to write on a palmtop’s screen. These have small disk storage and can be connected to
a wireless network. One has to train the system on the user’s handwriting before it can be used.
A palmtop computer has also facilities to be used as a mobile phone, fax and E-mail machine.
Fig:Laptop pc’s
Fig:Personal computer
Work stations
It is a powerful desktop computer designed to meet the computing needs of users or
clients, with better processing, high storage capacity and with efficient and effective graphics
display facility. The workstation looks similar to a personal computer and can be used by only
one person at a time through the local area network.
Fig:Work station
36
Fig:Client server
Computers come in many different forms. They range from massive, multipurpose mainframes
and supercomputers to desktop-size personal computers. Between these extremes is a vast middle
ground of minicomputers and workstations. Large minicomputers approach mainframes in computing
power, whereas workstations are powerful personal computers.
Mainframes and large minicomputers are used by many businesses, universities, hospitals and
government agencies to carry out sophisticated scientific and business calculations. These computers
are expensive and many require a sizeable staff of supporting personnel and a special, carefully
controlled environment.
Personal computers, on the other hand, are small and inexpensive. In fact, portable, battery-
powered “laptop” computers weighing less cost. Personal computers are used extensively in most
schools and businesses and they are rapidly becoming common household items. Many students use
personal computers when learning program with C.
The small size and low cost, modern personal computers approach minicomputers in computing
power. They are now used for many applications that formerly required larger, more expensive
computers. Their performance continues to improve dramatically as their cost continues to drop. The
design of a personal computer permits a high level of interaction between the user and the computer.
Most applications are specifically designed to take advantage of this feature thus providing the skilled
user with a wide variety of creative tools to write, draw or carry out numerical computations.
37
3. Number systems
Introduction
A number is required for counting or to express the amount of some quantity. It consists of
group of symbols called digits, which are arranged in a definite manner. There can be many groups of
symbols called digits, which are arranged in a definite manner. There can be many ways in which the
digits can be arranged to form a number. This gives rise to what we call a number system. Each such
system deals with a different set of digits to form a number belonging to that system.
The most widely adopted system is the decimal number system which has ten digits (0,1,2,3
…9), the octal system has eight digits (0,1,2,3…, 7), the hexadecimal system has sixteen digits (0,1,2,3…
,9,A,B,C,D,E,F), the binary number system has only two (0,1), symbols.
The number of digits in a system is called ‘radix’ or ‘base’. So that decimal system may be called as radix-
10 system, the binary system as radix-2 system.
NUMBER SYSTEMS
Binary Decimal Octal Hexadecimal
0000 00 0 0
0001 01 1 1
0010 02 2 2
0011 03 3 3
0100 04 4 4
0101 05 5 5
0110 06 6 6
0111 07 7 7
1000 08 10 8
1001 09 11 9
1010 10 12 A
1011 11 13 B
1100 12 14 C
1101 13 15 D
1110 14 16 E
1111 15 17 F
38
3.1 Conversion of number system
Usually the numbers are expressed in decimal systems, because we are using decimal number
system in our daily life since decades. Thus any number from one number system can be represented to
any other number system. Since the input and the output values are to be decimal, and the computer
uses other number systems the computer professionals are required to convert decimal number system
to other number and in other number system to decimal.
1. Decimal to binary
2. Binary to decimal
3. Decimal to octal
4. Decimal to Hexadecimal
5. Octal to decimal
6. Octal to binary
7. Binary to octal
8. Hexadecimal to binary
9. Binary to hexadecimal
1. Conversions of Decimal to Binary- The method that is used for converting of decimals into
binary is known as the remainder method. We use the following steps in getting the binary
number-
(a) Divide the decimal number by 2.
(b) Write the remainder (which is either 0 or 1) at the right most position.
(c) Repeat the process of dividing by 2 until the quotient is 0 and keep writing the
remainder after each step of division.
(d) Write the remainders in reverse order.
39
Example- Convert (45)10 into binary number system.
2 45 Remainder
2 22 1
2 11 0
2 5 1
2 2 1
2 1 0
0 1
Conversions of Decimal Fractions to Binary Fractions- For converting decimal fractions into binary
fractions, we use multiplication. Instead of looking for a remainder we look for an integer. The following
steps are used in getting the binary fractions-
(a) Multiply the decimal fraction by 2.
(b) If a non-zero integer is generated, record the non-zero integer otherwise record 0.
(c) Remove the non-zero integer and repeat the above steps till the fraction value
becomes 0.
(d) Write down the number according to the occurrence.
Example- Find the binary equivalent of (0.75)10.
Remark- If the conversion is not ended and still continuing; we write the
approximation in 16 bits.
40
0.8 × 2 = 1.6 1
0.6 × 2 = 1.2 1
0.2 × 2 = 0.4 0
0.4 × 2 = 0.8 0
0.8 × 2 = 1.6 1
0.6 × 2 = 1.2 1
0.2 × 2 = 0.4 0
0.4 × 2 = 0.8 0
0.8 × 2 = 1.6 1
0.6 × 2 = 1.2 1
0.2 × 2 = 0.4 0
0.4 × 2 = 0.8 0
0.8 × 2 = 1.6 1
Thus (0.9)10 = (0.111001100110011001)2.
Binary 1 0 1 1 0 1
Number
5 4 3 2 1 0
Wt. of each 2 2 2 2 2 2
Bit
5 4 3 2 0
Weighted 1×2 0×2 1×2 1×2 0×2 1×2
Value
Solved 32 0 8 4 0 1
Multiplication
5 4 3 2 0
Thus (101101)2= 1 × 2 + 0 × 2 + 1 × 2 + 1 × 2 + 0 × 2 + 1 × 2 .
= 32 + 0 + 8 + 4 + 0 + 1
= 45
Conversions of Binary Fractions to Decimal Fractions – The conversions of binary fractions to the
decimal fractions is similar to conversion of binary numbers to decimal numbers. Here, instead of a
decimal point we have a binary point. The exponential expressions (or weight of the bits) of each
-1 -2
fractional placeholder is 2 , 2 ………
41
Example- Convert (101101.11)2 into decimal number system.
Binary 1 0 1 1 0 1 1 1
Number
5 4 3 2 1 0
Wt. of each 2 2 2 2 2 2 2-1 2-2
Bit
5 4 3 2 0 -1 -2
Weighted 1×2 0×2 1×2 1×2 0×2 1×2 1×2 1×2
Value
Solved 32 0 8 4 0 1 0.5 0.25
Multiplication
3. Conversion of Decimal to Octal- In converting decimal to octal, we follow the same process of
converting decimal to binary. Instead of dividing the number by 2, we divide the number by 8.
8 45 Remainder
8 5 5
8 0 5
Conversions of Decimal Fractions to Octal Fractions – We follow the same steps of conversions of
decimal fractions to binary fractions. Here we multiply the fraction by 8 instead of 2.
42
Example- Convert (45)10 into hexadecimal.
16 45 Remainder
16 2 D
16 0 2
(0.C)16.
5. Conversions of Octal to Decimal- We follow the same steps of conversion of binary to decimal.
th n-1 n-1
The only difference is that here weight of n bit is 8 instead of 2 .
Example- Convert (55)8 into decimal number system.
Octal 5 5
Number
1 0
Wt. of each 8 8
Bit
0
Weighted 5× 8 5×8
Value
Solved 40 5
Multiplication
Thus (55)8 = 40 + 5.
= 45
Conversions of Octal Fractions to Decimal Fractions- The weight of the bit of the fraction
-1 -2
placeholder is 8 , 8 ………. We follow the same steps of conversion of binary fractions to decimal
fractions.
43
Example- Convert (55.6)8 into decimal number system.
Octal 5 5 6
Number
1 0
Wt. of each 8 8 8-1
Bit
0 -1
Weighted 5×8 5×8 6×8
Value
Solved 40 5 0.75
Multiplication
Thus (55.6)8= 40 + 5 + 0.75 = 45.75
6. Conversions of Octal to Binary- We use the following steps in converting octal to binary-
(a) Convert each octal digit into 3-bit binary equivalent.
(b) Combine the 3-bit section by removing the spaces to get the binary number.
Octal 5 5
Number
Binary 101 101
Number
Octal 4 5 6
Number
Binary 100 101 110
Number
Conversions of Octal Fractions to Binary Fractions- We follow the same steps of conversion of
octal to binary.
44
7.Conversions of Binary to Octal- We use the following steps in converting binary to octal-
(a) Break the number into 3-bit sections starting from LSB to MSB.
(b) If we do not have sufficient bits in grouping of 3-bits, we add zeros to the left of MSB so
that all the groups have proper 3-bit number.
(c) Write the 3-bit binary number to its octal equivalent.
45
Example- Convert (2D)16 into binary.
Hexadecimal 2 D(=13)
Number
Binary 0010 1101
Number
Conversions of Hexadecimal Fractions to Binary Fractions -We use the same steps of hexadecimal
to binary conversion.
Example- Convert (2D.C)16 into binary.
46
Example- Convert (101101.11)2 into hexadecimal.
Hexadecimal 2 D(=13)
Number
1 0
Wt. of each 16 16
Bit
0
Weighted 2 × 16 13 × 16
Value
Solved 32 13
Multiplication
47
11.Conversions of Octal to Hexadecimal- The conversion involves the following steps-
(a) Convert each octal digit to 3 –bit binary form.
(b) Combine all the 3-bit binary numbers.
(c) Group them in 4-bit binary form by starting from MSB to LSB.
(d) Convert these 4-bit blocks into their hexadecimal symbols.
Octal 5 5
Number
Binary 101 101
Number
Octal 5 5 6
Number
Binary 101 101 110
Number
48
12.Conversions of Hexadecimal to Octal- We convert each hexadecimal digit in binary. Combine
all the binary numbers. Again group them into 3-bit form. Convert the 3-bit block in octal.
Hexadecimal 2 D(=13)
Number
Binary 0010 1101
Number
Students will acquire knowledge on Number Systems because number systems are the base of
computers. All the Arithmetic calculations are the base of Number systems only. They will get
knowledge to convert decimal to binary, octal and hexa decimal and viceversa.
49
Exercises
Questions:
50
5 Computer Languages
Language is the communication medium, the computer languages are used to communicate
with the computer. These are the communication media between the user and the computer. The
computer languages are formed with the group of instruction often called as programs. The computer
languages are divided as follows.
Language
Classification of languages
The machine language is formed with the help of binary digits. This is also called as the low level
language. This language is the collection of instruction using binary digits 0’s and 1’s. There are as
named as the machine can directly understand the programs.
1. Machine dependent
2. Writing a Programming is very difficult
3. Very difficult to find an error.
0100
1001
_____________
1101
______________
51
5.2 Assembly Language
This language is also very difficult and needs a lot of practice to master it because very
small. English support is given to this language. The language mainly helps in compiler
orientations. The instructions of the Assembly language will also be converted to machine
codes by language translator to be executed by the computer.
ii) Since it is machine dependent therefore programmer should have the knowledge of the
hardware also.
52
High level computer languages give formats close to English language and the purpose
of developing high level languages is to enable people to write programs easily and in their own
native language environment (English). High-level languages are basically symbolic languages
that use English words and/or mathematical symbols rather than mnemonic codes. Each
instruction in the high level language is translated into many machine language instructions
thus showing one-to-many translation.
Many languages have been developed for achieving different variety of tasks, some are fairly
specialized others are quite general purpose.
These languages are oriented towards the computational procedures for solving
mathematical and statistical problem
Examples are
53
These languages emphasize their capabilities for maintaining data processing procedures
and files handling problems. Examples are:
3. String and List Processing: These are used for string manipulation including search for
patterns, inserting and deleting characters. Examples are:
C++
Java
Visual Basic
Visual Java
Visual C
i) It is easier to learn.
ii) They require less time to write.
iii)They are easier to maintain.
iv) Problem oriented rather than 'machine' based.
v) Program written in a high-level language can be translated into many machine
language and therefore can run on any computer for which there exists an
appropriate translator.
vi) It is independent of the machine on which it is used i.e., Programs developed in high
level language can be run on any Computer.
54
vii) User-friendly.
viii) Similar to English with vocabulary of words and symbols.
http://www.ustudy.in
Summary:
The Types of Computer Languages elaborated about its importance and its advantages and
disadvantages.
Exercises
Questions:
C 1.Explain about the computer languages and its advantages and disadvantages in detail.
55
6.1 Algorithm
It is defined as a sequence of instructions designed in such a way that if the instructions are
executed in the specified sequence, the desired results will be obtained. The algorithm should precise
and unambiguous in practice and the results should obtain after a finite number of steps. An algorithm is
defined if any problem whose solution can be expressed in a list of executable instruction.
Characteristics of algorithms
In order to qualify algorithms is a sequence of instructions, they must possess the following
characteristics:
There are so many methods or logics available to solve the problem individually. All of those
methods logics may not be good, for given problem; there may be so many algorithms not of all
equality. The following are the primary factors that are often used to judge the quality of the algorithm.
1 Time To execute a program, the computer system takes some amount of time. The
lesser is the time required, the better is the algorithm.
4 Sequence The procedure of an algorithm must form in a sequence and some of the
instructions of an algorithm may be repeated in number of times or until a
particular condition is met.
5 Generalized The designed algorithm must solve a single isolated problem and more often
algorithms are desired to handle a range of input data to meet this criteria,
so the algorithms must be generalized.
56
Representation of algorithms
The algorithms can be represented in several ways. Generally the programmers follows one of the
following ways to represent an algorithms:
i) Normal English
ii) Flowchart
iii) Pseudo code
iv) Decision table
v) Program
1 Normal English The algorithm can be easily represented in step by step sequential order in
normal English, such algorithms are easy to understand, write and read.
2 Flow chart The flowchart is a pictorial representation of algorithms, the sequential steps
in an algorithm can be represented as a flowchart using the standard
symbols.
3 Pseudo code The flowcharts are only one of the possible format decision tools. Whereas
pseudo code is also a formal design tools and is very well with the rules of
structured design and programming.
4 Decision table A decision table helps a lot in designing a specific segment of design. It
provides another way to look at a complex, nested selection to help clarify
the conditions to be tested and how those conditions should be nested to
arrive at the proper actions.
5 Program The algorithms can be implemented as a program using any high level
language that becomes a program.
A sample algorithm
Write an algorithm to calculate and print the total number of students selected in various group, using
the following criteria. In a school there are 100 student appeared for examination. Based upon the
student marks who secure greater than 70% as first class, greater than 60% as second class, and greater
than 50% as third class and remaining are fail.
57
Algorithm
Step 4: check student mark is greater than 70 or not. If greater than 70 then “first class”.
Step 5: check student mark is greater than 60 and less than 70or not. If so then, “second class”.
Step 6: check student mark is greater than 50 and less than 60 or not. If so then, “third class”.
Step 7: print the result of the student with their names and marks.
6.2 Flowchart
A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the
steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic
representation illustrates a solution to a given problem.
58
More Flowchart Symbols
Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and
arrows show the sequence of the steps, and the relationships among them.
59
Symbol Name Function
60
Symbol Name Function
1. A simple flow chart showing the symbols for decision making statements(Simple IF):
61
2. A simple flow chart showing the symbols for decision making statements(Nested IF):
3. A simple flow chart showing the symbols for decision making statements(SWITCH):
62
4. A simple flow chart showing the symbols for Looping statements(Do-While):
63
EXAMPLES:
Algorithm:
Step 3: Calculate the area and circumference of a circle using the formula.
A=3.14*r*r;
C=2*3.14*r;
Step 5: Exit.
Flowchart:
64
2. ALGORITHM & FLOWCHART TO FIND THE GIVEN NUMBER IS EVEN OR ODD.
Algorithm:
Step 6: Exit
Flowchart:
65
3. ALGORITHM AND FLOWCHART TO PRINT THE NUMBERS FROM 1 to 10.
Algorithm:
Step 4: Print the values upto the value of n by checking with if statement if(n<10).
Step 5:Exit.
Flowchart:
66
Further Reading: List the chapters in Reference books/ web resources
http://www.ustudy.in
Summary:
Students will acquire knowledge about how to write algorithm for a program and they can draw
flowchart for each programs.
Exercises
Questions:
B 1. What is algorithm?
2. Define flowchart.
3. What is the importance of Algorithm?
4. Write an algorithm to find the area of a triangle?
5.Draw a flowchart for printing the biggest among two numbers?
C 1. Explain about importance of algorithm and flowchart. Briefly describe all the symbols
to denote in flowchart..
67
COURSE PLAN
1. Objectives
To study about the Basic of C-Program language
2. Outcomes
3. Pre-requisites
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations
1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation with Online Compiler
2. How to explain the definition and terms with in it
Define the variable, constant, keywords and rules for coming variable, constant keywords
and explain the structure of C Program.
3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
This unit is the basic for writing a C Programming. Understand this unit will be to write a
simple program.
6. What is the final conclusion?
Students will acquire knowledge basic structure of C Language
68
7. How to put it in a nut shell
Variables, Constant, Keywords, Input / output Statement.
8. Important points for understanding / memorizing / make it long lasting
Variable is nothing but name to the memory location and the value may be
changed during the program execution.
Constant is nothing but the value of the variable can’t changed during the
program execution.
Keyword is a reserved word. Can’t used this words as variable name.
Printf / Scanf are input / output statement in C language.
Operator is nothing but it is a symbol to perform various arithmetic Operations.
o Arithmetic Operator
o Assignment Operator.
o Logical Operator
o Ternary / Conditional Operator
o Relational operator
o Special Operator
o Increment / Decrement Operator
9. Questions and cross questions in that topic to make them think beyond the topic.
69
7. Introduction to C
7.2 C standards
C89/C90 standard – First standardized specification for C language was developed by American
National Standards Institute in 1989. C89 and C90 standards refer to the same programming
language.
C99 standard – Next revision was published in 1999 that introduced new futures like advanced
data types and other changes.
C11 standard adds new features to C and library like type generic macros, anonymous
structures, improved Unicode support, atomic operations, multi-threading, and bounds-checked
functions. It also makes some portions of the existing C99 library optional, and improves
compatibility with C++.
70
Embedded C includes features not available in normal C like fixed-point arithmetic, named
address spaces, and basic I/O hardware addressing
Operating systems, C compiler and all UNIX application programs are written in C language
Reliability
Portability
Flexibility
Interactivity
Modularity
Efficiency and Effectiveness
C language is used for developing system applications that forms major portion of operating systems
such as Windows, UNIX and Linux. Below are some examples of C being used.
Database systems
Graphics packages
Word processors
Spread sheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters
71
programs are divided into small are divided into objects structure for programming
programs called functions this language
Prime focus is on the data that is
Prime focus is on functions and
2 being operated and not on the N/A
procedures that operate on data
functions or procedures
Data moves freely around the
Data is hidden and cannot be
3 systems from one function to N/A
accessed by external functions
another
Program structure follows “Top Program structure follows
4 N/A
Down Approach” “Bottom UP Approach”
Examples:
5 C++, JAVA and C# (C sharp) BASIC, COBOL, FORTRAN
C, Pascal, ALGOL and Modula-2
Further Reading:
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com
Summary:
72
Exercises
A B BCPL C++
4. C is a ___ language
73
8 Basic Program
We are going to learn a simple “Hello World” C program in this section. Also, all the below topics are
explained in this section which are the basics of a C program.
C Basic Program:
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf("Hello World! ");
getch();
return 0;
}
Output:
Hello World!
Let’s see all the sections of the above simple C program line by line.
74
8.1 Steps to write C programs and get the output:
Below are the steps to be followed for any C program to create and get the output. This is common
to all C program and there is no exception whether its a very small C program or very large C program.
o If you want to create, compile and execute C programs by your own, you have to install
C compiler in your machine. Then, you can start to execute your own C programs in your
machine.
o You can refer below link for how to install C compiler and compile and execute C
programs in your machine.
o Once C compiler is installed in your machine, you can create, compile and execute C
programs as shown in below link.
Structure of C program is defined by set of rules called protocol, to be followed by programmer while
writing C program. All C programs are having sections/parts which are mentioned below.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
75
Example C program to compare all the sections:
You can compare all the sections of a C program with the below C program.
Output:
76
section throughout the program, can be defined in this section.
Function prototype Function prototype gives many information about a function like return
5
declaration section type, parameter names used inside the function.
Every C program is started from main function and this function contains
6 Main function
two major sections called declaration section and executable section.
User defined User can define their own functions in this section which perform particular
7
function section task as per the user requirement.
printf() and scanf() functions are inbuilt library functions in C which are available in C library by
default. These functions are declared and related macros are defined in “stdio.h” which is a
header file.
We have to include “stdio.h” file as shown in below C program to make use of these printf() and
scanf() library functions.
C printf() function:
o printf() function is used to print the “character, string, float, integer, octal and
hexadecimal values” onto the output screen.
o We use printf() function with %d format specifier to display the value of an integer
variable.
o Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
o To generate a newline,we use “\n” in C printf() statement.
Note:
o C language is case sensitive. For example, printf() and scanf() are different from Printf()
and Scanf(). All characters in printf() and scanf() functions must be in lower case.
1 #include <stdio.h>
2
3 int main()
4 {
5 char ch = 'A';
6 char str[20] = "fresh2refresh.com";
7 float flt = 10.234;
8 int no = 150;
9
10 double dbl = 20.123456;
11 printf("Character is %c \n", ch);
77
12 printf("String is %s \n" , str);
13 printf("Float value is %f \n", flt);
14 printf("Integer value is %d\n" , no);
15
16 printf("Double value is %lf \n", dbl);
17 printf("Octal value is %o \n", no);
18 printf("Hexadecimal value is %x \n", no);
19
20 return 0;
21
22 }
Output:
Character is A
String is
fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
You can see the output with the same data which are placed within the double quotes of printf
statement in the program except
2. C scanf() function:
o scanf() function is used to read character, string, numeric data from keyboard
o Consider below example program where user enters a character. This value is assigned
to the variable “ch” and then displayed.
o Then, user enters a string and this value is assigned to the variable ”str” and then
displayed.
78
Example program for printf() and scanf() functions in C:
1 #include <stdio.h>
2
3 int main()
4 {
5 char ch;
6 char str[100];
7
8 printf("Enter any character \n");
9 scanf("%c", &ch);
10 printf("Entered character is %c \n", ch);
11
12 printf("Enter any string ( upto 100 character ) \n");
13 scanf("%s", &str);
14 printf("Entered string is %s \n", str);
15 }
Output:
o The format specifier %d is used in scanf() statement. So that, the value entered is
received as an integer and %s for string.
o Ampersand is used before variable name “ch” in scanf() statement as &ch.
o It is just like in a pointer which is used to point to the variable. For more information
about how pointer works
Further Reading:
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com
79
Summary:
C is a case sensitive programming language. It means in C printf and Printf will have different
meanings.
C has a free-form line structure. End of each C statement must be marked with a semicolon.
Multiple statements can be one the same line.
White Spaces (ie tab space and space bar ) are ignored.
Statements can continue over multiple lines.
Exercises
A. Objective Type Questions:
1. C language is available for which of the following Operating Systems?
! # ~ ;
B.Questions
80
9.1 C– Tokens and keywords
C tokens, Identifiers and Keywords are the basics in a C program. All are explained in this page with
definition and simple example programs.
9.2 C tokens:
o C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
o Each and every smallest individual units in a C program are known as C tokens.
1 int main()
2{
3 int x, y, total;
4 x = 10, y = 20;
5 total = x + y;
6 Printf (“Total = %d \n”, total);
7}
where,
o main – identifier
o {,}, (,) – delimiter
o int – keyword
o x, y, total – identifier
o main, {, }, (, ), int, x, y, total – tokens
Do you know how to use C token in real time application programs? We have given simple real time
application programs where C token is used. You can refer the below C programs to know how to use C
token in real time program.
81
Real time application C programs for your reference:
9. 3. Identifiers in C language:
82
9.5 C – Constant
C Constants are also like normal variables. But, only difference is, their values can not be
modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
1. Integer Constants in C:
83
2. Real constants in C:
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
84
o Please note that when you try to change constant values after defining in C program, it
will through error.
1 #include <stdio.h>
2
3 void main()
4 {
5 const int height = 100; /*int constant*/
6 const float number = 3.14; /*Real constant*/
7 const char letter = 'A'; /*char constant*/
8 const char letter_sequence[10] = "ABC"; /*string constant*/
9 const char backslash_char = '\?'; /*special char cnst*/
10
11 printf("value of height : %d \n", height );
12 printf("value of number : %f \n", number );
13 printf("value of letter : %c \n", letter );
14 printf("value of letter_sequence : %s \n", letter_sequence);
15 printf("value of backslash_char : %c \n", backslash_char);
16 }
Output:
C1 #include <stdio.h>
2
3 #define height 100
4 #define number 3.14
5 #define letter 'A'
6 #define letter_sequence "ABC"
7 #define backslash_char '\?'
8
9 void main()
10 {
11
12 printf("value of height : %d \n", height );
13 printf("value of number : %f \n", number );
14 printf("value of letter : %c \n", letter );
15 printf("value of letter_sequence : %s \n", letter_sequence);
85
16 printf("value of backslash_char : %c \n", backslash_char);
17
18 }
Output:
Further Reading:
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com
Summary:
In a passage of text, individual words and punctuation marks are called tokens or lexical units. Similarly,
the smallest individual unit in a c program is known as a token or a lexical unit. C tokens can be classified
as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Exercises
A.Objective Type Questions:
1. Which of the following are tokens in C?
86
10 C – Variable
C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
1. Local variable
2. Global variable
3. Environment variable
87
1 #include<stdio.h>
2
3 void test();
4
5 int main()
6 {
7 int m = 22, n = 44;
8 // m, n are local variables of main function
9
10 /*m and n variables are having scope
11 within this main function only.
12 These are not visible to test funtion.*/
13 /* If you try to access a and b in this function,
14 you will get 'a' undeclared and 'b' undeclared
15 error */
16
17 printf("\nvalues : m = %d and n = %d", m, n);
18
19 test();
20
21 }
22
23 void test()
24 {
25 int a = 50, b = 80;
26 // a, b are local variables of test function
27
28 /*a and b variables are having scope
29 within this test function only.
30 These are not visible to main function.*/
31 /* If you try to access m and n in this function,
32 you will get 'm' undeclared and 'n' undeclared
33 error */
34
35 printf("\nvalues : a = %d and b = %d", a, b);
36 }
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80
88
10.4. Example program for global variable in C:
o The scope of global variables will be throughout the program. These variables can be
accessed from anywhere in the program.
o This variable is defined outside the main function. So that, this variable is visible to main
function and all other sub functions.
1 #include<stdio.h>
2
3 void test();
4
5 int m = 22, n = 44;
6 int a = 50, b = 80;
7
8 int main()
9 {
10
11 printf("All variables are accessed from main function");
12
13 printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
14
15 test();
16
17 }
18
19 void test()
20 {
21
22 printf("\n\nAll variables are accessed from" \
23 " test function");
24
25 printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
26 }
Output:
89
Difference between variable declaration & definition in C:
Further Reading:
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com
Summary:
A variable is just a named area of storage that can hold a single value (numeric or character). The C
language demands that you declare the name of each variable that you are going to use and its type, or
class, before you actually try to do anything with it.
Local Variables
Global Variables
Exercises
A.Objective Type Questions:
1. Which of the following are tokens in C?
90
11 C – Data Types
C data types are defined as the data storage format that a variable can store a data to perform a
specific operation.
Data types are used to define a variable before to use in a program.
Size of variable, constant and array are determined by data types.
Note:
91
11.3 Character data type:
1. float
2. double
1. float:
2. double:
Double data type is also same as float data type which allows up-to 10 digits after decimal.
The range for double datatype is from 1E–37 to 1E+37.
sizeof() function in C:
sizeof() function is used to find the memory space allocated for each C data types.
92
1 #include <stdio.h>
2 #include <limits.h>
3
4 int main()
5 {
6
7 int a;
8 char b;
9 float c;
10 double d;
11 printf("Storage size for int data type:%d \n",sizeof(a));
12 printf("Storage size for char data type:%d \n",sizeof(b));
13 printf("Storage size for float data type:%d \n",sizeof(c));
14 printf("Storage size for double data type:%d\n",sizeof(d));
15 return 0;
16 }
Output:
11.5 Modifiers in C:
1. short
2. long
3. signed
4. unsigned
5. long long
93
Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on
the CPU processor (8,16, 32 and 64 bit)
Enum syntax in C:
Enum example in C:
The above enum functionality can also be implemented by “#define” preprocessor directive as
given below. Above enum example is same as given below.
94
#define Jan 20;
#define Feb 21;
#define Mar 22;
1
#include <stdio.h>
2
3
int main()
4
{
5
enum MONTH { Jan = 0, Feb, Mar };
6
7
enum MONTH month = Mar;
8
9
if(month == 0)
10
printf("Value of Jan");
11
else if(month == 1)
12
printf("Month is Feb");
13
if(month == 2)
14
printf("Month is Mar");}
15
Output:
Month is March
Array, pointer, structure and union are called derived data type in C language.
Further Reading:
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com
Summary:
C has a concept of 'data types' which are used to define a variable before its use. The definition of a
variable will assign storage for the variable and define the type of data that will be held in the location.
95
The value of a variable can be changed any time. C has the following basic built-in datatypes.
int
float
double
char
void
Exercises
A.Objective Type Questions:
1. What will be the maximum size of a float variable?
B. Questions:
1. Explain in detail about C-Datatypes.
2. Discuss the following
a. Derived Datatype
b. User defined Datatype
96
12 C – Operators and Expressions
The symbols which are used to perform logical and mathematical operations in a C program are
called C operators.
These C operators join individual constants and variables to form expressions.
Operators, functions, constants and variables are combined together to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant
and A + B * 5 is an expression.
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
97
12.2 C- Arithmetic Operators
Arithmetic Operators in C:
o In this example program, two values “40″ and “20″ are used to perform arithmetic
operations such as addition, subtraction, multiplication, division, modulus and output is
displayed for each operation.
1 #include <stdio.h>
2 int main()
3 {
4 int a=40,b=20, add,sub,mul,div,mod;
5
6 add = a+b;
7 sub = a-b;
8 mul = a*b;
9 div = a/b;
10 mod = a%b;
11
12 printf("Addition of a, b is : %d\n", add);
13 printf("Subtraction of a, b is : %d\n", sub);
14 printf("Multiplication of a, b is : %d\n", mul);
15 printf("Division of a, b is : %d\n", div);
16 printf("Modulus of a, b is : %d\n", mod);
17 }
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
98
12.3 C – Assignment Operators
Assignment operators in C:
o In C programs, values for the variables are assigned using assignment operators.
o For example, if the value “10″ is to be assigned for the variable “sum”, it can be assigned
as “sum = 10;”
o Other assignment operators in C language are given below.
o In this program, values from 0 – 9 are summed up and total “45″ is displayed as output.
o Assignment operators such as “=” and “+=” are used in this program to assign the values
and to sum up the values.
1 # include <stdio.h>
2 int main()
3 {
4 int Total=0,i;
5 for(i=0;i<10;i++)
6 {
7 Total+=i; // This is same as Total = Toatal+i
8 }
9 printf("Total = %d", Total);
10 }
Output:
Total = 45
99
12.4 C – Relational Operators
Relational operators in C:
o Relational operators are used to find the relation between two variables. i.e. to compare
the values of two variables in a C program.
o In this program, relational operator (==) is used to compare 2 values whether they are
equal are not.
o If both values are equal, output is displayed as ” values are equal”. Else, output is
displayed as “values are not equal”.
o Note : double equal sign (==) should be used to compare 2 values. We should not single
equal sign (=).
1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 if (m == n)
6 {
7 printf("m and n are equal");
8 }
9 else
10 {
11 printf("m and n are not equal");
12 }
13 }
Output:
100
12.5 C – Logical Operators
Logical operators in C:
o These operators are used to perform logical operations on the given expressions.
o There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||)
and logical NOT (!).
1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 int o=20,p=30;
6
7 if (m>n && m !=0)
8 {
9 printf("&& Operator : Both conditions are true\n");
10 }
11 if (o>p || p!=20)
12 {
13 printf("|| Operator : Only one condition is true\n");
14 }
15 if (!(m>n && m !=0))
16 {
17 printf("! Operator : Both conditions are true\n");
18 }
19 else
20 {
21 printf("! Operator : Both conditions are true. " \
22 "But, status is inverted as false\n");
23 }
24 }
101
Output:
o In this program, operators (&&, || and !) are used to perform logical operations on the
given expressions.
o && operator – “if clause” becomes true only when both conditions (m>n and m! =0) is
true. Else, it becomes false.
o || Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is
true. It becomes false when none of the condition is true.
o ! Operator – It is used to reverses the state of the operand.
o If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by “!”
operator.
o So, “! (m>n and m! =0)” returns false (0).
102
12.6 C – Bit wise Operators
o These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
o Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
Note:
103
Example program for bit wise operators in C:
o In this example program, bit wise operations are performed as shown above and output
is displayed in decimal format.
1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
5
6 AND_opr = (m&n);
7 OR_opr = (m|n);
8 NOT_opr = (~m);
9 XOR_opr = (m^n);
10
11 printf("AND_opr value = %d\n",AND_opr );
12 printf("OR_opr value = %d\n",OR_opr );
13 printf("NOT_opr value = %d\n",NOT_opr );
14 printf("XOR_opr value = %d\n",XOR_opr );
15 printf("left_shift value = %d\n", m << 1);
16 printf("right_shift value = %d\n", m >> 1);
17 }
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
o Conditional operators return one value if condition is true and returns another value is
condition is false.
o This operator is also called as ternary operator.
o In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal
to if else conditional statements.
104
Example program for conditional/ternary operators in C:
1 #include <stdio.h>
2 int main()
3{
4 int x=1, y ;
5 y = ( x ==1 ? 2 : 0 ) ;
6 printf("x value is %d\n", x);
7 printf("y value is %d", y);
8}
Output:
x value is 1
y value is 2
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator :
++var_name;(or) var_name++;
Decrement operator :
– - var_name; (or) var_name – -;
…
Example:
Increment operator :
++i;i++;
Decrement operator: –-i; i–-;
…
o In this program, value of “i” is incremented one by one from 1 up to 9 using “i++”
operator and output is displayed as “1 2 3 4 5 6 7 8 9”.
105
1 //Example for increment operators
2
3 #include <stdio.h>
4 int main()
5 {
6 int i=1;
7 while(i<10)
8 {
9 printf("%d ",i);
10 i++;
11 }
12 }
Output:
123456789
o In this program, value of “I” is decremented one by one from 20 up to 11 using “i–”
operator and output is displayed as “20 19 18 17 16 15 14 13 12 11”.
Output:
20 19 18 17 16 15 14 13 12 11
106
Difference between pre/post increment & decrement operators in C:
o Below table will explain the difference between pre/post increment and decrement
operators in C.
107
Example program for post – increment operators in C:
1 #include <stdio.h>
2 int main()
3 {
4 int i=0;
5 while(i++ < 5 )
6 {
7 printf("%d ",i);
8 }
9 return 0;
10 }
Output:
12345
o Step 1 : In this program, value of i ”0″ is compared with 5 in while expression.
o Step 2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator.
o Step 3 : Then, this incremented value “1″ is assigned to the variable “i”.
o Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4 5″.
1 #include <stdio.h>
2 int main()
3 {
4 int i=10;
5 while(--i > 5 )
6 {
7 printf("%d ",i);
8 }
9 return 0;
10 }
Output:
9876
108
Example program for post - decrement operators in C:
1 #include <stdio.h>
2 int main()
3 {
4 int i=10;
5 while(i-- > 5 )
6 {
7 printf("%d ",i);
8 }
9 return 0;
10 }
Output:
98765
Special Operators in C:
o In this program, “&” symbol is used to get the address of the variable and “*” symbol is
used to get the value of the variable that the pointer is pointing to. Please refer C –
pointer topic to know more about pointers.
109
1 #include <stdio.h>
2
3 int main()
4 {
5 int *ptr, q;
6 q = 50;
7 /* address of q is assigned to ptr */
8 ptr = &q;
9 /* display q's value using ptr variable */
10 printf("%d", *ptr);
11 return 0;
12 }
Output:
50
o sizeof() operator is used to find the memory space allocated for each C data types.
1 #include <stdio.h>
2 #include <limits.h>
3
4 int main()
5 {
6
7 int a;
8 char b;
9 float c;
10 double d;
11 printf("Storage size for int data type:%d \n",sizeof(a));
12 printf("Storage size for char data type:%d \n",sizeof(b));
13 printf("Storage size for float data type:%d \n",sizeof(c));
14 printf("Storage size for double data type:%d\n",sizeof(d));
15 return 0;
16 }
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
110
Further Reading:
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com
Summary:
Arithmetic Operators
Logical (or Relational) Operators
Bitwise Operators
Assignment Operators
Misc Operators
Exercises
A.Objective Type Questions:
1. Which of the following is an example of compounded assignment statement?
:= .EQ. = ==
B. Questions:
1. Explain in detail about C-Operators with examples.
2. Discuss the following
a. Conditional Operators
b. Increment and Decrement Operators
111
13 C – Decision Control statement
In decision control statements (C if else and nested if), group of statements are executed when
condition is true. If condition is false, then else part statements are executed.
There are 3 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements
o Syntax for each C decision control statements are given in below table with description.
Decision control
Syntax Description
statements
if (condition) In these type of statements, if condition is true, then
if
{ Statements; } respective block of code is executed.
if (condition)
In these type of statements, group of statements are
{ Statement1; Statement2;}
if…else executed when condition is true. If condition is false,
else
then else part statements are executed.
{ Statement3; Statement4; }
if
(condition1){ Statement1; } If condition 1 is false, then condition 2 is checked and
nested if else_if (condition2) statements are executed if it is true. If condition 2 also
{ Statement2; } gets failure, then else part is executed.
else Statement 3;
In “if” control statement, respective block of code is executed when condition is true.
1 int main()
2{
3 int m=40,n=40;
4 if (m == n)
5 {
6 printf("m and n are equal");
7 }
8}
Output:
112
Example program for if else statement in C:
In C if else control statement, group of statements are executed when condition is true. If condition
is false, then else part statements are executed.
1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 if (m == n) {
6 printf("m and n are equal");
7 }
8 else {
9 printf("m and n are not equal");
10 }
11
12 }
Output:
m and n are not equal
o In “nested if” control statement, if condition 1 is false, then condition 2 is checked and
statements are executed if it is true.
o If condition 2 also gets failure, then else part is executed.
1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 if (m>n) {
6 printf("m is greater than n");
7 }
8 else if(m<n) {
9 printf("m is less than n");
10 }
11 else {
12 printf("m is equal to n");
13 }
14 }
Output:
m is greater than n
113
13.2 C – Loop control statements
Loop control statements in C are used to perform looping operations until the given condition is true.
Control comes out of the loop statements once condition becomes false.
1. for
2. while
3. do-while
o Syntax for each C loop control statements are given in below table with description.
In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i); } }
Output:
0123456789
114
Example program (while loop) in C:
In while loop control statement, loop is executed until condition becomes false.
1 #include <stdio.h>
2
3 int main()
4 {
5 int i=3;
6
7 while(i<10)
8 {
9 printf("%d\n",i);
10 i++;
11 }
12
13 }
Output:
3456789
In do..while loop control statement, while loop is executed irrespective of the condition for first time.
Then 2nd time onwards, loop is executed until condition becomes false.
1 #include <stdio.h>
2
3 int main()
4 {
5 int i=1;
6
7 do
8 {
9 printf("Value of i is %d\n",i);
10 i++;
11 }while(i<=4 && i>=2);
12
13 }
Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
115
Difference between while & do while loops in C:
The statements which are used to execute only specific block of statements in a series of blocks are
called case control statements.
1. switch
2. break
3. continue
4. goto
o Switch case statements are used to execute only specific case statements based on the
switch expression.
o Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}
116
Example program for switch..case statement in C:
1 #include <stdio.h>
2
3 int main ()
4 {
5 int value = 3;
6
7 switch(value)
8 {
9 case 1:
10 printf("Value is 1 \n" );
11 break;
12 case 2:
13 printf("Value is 2 \n" );
14 break;
15 case 3:
16 printf("Value is 3 \n" );
17 break;
18 case 4:
19 printf("Value is 4 \n" );
20 break;
21 default :
22 printf("Value is other than 1,2,3,4 \n" );
23 }
24
25 return 0;
26 }
Output:
Value is 3
break statement in C:
o Break statement is used to terminate the while loops, switch case loops and for loops
from the subsequent execution.
o Syntax: break;
117
Example program for break statement in C:
1 #include <stdio.h>
2
3 int main()
4 {
5 int i;
6
7 for(i=0;i<10;i++)
8 {
9 if(i==5)
10 {
11 printf("\nComing out of for loop when i = 5");
12 break;
13 }
14 printf("%d ",i);
15 }
16
17 }
Output:
01234
Coming out of for loop when i = 5
Continue statement in C:
o Continue statement is used to continue the next iteration of for loop, while loop and do-
while loops. So, the remaining statements are skipped within the loop for that
particular iteration.
o Syntax : continue;
1 #include <stdio.h>
2
3 int main()
4 {
5 int i;
6
7 for(i=0;i<10;i++)
8 {
118
9 if(i==5 || i==6)
10 {
11 printf("\nSkipping %d from display using " \
12 "continue statement \n",i);
13 continue;
14 }
15 printf("%d ",i);
16 }
17
18 }
Output:
01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
789
goto statement in C:
o goto statements is used to transfer the normal flow of a program to the specified label
in the program.
o Below is the syntax for goto statement in C.
{
…….
go to label;
…….
…….
LABEL:
statements;
}
1 #include <stdio.h>
2
3 int main()
4 {
5 int i;
6
7 for(i=0;i<10;i++)
8 {
9 if(i==5)
10 {
119
11 printf("\nWe are using goto statement when i = 5");
12 goto HAI;
13 }
14 printf("%d ",i);
15 }
16
17 HAI : printf("\nNow, we are inside label name \"hai\" \n");
18
19 }
Output:
01234
We are using goto statement when i = 5
Now, we are inside label name “hai”
http://www.tutorialspoint.com/cprogramming/
http://www.cprogramming.com
Summary:
Branching
Looping
Branching is deciding what actions to take and looping is deciding how many times to take a certain
action.
Students will acquire knowledge on Decision control statements and loop control statements.
120
Exercises
#include<stdio.h>
void main()
{
char c= 'a';
switch(c)
{
case 65 : printf("inside case A,");
break;
case 97 : printf("inside case a,");
break;
default: printf("inside default case");
break;
}}
#include<stdio.h>
void main()
{
int i=10;
switch(i)
{
case 1: printf(" i=1");
break;
case 10: printf(" i=10");
case 11: printf(" i=11");
break;
case 12: printf(" i=12");
}
}
A. i=10 i=11 i=12
B. i=1 i=10 i=11 i=12
C. i=10 i=11
D. None of the Above
121
COURSE PLAN
1. Objectives
To study about the concepts of Arrays, types of arrays
2. Outcomes
Students will acquire knowledge on array declaration and (runtime & Compilation) initialization.
3. Pre-requisites
Know the concept of basic data types in C Language
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations
1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation
2. How to explain the definition and terms with in it
Explain the memory allocation using Arrays, types of arrays and its initialization concepts
3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
Understand the array concept easily apply the array concept in Array of structure in the
next unit.
122
6. What is the final conclusion?
Students will acquire knowledge on array declaration and (runtime & Compilation) initialization.
7. How to put it in a nut shell
One Dimension Array, Two Dimension Array, Multi Dimension Array, User define
function, Standard Library Function.
8. Important points for understanding / memorizing / make it long lasting
Array is a Group of Similar Data Items. Each Items accessed using the Array
index number
Three Types of Array one, Two, Multi Dimension Array
Function is a group of statement to solve a specific task
Two Types of function 1. User Define function 2. Standard Library Function.
Function call the same function itself is called recursive function.
9. Questions and cross questions in that topic to make them think beyond the topic.
B 1. Define an array
2. What are all the types of array available?
3. Give the syntax of array declaration.
D
1. Define a function?
2. Define formal parameter
3. Define Actual Parameter
Students will acquire knowledge on array declaration and (runtime & Compilation) initialization.
123
14.1 Introduction.
The C Programming language generally uses the variables which are nothing but a name given to
a storage area that our programs can manipulate. Each variable in C has a specific type, which
determines the size and layout of the variable's memory; the range of values that can be stored within
that memory and the limitations are it can’t store more than one value at a time. The limitation of
variables could be avoided by using the arrays.
Arrays.
C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows,
Syntax
<type> <array Name> [ array Size ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 10-element array called balance of
type double, use this statement:
double balance[10];
124
14.3. Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
The number of values between braces { } cannot be larger than the number of elements that we declare
for the array between square brackets [ ].
Following is the pictorial representation of the same array we discussed above:
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example:
The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example which will use all the above mentioned three concepts viz. declaration,
assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
} 125
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];
126
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional
array can be think as a table which will have x number of rows and y number of columns. A 2-
dimentional array a, which contains three rows and four columns can be shown as below:
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in ‘a’.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
127
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return
When 0;
the above code is compiled and executed, it produces the following result:
}
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that most
of the arrays you create will be of one or two dimensions.
14.6.Passing Arrays as Function Arguments
If you want to pass a single-dimension array as an argument in a function, you would have to declare
function formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received. Similar
way you can pass multi-dimensional array as formal parameters.
128
Way-1
Formal parameters as a pointer as follows. You will study what is pointer in next chapter.
void myFunction(int *param)
{
.
.
.
}
Way-2
Way-3
Formal parameters as an unsized array as follows:
void myFunction(int param[])
{
.
.
.
}
Example
Now, consider the following function, which will take an array as an argument along with another
argument and based on the passed arguments, it will return average of the numbers passed through the
array as follows:
129
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
When the above code is compiled together and executed, it produces the following result:
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C
performs no bounds checking for the formal parameters.
Return array from function
C programming language does not allow to return an entire array as an argument to a function.
However, you can return a pointer to an array by specifying the array's name without an index. You will
130
study pointer in next chapter so you can skip this chapter until you understand the concept of Pointers
in C.
If you want to return a single-dimension array from a function, you would have to declare a function
returning a pointer as in the following example:
int * myFunction()
{
}
Second point to remember is that C does not advocate to return the address of a local variable to
outside of the function so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an
array and call this function as follows:
#include <stdio.h>
/* function to generate and return random numbers */
int * getRandom( )
{
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i)
{
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main ()
{
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ )
{
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
131
15. Functions in C.
15.1. Introduction
Function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
Functions
The C standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one memory location
to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure, etc.
Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
132
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the
function does.
Example
Following is the source code for a function called max(). This function takes two parameters num1 and
num2 and returns the maximum between the two:
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is
also valid declaration:
int max(int, int);
133
Function declaration is required when you define a function in one source file and you call that function
in another file. In such case you should declare the function at the top of the file calling the function.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
While running final executable, it would produce the following result:
Max value is : 200
134
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
15.5 Function call by value
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter inside
the function have no effect on the argument.
By default, C programming language uses call by value method to pass arguments. In general, this
means that code within a function cannot alter the arguments used to call the function. Consider the
function swap() definition as follows.
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0; 135
}
Let us put above code in a single C file, compile and execute it, it will produce the following result:
Before swap, value of a :100
Before swap, value of b :200
Which shows that there is no change in the values though they had been changed inside the function.
15.6 Function call by reference
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions just like any other value.
So accordingly you need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to by its arguments.
136
Let us call the function swap() by passing values by reference as in the following example:
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Let us put above code in a single C file, compile and execute it, it will produce the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
Which shows that there is no change in the values though they had been changed inside the function.
Summary:
137
6.2. Recursive function
Recursion is the process of repeating items in a self-similar way. Same applies in programming
languages as well where if a programming allows you to call a function inside the same function that is
called recursive call of the function as follows.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go in
infinite loop.
Recursive function are very useful to solve many mathematical problems like to calculate factorial of a
number, generating Fibonacci series, etc.
Number Factorial
Following is an example, which calculates factorial for a given number using a recursive function:
#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
138
When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016
Fibonacci Series
Following is another example, which generates Fibonacci series for a given number using a
recursive function:
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
0 1 1 2 3 5 8 13 21 34
139
COURSE PLAN
1. Objectives
To study about how to create & use a Structures for heterogeneous data items
2. Outcomes
Students will acquire knowledge on structure and array of structure in C Language
3. Pre-requisites
Knowledge of Data types, Array and Function.
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations
Not Applicable
1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation
2. How to explain the definition and terms with in it
Explain the concept of Array and compare with Structure variables.
3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
Not Applicable
6. What is the final conclusion?
Students will acquire knowledge on structure and array of structure in C Language and Know
the various string Operations in C Language.
140
7. How to put it in a nut shell
8. Important points for understanding / memorizing / make it long lasting
Structure is a group of Dissimilar items.
String is a Group of Character
Various String functions are a) strlen() b) strcmp() c)strcat d)strlwr e)strupr() f) strrev()
9. Questions and cross questions in that topic to make them think beyond the topic.
B 1. What is structure?
2. What is different between structure & array?
3. Uses of structure
4. Write the program for Book information storing structure declaration
C 1. Write the program for 100 Books information insertion & displaying using structure
2. Write the program for student information details using structure
D 1. Union is a ______________item:
To study about how to create & use a Structures for heterogeneous data items add to the
clarity of the program
141
Array(Unit III) handle only all ints, or all floats or all chars at a time. In fact when we handle real
world data, we don’t usually deal with little atoms of information by themselves—things like
integers, characters and such. Instead we deal with entities that are collections of things, each thing
having its own attributes, just as the entity we call a ‘book’ is a collection of things such as title,
author, call number, publisher, number of pages, date of publication, etc. As you can see all this
data is dissimilar, for example author is a string, whereas number of pages is an integer. For dealing
with such collections, C provides a data type called ‘structure’. A structure gathers together,
different atoms of information that comprise a given entity.
17. Structures
Introduction
Data type is the type of the data, that are going to access within the program. ‘C’ Supports different data
types, each data type may have predefined memory requirement and storage representation.
information and how arrays can hold a number of pieces of information of the same data type.
These two data types can handle a great variety of situations. But quite often we deal with entities that
are collection of dissimilar data types.
Table 4.1.1
INFORMATIONS DATA TYPE
NAME Character Array
BOOK (char [100])
PRICE float
NUMBER OF PAGE int
Construct individual arrays, one for storing names, another for storing prices and still another
for storing number of pages.
Table 4.1.2
142
First Approach Second Approach
This approach no doubt allows you to store A structure contains a number of data types
names, prices and number of pages. But as you grouped together. These data types may or may
must have realized, it is an unwieldy approach
not be of the same type
that obscures the fact that you are dealing with
a group of characteristics related to a single
entity
main( ) main( )
{ {
char name[3] ; struct book
float price[3] ; {
int pages[3], i ; char name ;
printf ( "\nEnter names, prices and no. of pages float price ;
of 3 books\n" ) ; int pages ;
for ( i = 0 ; i <= 2 ; i++ ) };
scanf ( "%c %f %d", &name[i], &price[i], struct book b1, b2, b3 ;
&pages[i] ); printf ( "\nEnter names, prices & no. of pages of 3
printf ( "\nAnd this is what you entered\n" ) ; books\n" ) ;
for ( i = 0 ; i <= 2 ; i++ ) scanf ( "%c %f %d", &b1.name, &b1.price,
printf ( "%c %f %d\n", name[i], price[i], pages[i] &b1.pages ) ;
); scanf ( "%c %f %d", &b2.name, &b2.price,
} &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price,
&b3.pages ) ;
printf ( "\nAnd this is what you entered" ) ;
printf ( "\n%c %f %d", b1.name, b1.price, b1.pages
);
printf ( "\n%c %f %d", b2.name, b2.price, b2.pages
);
printf ( "\n%c %f %d", b3.name, b3.price, b3.pages
);
}
A 100.00 354
C 256.50 682
F 233.70 512
143
A 100.000000 354
C 256.500000 682
F 233.700000 512
Declaring a Structure
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
};
struct book
char name ;
float price ;
int pages ;
};
This statement defines a new data type called struct book. Each variable of this data type
will consist of a character variable called name, a float variable called price and an integer variable called
pages
144
Need to sets aside space in memory in a structure by using creating
It makes available space to hold all the elements in the structure for Table 4.1.2
name is 1 byte, price is 4 bytes, pages is 2 bytes, So total 7 bytes to allocate for b1, similarly s2, s3 also.
Table 4.1.2 structure variable contains 7 bytes each.
Table 5.1.3
{ { {
It is important to understand that a structure type declaration does not tell the compiler to reserve
any space in memory. All a structure declaration does is, it defines the ‘form’ of the structure.
Usually structure type declaration appears at the top of the source code file, before any variables or
functions are defined
Access individual elements of use a dot (.) operator. So to refer to Table 4.1.2 of the structure defined
in our sample program we have to use,
b1.pages
145
Similarly, to refer to price we would use,
b1.price
Note that before the dot there must always be a structure variable and after the dot there must always
be a structure element.
Whatever be the elements of a structure, they are always stored in contiguous memory locations. The
following program would illustrate this:
Table 4.1.4
/* Memory map of structure elements */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
printf ( "\nAddress of price = %u", &b1.price ) ;
146
17.2 Array of Structures
In our sample program, to store data of 100 books we would be required to use 100
different structure variables from b1 to b100, which is definitely not very convenient. A better approach
would be to use an array of structures. Following program shows how to use an array of structures.
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b[100] ;
int i ;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "\nEnter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}
for ( i = 0 ; i <= 99 ; i++ )
printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
}
linkfloat( )
{
float a = 0, *b ;
b = &a ; /* cause emulator to be linked */
a = *b ; /* suppress the warning - variable not used */
}
147
real life cannot be handled using arrays, therefore created a new data type called structure. But even
using structures programming convenience could not be achieved, because a lot of variables (b1 to b100
for storing data about hundred books) needed to be handled. Therefore he allowed us to create an array
of structures; an array of similar data types which themselves are a collection of dissimilar data types.
Hats off to the genius!
(d) In an array of structures all elements of the array are stored in adjacent memory locations. Since
each element of this array is a structure, and since all structure elements are always stored in adjacent
locations you can very well visualise the arrangement of array of structures in memory. In our example,
b[0]’s name, price and pages in memory would be immediately followed by b[1]’s name, price and
pages, and so on.
(e) What is the function linkfloat( ) doing here? If you don’t define it you are bound to get the error
"Floating Point Formats Not Linked" with majority of C Compilers. What causes this error to occur?
When parsing our source file, if the compiler encounters a reference to the address of a float, it sets a
flag to have the linker link in the floating-point emulator. A floating point emulator is used to manipulate
floating point numbers in runtime library functions like
reference to the float is a bit obscure and the compiler does not detect the need for the
emulator. The most common is using scanf( ) to read a float in an array of structures as shown in our
program. How can we force the formats to be linked? That’s where the linkfloat( ) function comes in. It
forces linking of the floating-point emulator into an application. There is no need to call this function,
just define it anywhere in your program.
The immediate application that comes to the mind is Database Management. That is, to maintain data
about employees in an organization, books in a library, items in a store, financial accounting transactions
in a company etc. But mind you, use of structures stretches much beyond database management. They
can be used for a variety of purposes like:
INTRODUCTION
To define a union, you must use the union statement in very similar was as you did while defining
structure. The union statement defines a new data type, with more than one member for your program.
Data type is the type of the data, that are going to access within the program. ‘C’ Supports different data
types, each data type may have predefined memory requirement and storage representation.
Defining a Union
Synatx Example
Example
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
149
{
union student record1;
union student record2;
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
C Union is also like structure, i.e. collection of different data types which are grouped together. Each
element in a union is called member.
Union and structure in C are same in concepts, except allocating memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
150
We can access only one member of union at a time. We can’t access all member values at the same time
in union. But, structure can access all member values at the same time. This is because, Union allocates
one common storage space for all its members. Where as Structure allocates storage space for all its
members separately.
Many union variables can be created in a program and memory will be allocated for each union variable
separately.
151
20 STRINGS
INTRODUCTION
The way a group of integers can be stored in an integer array, similarly a group of characters can
be stored in a character array. Character arrays are many a time also called strings.Character arrays or
strings are used by programming languages to manipulate text such as words and sentences.
Note that, in this declaration ‘\0’ is not necessary. C inserts the null character automatically.
/* Program to demonstrate printing of a string */ /* Program to demonstrate printing of a string */
main( ) main( )
{ {
char name[ ] = "Klinsman" ; char name[ ] = "Klinsman" ;
int i = 0 ; char *ptr ;
while ( i <= 7 ) ptr = name ; /* store base address of string */
{ while ( *ptr != `\0' )
printf ( "%c", name[i] ) ; {
i++ ; printf ( "%c", *ptr ) ;
}} ptr++ ;
}}
And here is the output...
Klinsman
152
As with the integer array, by mentioning the name of the array we get the base address (address of the
zeroth element) of the array. This base address is stored in the variable ptr using,
ptr = name ;
Once the base address is obtained in ptr, *ptr would yield the value at this address, which gets printed
promptly through,
printf ( "%c", *ptr ) ;
Then, ptr is incremented to point to the next character in the string. This derives from two facts: array
elements are stored in contiguous memory locations and on incrementing a pointer it points to the
immediately next location of its type. This process is carried out till ptr doesn’t point to the last
character in the string, that is, ‘\0’.
In fact, the character array elements can be accessed exactly in the same way as the elements of an
integer array. Thus, all the following notations refer to the same element:
name[i]
*( name + i )
*( i + name )
i[name]
Note that the declaration char name[25] sets aside 25 bytes under the array name[ ], whereas the
scanf( ) function fills in the characters typed at keyboard into this array until the enter key is hit.
Once enter is hit, scanf( ) places a ‘\0’ in the array. Naturally, we should pass the base address of the
array to the scanf( ) function.
While entering the string using scanf( ) we must be cautious about two things:
The length of the string should not exceed the dimension of the character array
This is because the C compiler doesn’t perform bounds checking on character arrays. Hence, if you
carelessly exceed the bounds there is always a danger of overwriting something important, and in that
event, you would have nobody to blame but yourselves.
scanf( ) is not capable of receiving multi-word strings.
Therefore names such as ‘Debashish Roy’ would be unacceptable. The way to get around this
limitation is by using the function gets( ). The usage of functions gets( ) and its counterpart puts( ) is
shown below.
153
main( )
{
char name[25] ;
printf ( "Enter your full name " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
}
On displaying a string, unlike printf( ), puts( ) places the cursor on the next line. Though gets( ) is capable
of receiving only one string at a time, the plus point with gets( ) is that it can receive a multi-word
string.
Suppose we wish to store “Hello”. We may either store it in a string or we may ask the C compiler to
store it at some location in memory and assign the address of the string in a char pointer. This is shown
below:
char str[ ] = "Hello" ;
char *p = "Hello" ;
There is a subtle difference in usage of these two forms. For example, we cannot assign a string to
another, whereas, we can assign a char pointer to another char pointer. This is shown in the following
program.
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Also, once a string has been defined it cannot be initialized to another set of characters. Unlike strings,
such an operation is perfectly valid with char pointers.
154
main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}
With every C compiler a large set of useful string handling library functions are provided.
Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
Compares two strings without regard to case ("i" denotes that this function ignores
strcmpi case)
stricmp Compares two strings without regard to case (identical to strcmpi)
strnicmp Compares first n characters of two strings without regard to case
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string
155
strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the following
program.
main( ) Description
{
char arr[ ] = "Bamboozled" ; Note that in the first call to the function strlen( ),
int len1, len2 ; we are passing the base address of the string, and
len1 = strlen ( arr ) ; the function in turn returns the length of the
len2 = strlen ( "Humpty Dumpty" ) ; string. While calculating the length it doesn’t count
printf ( "\nstring = %s length = %d", arr, len1 ) ; ‘\0’.
printf ( "\nstring = %s length = %d", "Humpty
Dumpty", len2 ) ; Even in the second call,
} len2 = strlen ( "Humpty Dumpty" ) ;
what gets passed to strlen( ) is the address of the
string and not the string itself
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13
strcpy( )
This function copies the contents of one string into another. The base addresses of the source and target
strings should be supplied to this function.
main( ) Description
{ On supplying the base addresses, strcpy( ) goes on
char source[ ] = "Sayonara" ; copying the characters in source string into the
char target[20] ; target string till it doesn't encounter the end of
strcpy ( target, source ) ; source string (‘\0’). It is our responsibility to see to
printf ( "\nsource string = %s", source ) ; it that the target string’s dimension is big enough
printf ( "\ntarget string = %s", target ) ; to hold the string being copied into it. Thus, a
} string gets copied into another, piece-meal,
character by character
And here is the output...
source string = Sayonara
target string = Sayonara
156
strcat( )
This function concatenates the source string at the end of the target string. For example, “Bombay” and
“Nagpur” on concatenation would result into a string “BombayNagpur”.
main( ) Note that the target string has been made big
{ enough to hold the final string
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Folks!
target string = HelloFolks!
strcmp( )
This is a function which compares two strings to find out whether they are same or different. The two
strings are compared character by character until there is a mismatch or end of one of the strings is
reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re
not, it returns the numeric difference between the ASCII values of the first non-matching pairs of
characters. Here is a program which puts strcmp( ) in action.
main( ) In the first call to strcmp( ), the two strings are identical—
{ “Jerry” and “Jerry”—and the value returned by strcmp( ) is
char string1[ ] = "Jerry" ; zero. In the second call, the first character of “Jerry” doesn't
char string2[ ] = "Ferry" ; match with the first character of “Ferry” and the result is 4,
int i, j, k ; which is the numeric
i = strcmp ( string1, "Jerry" ) ; difference between ASCII value of ‘J’ and ASCII value of ‘F’. In
j = strcmp ( string1, string2 ) ; the third call to strcmp( ) “Jerry” doesn’t match with “Jerry
k = strcmp ( string1, "Jerry boy" ) ; boy”, because the null character at the end of “Jerry”
printf ( "\n%d %d %d", i, j, k ) ; doesn’t match the blank in “Jerry boy”. The value returned is
} -32, which is the value of null character minus the ASCII
value of space, i.e., ‘\0’ minus ‘ ’, which is equal to -32.
The exact value of mismatch will rarely concern us. All we
usually want to know is whether or not the first string is
alphabetically before the second string. If it is, a negative
value is returned; if it isn’t, a positive value is returned. Any
non-zero value means there is a mismatch
And here is the output...
0 4 -32
157
Summary:
Questions:
B 1. Write a program that converts all lowercase characters in a given string to its
equivalent uppercase character
2. Write any 5 string library function
3. What is String? Explain
158
COURSE PLAN
1. Objectives
To study about File handing Pointer in C language
2. Outcomes
Students will acquire knowledge on Pointers and Files in C language
3. Pre-requisites
Basic C Programming
4. Terminology used other than normal known scientific / engg terms and their
fundamental explanations / relations
Not Applicable
1. How to plan for delivery – black board / ppt / animated ppt / (decide which is good
for this topic)
Power Point Presentation
2. How to explain the definition and terms with in it
Defining the Pointer variable , Defining the files and various file operations and modes.
3. How to start the need for any derivation / procedure / experiment / case study
Not Applicable
4. Physical meaning of math equations / calculations
Not Applicable
5. Units and their physical meaning to make them understand practical reality and
comparison between different units
Not Applicable
159
6. What is the final conclusion?
Understand the concept of Pointers and Various File Operations in C Language
7. How to put it in a nut shell
Pointer , File, EOF, BOF, Read Mode, Write Mode )
8. Important points for understanding / memorizing / make it long lasting
Pointer
Pointers are variables which hold addresses of other variables.
Pointers can be used to make a function return more than one value simultaneously.
The array variable acts as a pointer to the zeroth element of the array. In a 1-D array, zeroth
element is a single value, whereas, in a 2-D array this element is a 1-D array.
On incrementing a pointer it points to the next location of its type.
Array elements are stored in contiguous memory locations and so they can be accessed
using pointers.
Only limited arithmetic can be done on pointers
Files
1. File I/O can be performed on a character by character basis, a line by line basis, a record by
record basis or a chunk by chunk basis.
2. Different operations that can be performed on a file are creation of a new file, opening an
existing file, reading from a file, writing to a file, moving to a specific location in a file
(seeking and closing file.
3. File I/O is done using a buffer to improve the efficiency.
4. A file can be a text file or a binary file depending upon its contents.
5. Library function convert \n to \r\n or vice versa while writing/reading to/from a file.
6. Many library functions convert a number to a numeric string before writing it to a file,
thereby using more space on disk. This can be avoided using functions fread() and fwrite().
In low level file I/O we can do the buffer management ourselves.
9. Questions and cross questions in that topic to make them think beyond the topic.
B 1. What is pointer?
2. Explains the pointer notation
3. Restriction using pointer arithmetic
160
4. write program for given elements to an Pointer array.(int i=5, j=6,k=7,z=20)
D 1. What is File
2. What are the various mode to open the file
3. Write a Program to read the content of a File.
F 1. Develop a C program to read a data file and display its contents in a neat format?
2. Explain about the file read, write and append operations in C with suitable example?
161
19 Pointer
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If pointer is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two
pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
162
main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
}
Note that printing the value of *( &i ) is same as printing the value of i.
The expression &i gives the address of the variable i. This address can be collected in a variable, by
saying,
j = &i ;
163
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}
The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3
Work through the above program carefully, taking help of the memory locations of i and j shown earlier.
This program summarizes everything that we have discussed so far. If you don’t understand the
program’s output, or the meanings of &i, &j, *j and *( &i ), re-read the last few pages. Everything we say
about C pointers from here onwards will depend on your understanding these expressions thoroughly.
164
19.2 Pointer arithmetic.
main( )
{
int i = 3, *x ;
float j = 1.5, *y ;
char k = 'c', *z ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of j = %f", j ) ;
printf ( "\nValue of k = %c", k ) ;
x = &i ;
y = &j ;
z = &k ;
printf ( "\nOriginal address in x = %u", x ) ;
printf ( "\nOriginal address in y = %u", y ) ;
printf ( "\nOriginal address in z = %u", z ) ;
x++ ;
y++ ;
z++ ;
printf ( "\nNew address in x = %u", x ) ;
printf ( "\nNew address in y = %u", y ) ;
printf ( "\nNew address in z = %u", z ) ;
}
Here is the output of the program.
Value of i = 3
Value of j = 1.500000
Value of k = c
Original address in x = 65524
Original address in y = 65520
Original address in z = 65519
New address in x = 65526
New address in y = 65524
New address in z = 65520
i j k x y z
3 1.500000 ‘c’ 65524 65520 65519
65524 65520 65519
165
Observe the last three lines of the output. 65526 is original value in x plus 2, 65524 is original value
in y plus 4, and 65520 is original value in z plus 1.
This so happens because every time a pointer is incremented it points to the immediately next
location of its type.
That is why, when the integer pointer x is incremented, it points to an address two locations after the
current location, since an int is always 2 bytes long (under Windows/Linux since int is 4 bytes long, new
value of x would be 65528).
Similarly, y points to an address 4 locations after the current location and z points 1 location after the
current location.
This is a very important result and can be effectively used while passing the entire array to a function.
The way a pointer can be incremented, it can be decremented as well, to point to earlier locations. Thus,
the following operations can be performed on a pointer:
Now we will try to correlate the following two facts, which we have learnt above:
(a) Array elements are always stored in contiguous memory locations.
(b) A pointer when incremented always points to an immediately next location of its type.
166
main( ) main( )
{ {
int arr[ ] = { 10, 20, 36, 72, 45, 36 } ; int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
int *j, *k ;
for ( i = 0 ; i <= 5 ; i++ )
j = &arr [ 4 ] ;
{
k = ( arr + 4 ) ;
printf ( "\nelement no. %d ", i ) ;
if ( j == k )
printf ( "address = %u", &num[i] ) ;
printf ( "The two pointers point to the same
}
location" ) ;
}
else
printf ( "The two pointers do not point to
the same location" ) ;
}
The output of this program would look like this:
element no. 0 address = 65512
element no. 1 address = 65514
element no. 2 address = 65516
element no. 3 address = 65518
element no. 4 address = 65520
element no. 5 address = 65522
167
19.4 Array of Pointer
The way there can be an array of ints or an array of floats, similarly there can be an array of pointers.
Since a pointer variable always contains an address, an array of pointers would be nothing but a
collection of addresses. The addresses present in the array of pointers can be addresses of isolated
variables or addresses of array elements or any other addresses.
main( )
{
int *arr[4] ; /* array of integer pointers */
int i = 31, j = 5, k = 19, l = 71, m ;
arr[0] = &i ;
arr[1] = &j ;
arr[2] = &k ;
arr[3] = &l ;
for ( m = 0 ; m <= 3 ; m++ )
168
23 FILES
Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of
some kind. The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a database; or pixels
from a graphical image. The meaning attached to a particular file is determined entirely by the data
structures and operations used by a program to process the file. It is conceivable (and it sometimes
happens) that a graphics file will be read and displayed by a program designed to process textual data.
The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a
machine decipherable storage media where programs and data are stored for machine usage.
Essentially there are two kinds of files that programmers deal with text files and binary files. These two
classes of files will be discussed in the following sections.
A text file can be a stream of characters that a computer can process sequentially. It is not only
processed sequentially but only in forward direction. For this reason a text file is usually opened for only
one kind of operation (reading, writing, or appending) at any given time.
Similarly, since text files only process characters, they can only read or write data one character at a
time. (In C Programming Language, Functions are provided that deal with lines of text, but these still
essentially process data one character at a time.) A text stream in C is a special kind of file. Depending
on the requirements of the operating system, newline characters may be converted to or from carriage-
return/linefeed combinations depending on whether data is being written to, or read from, the file.
Other character conversions may also occur to satisfy the storage requirements of the operating system.
These translations occur transparently and they occur because the programmer has signalled the
intention to process a text file.
169
Binary files
A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and
a character are equivalent. Hence a binary file is also referred to as a character stream, but there are
two essential differences.
1. No special processing of the data occurs and each byte of data is transferred to or from the disk
unprocessed.
2. C Programming Language places no constructs on the file, and it may be read from, or written
to, in any manner chosen by the programmer.
Binary files can be either processed sequentially or, depending on the needs of the application, they can
be processed using random access techniques. In C Programming Language, processing a file using
random access techniques involves moving the current file position to an appropriate place in the file
before reading or writing data. This indicates a second characteristic of binary files.
They a generally processed using read and write operations simultaneously.
For example, a database file will be created and processed as a binary file. A record update operation
will involve locating the appropriate record, reading the record into memory, modifying it in some way,
and finally writing the record back to disk at its appropriate location in the file. These kinds of operations
are common to many binary files, but are rarely found in applications that process text files.
When the program is terminated, the entire data is lost in C programming. If you want to keep large
volume of data, it is time consuming to enter the entire data. But, if file is created, these information
can be accessed using few commands. There are large numbers of functions to handle file I/O in C
language.
170
23.2 File operations
There are different operations that can be carried out on a file. These are:
When you open a file, you must specify how it is to be opened. This means whether to create it from
new, overwrite it and whether it's text or binary, read or write and if you want to append to it. This is
done using one or more file mode specifiers which are single letters "r", "b", "w", "a" and + (in
combination with the other letters). "r" - Opens the file for reading. This fails if the file does not exist or
cannot be found. "w" - Opens the file as an empty file for writing. If the file exists, its contents are
destroyed. "a" - Opens the file for writing at the end of the file (appending) without removing the EOF
marker before writing new data to the file; this creates the file first if it doesn't exist. Adding + to the file
mode creates three new modes:
"r+" Opens the file for both reading and writing. (The file must exist.) "w+" Opens the file as an empty
file for both reading and writing. If the file exists, its contents are destroyed.
"a+" Opens the file for reading and appending; the appending operation includes the removal of the EOF
marker before new data is written to the file and the EOF marker is restored after writing is complete;
creates the file first if it doesn't exist.
171
Opening Modes in Standard I/O
File Mode Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If
w Open for writing.
the file does not exist, it will be created.
Open for append. i.e, Data is
a If the file does not exists, it will be created.
added to end of file.
Open for both reading and
r+ If the file does not exist, fopen() returns NULL.
writing.
Open for both reading and If the file exists, its contents are overwritten. If
w+
writing. the file does not exist, it will be created.
Open for both reading and
a+ If the file does not exists, it will be created.
appending.
File operations
Opening a File
Before we can read(or write) information from (to) a file on a disk we must open the file. To
open the file we have called the function fopen(). It would open a file a file “PRC1.C” in ‘read
mode, which tells the C compiler that we would be reading the contents of the file. Not that “r”
is a string not a character; hence the double quotes and not single quotes. In fact fopen()
performs three important tasks when you open the file in “r’ mode:
Why do we need a buffer at all? Imagine how inefficient it would be to actually access the disk
every time we want to read a character from it. Every time we read some think from disk, it
takes some time for the disk drive to position the read/write head correctly. On a floppy disk
system, the drive motor has to actually start rotating the disk from a standstill position every
time the disk is accessed. If this were to be done for every character we read from the disk, it
would take a long time to complete the reading operation. This is where a buffer comes in. it
would be more sensible to read the contents of the file into the buffer while opening. This is
where a buffer comes in. it would be more sensible to read the contents of the file into the
172
buffer while opening the file and then read the file character by character from the buffer rather
than from the disk. This is shown in the below figure.
PR1.C
Memory DISK
40
fp
40
some argument also applies to writing information in a file. Instead of writing characters in the file on
the disk one character at time it would be more efficient to write charters in a buffer and then finally
transfer the content from the buffer to the disk.
To be able to successfully read from a file information like mode of opening, size of file, place in the file
from where the next read operation would be performed, etc. has to be maintained. Since all this
information is inter-related, all of it is gathered together by fopen() in a structure called FILE. fopen()
return the address of this structure, which we have collected in the stracture pointer called fp. We have
declared fp as
FILE * fp;
The FILE structure has been defined in the header file “stdio.h” (standing for standard input/ouput
header file). therefore, it is necessary to #include this file.
173
23.4 Reading file content.
C program to read a file: This program reads a file entered by the user and displays its contents
on the screen, fopen function is used to open a file it returns a pointer to structure FILE. FILE is a
predefined structure in stdio.h . If the file is successfully opened then fopen returns a pointer to file and
if it is unable to open a file then it returns NULL. fgetc function returns a character which is read from
the file and fclose function closes the file. Opening a file means we bring file from disk to ram to perform
operations on it. The file must be present in the directory in which the executable file of this code sis
present.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r"); /* read mode */
if( fp == NULL )
{
printf("Error while opening the file.\n");
exit(0);
}
printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
return 0;
}
174
23.5 Error handling While opening a File
There is a possibility that when we try to open a file using the function fopen(), the file may not
be opened. While opening the file in “r” mode, this may happen because the file being opened may not
be present on the disk at all. And you obviously cannot read a file that doesn’t exist. Similarly, while
opening the file for writing, fopen() may fail due to a number of reasons, like, disk space may be
insufficient to create a new file, of the disk may be write protected or the disk is damaged and so on.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
Fp = fopen (“PRGRAM1.C”, “r”);
if (fp == NULL)
{
puts(“cannot open file”);
Exit(1);
}
return 0;
}
To close a file, use the fclose( ) function. The prototype of this function is:
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function
actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory
used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provide by C standard library to read and write a file character by character
or in the form of a fixed length string.
175
23.7 Writing to a File
The fputc() function is similar to the putch() function, in the senses that both output characters.
However, putch() function always writes to the VDU, whereas, fputc() write to the file. Which file? The
file signified by ft. The writing process continues till all characters from the source file have been written
to the target file, following which the while loop terminates.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char s[80],.
fp=fopen(“Cprogram.txt”, “w”);
if(fp==NULL)
{
printf("Cannot open file\n");
exit(1);
}
printf("\nenter a few lines of text:”);
while(strlen(gets(s)>0)
{
fputs(s, fp);
fputs(“\n”, fp);
}
fclose(fp);
return 0;
}
We have already used the function fgetc() which reads characters from a file. Its counterpart is a
function called fputc() which writes characters to a file. As a practical use of these character I/O
functions, we can copy the contents of one file into another, as demonstrated in the following program.
This program takes the contents of a file and copies them into another file, character by character.
176
/* File Copy Program */
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fs, *ft;
char ch;
fs = fopen(“prg1.c”,”r”)
if( fs == NULL)
{
puts(“Cannot open Source file”);
exit(1)
}
ft = fopen(“prg2.c”,”w”);
if ( ft ==NULL)
{
puts(“Cannot open target file”);
fclose(fs);
exit(2);
}
while(1)
{
ch = fgetc(fs);
if(ch==EOF)
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft)
return 0;}
Writing to a File
The fputc() function is similar to the putch() function, in the senses that both output characters.
However, putch() function always writes to the VDU (Visual Display Unit). Whereas, fputc() writes a to
the file. Which file? The file signified by ft. The writing process continues till all characters from the
source file have been written to the target file, following which the while loop terminates. In the above
file copy program is capable of copying only text files. To copy file with extension .EXE or JPG, we need
to open the file in binary mode.
177