CP Material 1 1 PDF
CP Material 1 1 PDF
CP Material 1 1 PDF
PROBLEM SOLVING
LEARNING OBJECTIVES
After going through this chapter, the readers will be able to:
apply problem solving techniques;
define an algorithm and its features;
describe the analysis of the algorithm efficiency;
discuss the analysis of algorithm complexity; and
design flowchart
1.1 INTRODUCTION
In our daily life, we routinely encounter and solve problems. We pose problems that we need or
want to solve. For this, we make use of available resources, and solve them. Some categories of resources
include: the time and efforts of yours and others; tools; information; and money. Some of the problems
that you encounter and solve are quite simple. But some others may be very complex.
In this unit we introduce you to the concepts of problem-solving, especially as they pertain to computer
programming.
The problem-solving is a skill and there are no universal approaches one can take to solving
problems. Basically one must explore possible avenues to a solution one by one until she/he comes across
a right path to a solution. In general, as one gains experience in solving problems, one develop one’s own
techniques and strategies, though they are often intangible. Problem-solving skills are recognized as an
integral component of computer programming. It is a demand and intricate process which is equally
important throughout the project life cycle especially – study, designing, development, testing and
implementation stages. The computer problem solving process requires:
i) Problem anticipation
ii) Careful planning
iii) Proper thought process
iv) Logical precision
v) Problem analysis
vi) Persistence and attention.
At the same time it requires personal creativity, analytic ability and expressions. The chances of
success are amplified when the problem solving is approached in a systematic way and satisfaction is
achieved once the problem is satisfactorily solved. The problem should be anticipated as far as possible
and properly defined to help the algorithm defined and development process.
Computer is a very powerful tool for solving problems. It is a symbol-manipulating machine that
follows a set of stored instructions called a program. It performs these manipulations very quickly and
stores the input, all commands and output. A computer can’t think like human so that when solving any
problem we have to specify the needed initial data, the operations which to be performed. And the result
you wanted as output. Any of the instructions missing you will get either no result or invalid result. In
either case your problem has not yet been solved. Therefore e several step need to be considered before
writing a program. These steps may free you from hours of finding and removing errors in your program
(a process called debugging).It should also make the act of problem solving with a computer a much
simpler task.
All types of computer programs are collectively referred to as software. Programming languages
are also part of it. Physical computer equipment such as electronic circuitry, input output devices, storage
media etc. comes under hard ware. Software governs the functioning of hardware. Operations performed
by software may be built in to the hardware, while instructions executed by the hardware may be
generated in software .
Problem solving 1
The decision to incorporate certain functions in the hardware and others in the software is made
by the manufacturer and designer of the software and hardware. Normal considerations for this are: cost,
speed, memory required, adoptability and reliability of the system. Set of instructions of the high-level
language used to code a problem to find its solution is referred to as source program. A translator
program called a compiler or interpreted, translate the source program in to the object program. This is
the compilation or interpretation phase. All the testing of the source programs as regards the correct
format of instructions is performed at this stage and the errors, is any, and is printed. If there is no error
the source program is transformed in to the machine language program called object program. The object
program is executed to perform calculations this stage is the execution phase. Data, if required by the
program are supplied now and the result is obtained on the output device.
Results
Problem solving 2
problem is more clearly defines. This approach of focusing on a particular problem can give us the
foothold we need for making a star on the solution to the general problem.
1.2.4 Similarities among problems
One way to make a start is by considering a specific example .Another approach is to bring the
experience to bear on the current problem. So it is important to see if there are any similarities between
the current problem and the past problems which we have solved. He more experience one has the more
tools and techniques one can bring to bear in tackling the given problem. But some time it blocks us from
discovering desirable or better solution to the problem. A skill that is important to try to develop in
problem solving is the ability to view a problem from a variety of angles. One must be able to
metaphorically turn a problem upside down, Inside out, sideways, backwards, forwards and so on. Once
one has developed this skill it should be possible to get started on any problem.
1.2.5 Working backwards from the solution
In some cases we can assume that we already have the solution to the problem and then try to
work backwards to the starting point. Even a guess at the solution to the problem may be enough to give
us a foothold to start on the problem. We can systematize the investigation and avoid duplicate efforts by
writing down the various steps taken and explorations made. Another practice that helps to develop the
problem solving skills is , once we has solved problem , to consciously reflect back on the way we went
about discovering the solution.
1.3 USING COMPUTER AS A PROBLEM-SOLVING TOOL
The computer is a resource-a versatile tool-that can help you solve some of the problems that you
encounter. A computer is a very powerful general-purpose tool. Computers can solve or help to solve
many types of problems. There are also many ways in which a computer can enhance the effectiveness of
the time and effort that you are willing to devote to solving a problem. Thus it will prove to be well worth
the time and effort you spend to learn how to make effective use of this tool.
In this section, we discuss the steps involved in developing a program. Program development is a
multi-step process that requires you to understand the problem, develop a solution, write the program, and
then test is. This critical process determines the overall quality and success of your program. If you
carefully design each program using good structured development techniques our programs will be
efficient, error free, and easy to maintain. The following are the steps in detail:
i) Develop an Algorithm and a Flowchart
ii) Write the program in a computer language (for example say C programming language)
iii) Enter the program sing some editor.
iv) Test and debug the program.
v) Run the program, input data, and get the results.
1.4 DESIGN OF ALGORITHMS
The first step in the program development is to devise and describe a precise plan of what you
want the computer to do. This plan, expressed as a sequence of operation, is called an algorithm. An
algorithm is just an outline or idea behind a program..
1.4.1 Definition
An algorithm is a finite set of steps defining the solution of a particular problem. An algorithm is
expressed in pseudo code-something resembling C language or Pascal, but with some statements in
English rather than within the programming language. Developing an efficient algorithms one which is
capable of giving the solution to the problem by using minimum resources of the system such as memory
and processor’s time. Algorithm is a language independent, well structured and detailed. It will enable the
programmer to translate into a computer program using any high-level language.
Problem solving 3
1.4.2 Features of Algorithm
Following features should be present in an algorithm:
Proper understanding of the problem
For designing an efficient algorithm, the expectations from the algorithm should be clearly
defined so that the person developing the algorithm can understand the expectations from is. This
is normally the outcome of the problem definition phase.
Use of procedures/functions to emphasize modularity
To assist the development, implementation and readability of the program, it is usually helpful to
modularize (section) the program. Independent functions perform specific and well defined tasks.
In applying modularization, is is important to watch that the process is not taken so far to a point
at which the implementation becomes difficult to read because of fragmentation. The program
then can be implemented as calls to the various procedures that will be needed in the final
implementations.
Choice of variable names
Proper variable names and constant names can make the program more meaningful and easier to
understand. This practice tends to make the program more self-documenting. A clear definition of
all variables and constants at the start of the procedure/algorithm can also be helpful. For
example, it is better to use variable day for the day of the weeks, instead of the variable A or
something else.
Documentation of the program
Brief information about the segment of the code can be included in the program to facilitate
debugging and providing information. A related p art of the documentation is the information that
the programmer presents to the user during the execution of the program. Since the program is
often to be used by persons who are unfamiliar with the working and input requirements of the
program, proper documentation must be provided. That is, the program must specify what
responses are required from the user. Care should also be taken to avoid ambiguities in these
specifications also the program should “catch” incorrect responses to its requests and inform the
user in an appropriate manner.
1.4.3 Criteria to be followed by an algorithm
The following is the criteria to be followed by an algorithm:
i) Input: There should be zero or more values which are to be supplied.
ii) Output: At least one result is to be produced.
iii) Definiteness: Each step must be clear and unambiguous.
iv) Finiteness: Each step must be sufficiently a basic that a person using only paper and
pencil canin principle carry it out. In addition, not only each step isdefinite, it must
also be feasible.
Example 1.1: An algorithm to find the area of a Circle of radius r.
Inputs to the algorithm:
Radius r of the Circle.
Expected output:
Area of the Circle
Algorithm:
Step1: Read\input the Radius r of the Circle
Step2: Area= PI*r*r // calculation of area
Step3: Print Area
Example 1.2: An algorithm to compute and display the sum of two numbers
Inputs to the algorithm:
Two numbers
Expected output:
Sum of two numbers
Problem solving 4
Algorithm:
Step1: Read two numbers a and b
Step2: Calculate the sum of a and b and store it is sum
Step3: Print sum
Example 1.3: Ravi has to attend at least 70% of Practical Classes for C programming to be eligible to
appear in the external examination. Maximum no. of practical classes allotted for the course is 50. He
has attended 20 out of 30 classes held so far. Find at least how many more classes to be attended by Ravi
to be eligible for appearing in Practical Examination.
Inputs to the algorithm:
Minimum Percentage of Attendance required appearing for the external exams.
Maximum Number of practical classes
Number of Classes held so far.
Number of classes attended by Ravi so far.
Expected output:
Number of classes to be attended by Ravi to get eligibility for appearing the external examination
Algorithm:
Step1: Read Minimum percentage of attendance required.
Step2: Read Maximum no. of practical classes in the course (P)
Step3: Read Classes already attended (Ca)
Step4: Read No. of classes conducted so far.(CT)
Step5: Find the no. of Classes to be attended byRavi (Ct= C*P/100)
Step6: Print CM.
Example 1.5: An algorithm to compute and print the average of a set of data values.
Inputs to the algorithm:
List of data values
Expected Output:
Average of the data values
Step1: Set the sum of the data values and the count to zero
Step2: As long as the data values exist, add the next data value to the sum andadd
1 to the count.
Step3: To compute the average, divide the sum by the count.
Step4: Print average.
Problem solving 5
Expected Output:
Factorial of the integer
step1: Read the number n
step2: [initialize] i 1, fact 1
step3: Repeat steps 4 through 5 until i = n
step4: fact fact*i
step5: i i +1
step6: Print fact
Example 1.8: Ramshewar goes to market for buying some fruits and vegetables. He is having a currency
of Rs 500 with him for marketing. From a shop he purchases 2.0 kg Apple priced Rs. 50.0 per kg, 1.5 kg
Mango priced Rs.35.0 per kg, 2.5 kg Potato priced Rs.10.0 per kg, and 1.0 kg Tomato priced Rs.15 per
kg. He gives the currency of Rs. 500 to the shopkeeper. Find out the amount shopkeeper will return to
Ramshewar and also tell the total item purchased.
Before we write algorithm for solving above problem let we find out what the inputs to the
algorithm are and what expected output is.
Inputs to the algorithm are:
Quantity of different items purchased.
Unit Price of each item.
Total amount given to the shopkeeper.
Expected output:
Amount to be returned by shopkeeper after deducting total price of the purchased
vegetables and fruits.
Algorithm:
Step1: Total Cost=0;
Step2: Read Number of units of ith item purchased;
Spet3: Read unit price of ith item
Step4: cost of ith item (CI) = number of units * unit price of ith item.
Step5: total cost = total cost +CI.
Step6: i= i+1;
Step7: if i<=4 goto step 2.
Step7: RefundAmount = GivenAmount-Total Cost
Step8: Print RefundAmount
Problem solving 6
Table of N
Algorithm:
Step 1: I=1
Step 2: Read N
Step 3: If I <= 10 then print I*N otherwise goto Step 6
Step 4: I =I+1
Step 5: repeat step3 and 4
Step 6: stop
Complex or
largeproblem
Complex
solution
Fig 1.1. Schematic break down of problem into subtasks as employed in top down
designs
Problem solving 7
1.5 FLOW CHARTS
“Flow charts are pictorial representation of an algorithm”. It shows the flow of operations
in pictorial form.
Problem solving 8
Flowchartscan be used for preparing a better documentation of a complex problem.
v) When decision symbol is used only one flow line should enter toit (decision symbol),
but there may be two or three flow lines coming out of the decision symbol, one for
each possible answer.
A<B A>B
Compare
A& B
A=B
vi) In a flowchart only one flow line should come to the end symbol.
END
vii) While writing steps inside the processing symbol, steps should be brief and if
necessary, you can use the annotation symbol to describe data or processing steps
more clearly.
P=A*R
Problem solving 9
for better way of communication.
x) A flowchart must have a logical start and end.
xi) Once a flowchart is drawn its validity should be tested by passing through it with a
simple set of test data.
start
Example1.10: Draw a flowchart to find the simple interest
accept p,t,r
i=ptr/100;
print i;
stop
Sum=0
N=0
N=N+1
sum=sum+N
is
N=50?
yes
print sum
stop
Problem solving 10
Example1.12: Draw a flowchart to find the largest of three numbers A, B, and C.
start
Read A B C
B>C
No No
print C print A
print B print c
stop
Read N
M=1
F=1
F=F*M
NO
M=M+1 Is M=N?
YES
Print F
stop
Problem solving 11
Example1.14: Draw a flow chart to find the roots of a quadratic equation
start
Read A B
C
D=B*B-4*A*C
False True
IS
D>0
True False
IS ROOT1=(-B+sqrt(D))/(2*A)
D>0 ROOT2=(-B+sqrt(D))/(2*A
PRINT “REAL
RP=-B/2*A ROOT1=-B/2*A AND
IP=SQRT(-D)/2*A ROOT2=-B/2*A DISTINCT”
STOP
Problem solving 12
Example1.15: Draw a flowchart to print biggest number from given list of numbers
start
Read N,X
BIG=X
COUNT=1
IF
COUNT<N
Read X
Print BIG
IF X>BIG
BIG=X
COUNT=COUNT+1
Problem solving 13
Example1.16: Draw a flowchart to display the given number is prime or not
START
READ N
K=√N
I=2; FLAG=1
R=remainder of(N/I)
IS
R=0
I=I+1 FLAG=0
IS I<=K
IS
FLAG=
0
Problem solving 14
Example1.17: Draw a flowchart to generate first n elements of Fibonacci series.
START
READ N
FIB1=1
FIB2=1
COUNT=2
FIB3=FIB1=+FIB2
PRINT FIB3
COUNT=COUNT+1
IS COUNT<N
No
yes
FIB1=FIB2 STOP
FIB2=FIB3
Problem solving 15
iv) Efficient Program Maintenance: Once a program is developed and becomes
operational it needs time to time maintenance. With help of flowchart maintenance
become easier.
v) Coding of the Program: Any design of solution of a problem is finally converted into
computer program. Writing code referring the flowchart of the solution become easy.
1.6 LAUNGAGE
A language is a mode of communication between two people. It is necessary for those two
people to understand the language in order to communicate. But even if the two people do not understand
the same language, a translator can help to convert one language to the other. Similarly we need a
language to communicate with the computer. A translator is also needed to convert from user’s form to
computers form. Like other language, a computer language also follows a particular grammar known as
the syntax.
Problem solving 16
allow application programs to be run in a variety of computers.
iii) These languages are machine independent.
iv) Languages falling in this category are FORTRAN, BASIC, and PASCAL etc.
v) These languages are easy to learn and programs may be written in these languages
with much less effort.
vi) However, the computer cannot understand them and they need to be translated into
machine language with the help of other programs known as compilers or interpreters.
SUMMARY
Computer is a powerful problem solving tool. Problem-solving skills are recognized as an integral
component of computer programming. A problem solving technique follows certain steps in finding
the solution to a problem. An algorithm is a finite set of steps defining the solution of a particular
problem. Flow chart is pictorial representation of an algorithm. It shows the flow of operations in
pictorial form. For drawing flow chart standard symbols are used. The START and STOP are
represented by an ellipse like figure , decision by the rhombus like figure the
EXERCISES
a) machine language b) assembly language c) high level language d) fourth generation language
Compressive Questions
Problem solving 17
1.1 What is algorithm and explain it briefly?
1.2 What is flowchart? What are different symbols used for design of flow chart?
1.3 Design an algorithm and draw flowchart to find area and circumference of a circle
1.4 Design an algorithm and draw flowchart to find area and circumference of a rectangle
1.5 Design an algorithm and draw flowchart to check the given character is vowel or not
1.6 Given the marks obtained by the students, maximum marks and pass marks in three subjects, design
an algorithm and draw flowchart to find whether the student passed or not, if the student passes
determine the percentage marks and grade.
The grade is determined as follows:
i) percentage marks >=80 grade is A
ii) percentage marks >=70 and <80 grade is B
iii) percentage marks >=60 and <70 grade is C
iv) percentage marks >=50 and <60 grade is D
v) percentage marks <50 grade is F
1.7 Design an algorithm and draw flowchart for converting temperature from Fahrenheit to centigrade
and vice-versa
1.8 Design an algorithm and draw flowchart to find roots of a quadratic equation
1.9 Design an algorithm and draw flowchart to find the nature of the triangle when sides are given
1.10 Design an algorithm and draw flowchart to find sum of n numbers.
1.11 Design an algorithm and draw flowchart to check given number is prime or not
1.12 Design an algorithm and draw flowchart to check given number is strong or not
1.13 Design an algorithm and draw flowchart to check given number is palindrome or not
1.14 Design an algorithm and draw flowchart to check given number is perfect or not
1.15 Design an algorithm and draw flowchart to check given number is Armstrong or not
1.16 Design an algorithm and draw flowchart to find the smallest number in a given list of numbers
1.17 Design an algorithm and draw flowchart to find first and second largest numbers in a given list
Problem solving 18
Chapter 2
BASICS OF C
LEARNING OBJECTIVES
After going through this chapter, the readers will be able to:
features of C programming language
Understand the main components of a C Program.
compile a C Program, identify the errors and run a C Program
learn the use of variables ,constants, data types, operators
learn the usage of scanf() and printf() for data input and output
precedence and Associativity of operators
write simple C programs
2.1 OVERVIEW OF C
Before writing C program, we will find out what really is C language, how it came into
existence and where does it stand with respect to other computer language. We will briefly outline these
issues in the following section.
2.1.1 History of C
C is a programming language developed at AT&T‟s bell laboratories of USA in 1972. It was
designed and written by a man named DENNISRITCHIE. In the late seventies c began to replace the
more familiar languages of that time like PL\I, ALGOL etc.
By 1960,many programming languages came into existence, almost each for a specific
purpose for example COBOL was being used for commercial or business applications, FORTRAN for
scientific applications and so on .so, people started thinking why could not there be a one general purpose
language .Therefore ,an international committee was set up to develop such a language ,which came out
with the invention of ALGOL60,but this language never became popular because it was too abstract and
too general. To improve this, new language called combined programming language (CPL) was
developed at Cambridge University. But this language was very complex in the sense that it has too many
features and it was very difficult to learn. Matrin Richards at Cambridge University reduced the features
of CPL and developed a new language (BCPL). But unfortunately it turned out to be much less powerful
and too specific. Ken Thompson at AT & T‟s bell labs, developed a language called B, but like BCPL
this was also too specific. Ritchie inherited the features of B and BCPL and added some features on his
own and developed a language called C. C proved to be quite compact and coherent.
2.1.2 Features of C
i) Middle Level Language: Among the two types of programming languages discussed earlier, C lies in
between these two categories. That‟s why it is often called a middle level language, since it was designed
to have both: relatively good programming efficiency and relatively good machine efficiency.
ii) Portability: C code is very portable, that it allows the same C program to be run on the machines with
different hardware configurations.
iii) Flexibility: The flexibility of C allows it to be used for systems programming as well as for
application programming.
iv) Structured Language: C is commonly called a structured language because of structural similarities
of ALGOL and PASCAL. Structured language is one that divides the entire program into the modules
using top-down approach where each module executes one job or task.
It is easy for debugging, testing and maintenance if a language is structured one.
Basics of C 19
2.2 STRUCTURE OF A C PROGRAM
To solve a problem there are three main things to
be considered .firstly what should be the output? Preprocessor directives
Secondly what should be the input that will be Global data declarations
required to produce this output and thirdly the steps main() /* main function */
of instructions which use these inputs to produce the {
required output .every programming language Declaration part ;
follows a set of rules known as syntax . C is a case Program statements;
sensitive language. All cprograms consist of one or }
more functions. One function that must be present in /* user defined functions */
every C program is main(). This is the first function fun1()
called up when the program execution begins. {
Basically main () outlines what a program does. -------
-------
The structure of a c program is illustrated in flowing }
figure1.1.Where functions fun1 (), fun2()
fun2 () represent user defined functions. {
------
}
Basics of C 20
loop .Such a grouping is known as a compound statement or a block every statement within a function
ends with a terminator semicolon(;).
printf(“this is a C program”); prints the words on the screen .The text to be printed is enclosed
in double quotes.
Comments may appear anywhere within a program as long as they are placed with in the
delimiters /* and*/ .Such comments are helpful in identifying the program principal features or in
explaining the underlying logic of various program features.
As every natural languages has a basic character set, computer languages also have a character set,
rules to define words. Words are used to form statements; these in turn are used to write the
programs.The basic elements used to construct simple C program statements are C character set,
identifiers, keywords, data types, constants, variables, declaration and naming conventions of variables.
Basics of C 21
2.3.2 Identifiers
Identifiers refer to the names of variables, functions and array. These are user defined names and
consist of a sequence of letters and digits, with a letter as a first character. Both upper case and lower
cases letters are permitted, although lower case letters are commonly used. The underscore character is
also permitted.
Variable
A variable is an identifier for a memory location in which data can be stored and subsequently recalled.
2.3.3 Keywords
Keywords are reserved words which have standard, predefined meaning in C. keywords serve as
basic building blocks for program statements. They cannot be used as program defined identifiers.
The lists of C keywords are as follows:
2.4 CONSTANTS
A constant is a quantity that can be stored in a location of the memory of a computer. It refers to a fixed
value that does not change during the execution of the program. For example the memory structure of a
variable X whose value is 13 at the location number 3540 can be shown as follows:
Basics of C 22
Constants
Numeric
Integer Real
Fractional
form
Decimal Octa Hexadecima
l l Exponential form
ii)Octal Integer constant: An octal integer constant can consist of any combination of digits taken
from the set 0 through 7 preceded by zero(0). The format that specifies octal integer constant is
%o(where „o‟ is called conversion character).
Basics of C 23
iii) Hexadecimal Integer constant:
A hexadecimal integer constant can consist of any combination of digits taken from the set 0 through 9
and A through F (or) a through f preceded by 0x (or) 0X. The format that specifies hexadecimal integer
constant is %x (or) %X(where „x‟ or „X‟ is called conversion character).
Exponent Form
This form of representing a floating point constant is generally used if the value of the constant is either
too small (or) too large. This is also called scientific notation. The format that specifies this type of
constants is %e (or) %E(where „e‟ (or) „E‟ is called conversion character). The general form for
representing this type of floating point value is:
Mantissa E exponent
The mantissa is either a real number expressed in fractional form (or) an integer with an optional + (or) –
sign. The exponent should be a decimal integer constant with an optional + (or) – sign. The mantissa and
exponent can be separated by either „e‟ (or) „E‟. Since the exponent causes the decimal point to “float”,
this notation is said to represent a real number in floating point form.
Basics of C 24
Valid examples Invalid examples(with reasons)
+17.4e3 12,2e4(comma is not allowed)
-6E-1 17.6e-2.3(exponent should be an integer)
-0.03e+7 343(exponent should present)
5e-5 $14.3E+56(special symbol is not allowed)
5.32E-32 3.8 e-3(white space characters are not allowed)
Remember that a character constant (eg „x‟) is not equivalent to the single character string constant
(eg, “x”). Further, a single character string constant does not have an equivalent integer value while a
character constant has an integer value, character strings are often used in programs to build meaningful
programs.
Rules for constructing constants
Basics of C 25
i) An integer constant or a floating point constant must have at least one digit.
ii) Integer constant should not have a decimal point.
iii) No commas (or) blank spaces (or) non-digit characters are allowed within an integer
constants (or) within a floating-point constant.
iv) An integer constant could be either +ve (or) –ve (+ve is default).
v) While representing floating-point constants it is possible to omit digits before (or)
after the decimal point.
vi) In scientific notation of a floating-point constant, the exponent should be either +ve
integer (or) –ve integer.
vii) The mantissa part and exponent part of a floating-point constant should be separated
by either „e‟ (or) „E‟.
viii)Mantissa can be either integer type (or) floating-point type with an optional + (or)
– sign.
ix) The exponent must have at least one digit.
x) Single character constant should be enclosed in a pair of single quotation marks
whereas string constant in double quotation marks.
xi) Only one character should be written within a pair of single quotes to represent single
character constant.
xii) A single character constant can be either a single alphabet (or) a single digit (or)
a single special symbol enclosed in a pair of single quotes.
xiii)A string constant may contain any number of characters.
xiv) The letters, digits, special symbols or blank spaces are allowed in string constants.
xv) A single character enclosed in a pair of single quotes is different from the same when
enclosed in pair of double quotes.
2.4.4 Backslash character constants
C supports some special backlash character constants that are used in output functions.For
example the Symbol “/n” stands for new line character. A list of such backlash character constants is
given in the below table. Note that each one of them represents one character.
Character Constant Meaning
\n New line (Line break)
\b Backspace
\t Horizontal Tab
\f Form feed
\a Alert (alerts a bell)
\r Carriage Return
\v Vertical Tab
\? Question Mark
\' Single Quote
\'' Double Quote
\\ Backslash
\0 Null
Basics of C 26
i) Primary data types
These are also called basic data types or fundamental data types. All C compilers support five
fundamental data types.
NOTE: C99 support three more data types, namely bool, complex, imaginary
2.5.1 Integer data type
Integers are whole numbers with a range of values supported by a particular machine. If a system
allocates 16 bits, to an integer, one size of integer value is limited to one range 32,768 to 32,767 (i.e-215
to 215-1).
In order to provide some control over the range of numbers and storage space, C has four classes of
integer storage, namely short int, long int, and long long int, in both signed and the unsigned forms.
Size and range of values of integer data types for 16 bit machine
Data type Size(bits) Range Default type
Int 16 -215 to 215-1 signed int
unsigned int 16 0to 216-1 unsigned
signed int 16 -215 to 215-1 int
short int 16 -215 to 215-1 short
unsigned short int 16 0to 216-1 unsigned short
signed short int 16 -215 to 215-1 short,signed short,short
int
long int 32 -231 to 231-1 long,signed long,signed
long int
unsigned long int 32 0to 232-1 unsigned long
signed long int 32 -231to 231-1 long int,long signed
long
Basics of C 27
Size and range values of floating data types on 16 bit machine.
Data type Size(bits) Range Precision
float 32 3.4e-38 to 3.4e38 7 digits
double 64 1.7e-308 to 1.7 e 308 15 digits
long bouble 80 3.4e-4931 to 3.4 e 4932 20 digits
Also it is used to indicate the no data is passed from the calling function to called function through
arguments. The header of the called function will be of the form
Return data type name(void);
Example2.10: void clear(void);
Example2.12: bool b;
b=1;
B=x>y;
Basics of C 28
2.5.7 Pointer type
A variable of pointer type can be declared similar to variables of other data types. At declaration pointer
type can be distinguished by an asterisk „*‟ preceding the variable name
Example2.13: int x,*p;
float y,*q;
p=&x;
q=&y;
A pointer can be printed out using the function printf() with the format specifier “%p”. Such as
printf(“the values of p is %p\n”,p);
data-type v1,v2,v3….vn
where v1,v2,v3….. are names of the variables. Variables are separated by commas.A declaration
statement must end with a semicolon. valid declarations are
Basics of C 29
balance=87.96;
ch=‟y‟;
C also permits multiple assignments in one line such as:
x= 3.5, y=78.4;are valid statements.
An assignment statement implies that the value of the variable on the left of the „equal‟ sign is set equal
to the value of the quantity /expression on the right side. The statement
count=count+3;
means that the new value of count is equal to the old value of count plus 3. During assignment operation
C converts the type of value on right hand side to the type of value on the left. This may involve
truncation when real value is converted to an integer.
Initialization:
It is also possible to assign a value to a variable at the time of the variable is declared.
This takes the following form:
data-type variable_name=constant;
Basics of C 30
Here the variable m that has been declared as int is not able to store the value 54321 correctly instead it
contains some garbage value. Because maximum value that an int variable can store is 32767,if the
program is executed on 16-bit machine.
The Variable k declared as unsigned has stored the value correctly.Unless specified otherwise printf()
function always display float or double values to six decimal places .
scanf(“control string”,&variable1,&variable2,….);
The control string contains format of the data being received. The ampersand symbol & before each
variable name is the operator that specifies variable name‟s address. The use of & is must in scanf()
function.
Example2.17: scanf(”%d”,&x);
When this statement is encountered, the execution of program stops and waits for the value of the
variable x to be typed in .The format %d specifies that an integer value is to be read from the terminal, we
have to type in the value in integer form. Once number typed and return key pressed, the next statement
in the program is executed.
Commonly used format specifications:
%c – read a single character.
%d – read a decimal Integer.
%e – read a floating point value in exponential form.
%f – read a floating point value.
%i – read a decimal, hexadecimal or octal Integer.
%h– read a short integer.
%x – read a hexadecimal integer (unsigned) using lower case a – f.
%X – read hexadecimal integer (unsigned) using upper case A – F.
%o – read an octal integer.
%s – read a string
%u –read unsigned decimal integer.
%[ character set] –reads only the characters specified with in brackets when inputting string.
%[^character set] –The characters specified after ^(circumflex) are not permitted in the input .
2.9OUTPUT FUNCTION-printf()
printf() function in „C‟ allows you to display information required to the user and also prints the
values of variables. Output data can be written from computer to standard output device.
Basics of C 31
Program2.4
#include < stdio.h > Output:
main ( ) Hello!Welcome to the world of
{ Engineering.
printf (“Hello!”);
printf (“Welcome to the world of Engineering!”);
}
Both the messages appear in the output as if a single line. If you wish to print the second message to the
beginning of next line, a new line character must be placed inside the quotation marks.
Program2.5
main() Output:
{ Hello!
The control string contains format of the data to be displayed and exp1,exp2,exp3…are output
expressions. The function accepts a series of arguments, each applying to a conversion specifier in the
given control string , printf() prints the formatted information to the standard output device, usually the
display screen
Program2.6
#include<stdio,h>
main()
Output:
{
value of a is 100
int a;
a=100;
printf(“value of a is %d”,a);
}
Here control string contains format specifier %d indicates a decimal integer to be displayed .a is the name
of the variable. If value of a is 100 the value 100 will be displayed on screen.
Program2.7 Program to read and print integer,float and character values
#include<stdio.h>
main()
{ int a;
float x;
char ch;
printf(“Enter value of a”);
Basics of C 32
a x ch
Basics of C 33
printf("\nThree floats on 3 lines: \n\t%f\n\t%f\n\t%f", f, g, h);
printf("\nThe rate is %f%%", f);
printf("\nThe result of %f/%f = %f\n", g, f, g / f);
}
Output: Decimal values without tabs: 2 10 50
Decimal values with tabs: 2 10 50
Three floats on 1 line: 1.050000 25.500000 -0.100000
Three floats on 3 lines:
1.050000
25.500000
-0.100000
The rate is 1.050000%
The result of 25.500000/1.050000 = 24.285715
Basics of C 34
iv) Assignment operators
v) Increment and Decrement operators
vi) Conditional operators (Ternary operator)
vii) Bitwise operator
viii) Special operator
Expression
Variables and constants connected by operator is called expression.
Example2.19: float x, y, z;
z=x % y; is not valid.
iii) All other operators can be applied to operands of the arithmetic type, which consists of integer,
floating point or complex types.
iv) When both the operands in an expression are integers, the expression is called integer expression.
Integer arithmetic leads an integer value.
v) When both operands are floating point type the expression is called floating point type expression.
Basics of C 35
Example2.23: 3+5/2*4-10+17%6 is evaluated as
3+((5/2)*4)-10+(17%6)
The result of the expression is 6
2.10.2 Relational Operators
Relational Operators are used to compare the values of two expressions. An expression such as
a < b, n! =0, p>q
containing a relational operator is termed as a relational expression .The value of a relational expression
is either one or zero. It is one if the specified relation is true and zero if the relation is false.
Relational Operators
i) ! (NOT) If the operand of the unary logical negative operator ! is nonzero, the result is true otherwise,
the result is false
The truth table for the NOT operator is
exp !exp
1 0
0 1
Example2.25: !0=1
!3.7=0
! (20)=0
Example2.26: int a=5, b=6, c;
c=! (a>b);
The value 1 is assigned to the variable c.
ii) && (AND) is used to check whether both the expressions are non-zero or not.
The truth table for AND operator is
Basics of C 36
exp1 exp2 exp1&&exp2
1 1 1
1 0 0
0 1 0
0 0 0
Example2.27: To check whether the values of three variables a,b,c form the sides of an equilateral
triangle the following code may written
if(a==b && b==c )
printf(“The values of a,b,c form an equilateral triangle”);
else
printf(“ The values of a,b,c don‟t form an equilateral triangle”);
Example2.30: To check whether the values of three variables a,b,c form the sides of an isosceles
triangle the following code may written
if(a==b || b==c || a==c)
printf(“The values of a,b,c form an isosceles triangle”);
else
printf(“ The values of a,b,c don‟t form an isosceles triangle”);
Consider the expression exp1||exp2. If exp1 is true then exp2 is not evaluated.
Basics of C 37
2.10.4 Increment and decrement operators(++ and--)
These two operators are unary operators. They exists in two forms i.e. pre and post(prefix and
postfix)
i) Increment operator(++)
Increment operator is used to increment the value of its operand by 1.General form for pre
incrimination is
++ operand
and post incrimination is
operand ++
where the operand must be a variable but cannot be constant or expression.++operand is called pre
increment or prefix increment and operand++ is called post increment or postfix increment
Example2.33: pre incrementation
int i=20;
++i;
printf(“i=%d”,i);
output: i=21
Example2.34: post incrementation
int i=20;
i++;
printf(i=%d”,i);
output:i=21;
In the above example prefix and postfix operation results in the same output. The prefix and postfix
operations differ in the value used for the operand when it is embedded inside expressions
Example2.35: int x=10,y;
y=++x;
printf(“x=%d,y=%d”,x,y);
output: x=11,y=11
Here x value is incremented before it is assigned to y. So the expression y = ++x is equivalent to the two
expressions x=x+1 and y=x
Example2.36: int a=5,b;
b=++a*4;
printf(“a=%d,b=%d”,a,b)
output: a=6,b=24
Example2.37: int x=10,y;
y=x++;
printf(“x=%d,y=%d”);
output: x=11,y=10
Here value of x is incremented after it is assigned to y, thus the expression y=x++ is equivalent to the
expressions y=x and x=x+1;
Example2.38: int a=5,b;
b=a++*4;
printf(“a=%d,b=%d”,a,b);
output: a=6,b=20
Basics of C 38
General form is
--operand
or
operand--
where the operand must be a variable but cannot be constant or expression.--operand is called pre
decrement or prefix decrement and operand-- is called post decrement or postfix decrement
Example2.39: int i=10;
--i;
printf(“i=%d”,i ) ;
output: i=9
Example2.40: int i=10;
i--;
printf(“i=%d”,i);
output: i=9;
In the above example both the prefix and postfix operations results in the same value.
i) Simple assignment
The operator used is „=‟.
The general form is
Variable name=expression;
The value of the expression is evaluated first and is assigned to the variable. The evaluation of the
expression is right to left.
Example2.43:
x=10 a=10 && 5
y=12.5 a=x>y
a=”A”
area=0.5*b*h.
Note:
= is the assignment operator used to assign right side expression value to the left hand side variable.
= = is comparison operator to compare the value of left hand and right hand side expression.
a=b will assign b value to a
a==b will compare the values of a and b for equality.
Basics of C 39
The general form is
v1=v2=v3=expression;
The value of the expression is assigned to the variables v1, v2, v3 etc. the evaluation is right to left.
Example2.44: a=b=0.
a=b=x+y
The value of x+y is assigned to b and then the value of b is assigned to a.
iii) Compound assignment
Compound assignment is a short hand notation for a simple assignment.
The compound assignment operators are
+ =, - =, * =, / =, % =.
To evaluate a compound assignment expression, first change it to a simple expression.
Basics of C 40
Example2.48:To find absolute value of an expression y=(x>=0)? x: -x;
expression1,expression2,---
,expressionN
The expression are evaluated from left to right and the value of the right most expression is the result of
the overall expression.
Example2.51: int i=10,j;
j= ( i+=5, --i , i+20);
j is assigned the value 34.
where the operand may be name of the data type or constant or variable or expression.
Basics of C 41
Example2.55: printf(“char size is %d bytes\n” , sizeof (char));
printf(“long int size is %dbytes\n” , sizeof(double));
printf(“double size is %dbyte\n”,sizeof(double));
Example2.56: sizeof(13.56)
sizeof(239462l)
sizeof(896254ll)
sizeof(„*‟)
sizeof(a+b)
iii) address operator
General form is
&operand
Where the operand must be a variable name.This operator is used to determine the address of the memory
location allotted to a variable.
3472 10
3472
iv) Indirection operator
General form is
*operand
Where the operand must be a pointer.This operator is used to get the value at the address represented by
the pointer. This operator is also called de-referencing operator or value at address operator.
Example2.58: int x=10,y,*p;
p=&x;
y=*p;
The value 10 of x is assigned to the variable y.
The expression y=*p is equivalent to the expression y=x.
v) Cast operators
These operators are used to convert the data type of operand explicitly to another type.
The general form is
(data type name)expression
Where datatype is int, double, char , pointer etc.
Example2.59:(int)9.3 ,(double)15,(float)327,3/(int)7.2,(int)8.5/(int)4.3
Example2.60: int a=10,b=6;
float x;
x=(float)a / (float)b;
The values of a and b are substituted in the right side expression in floating point mode and the value
assigned to x is1.6666666
Basics of C 42
2.11 OPERATOR PRECEDENCE AND ASSOCIATIVITY
Precedence is used to determine the order in which different operators in a complex expression
are evaluated.
Associativityisused to determine the order in which operators with the same precedence are
evaluated in a complex expression.
The precedence and associativity of different categories operators is presented in the following table:
Operators Associativity
1 ( ),[ ], . , -> L to R
( ++ prefix), ( -- prefix), unary +, unary -, R to L
2
& (address), *(indirection), cast, !(negation)
3 *, /, % L to R
4 +, - L to R
5 <, <=, >, >= L to R
6 = =, != L to R
7 && L to R
8 || L to R
9 ?: R to L
10 =, +=, *=, -=, /=, %= R to L
11 , (comma operator) L to R
Basics of C 43
If a char and double are combined, char is converted to double.
The hierarchy of type conversion is summarized in the following table:
Data type Order
long double complex high
double complex
float complex
long double
double
float
unsigned long long
long long
unsigned long
long
unsigned int
int
unsigned short int
short int
unsigned char
char low
Example Action
x= (int) 3.7 3.7 is converted to integer by truncation
x= (int) 13.7/ (int) 4.3 Evaluated as 13/4 and the result would be 3
x= (float) (a + b) the result of the expression a + b is converted to float
p= cos( (double) x) converts x value to double before using it.
SUMMARY
C is a high level programming language. C language has 32 keywords and each of them has a fixed
meaning and form the building blocks for the programming statements. There are five basic data types in
ANSI C ,namely int, float, double, char and void .C99 has three more data types, namely complex, bool
and pointer. Except void other data types has qualifiers signed and unsigned, long, short and long long.
System will allocate three different size of space for each variable. Constants in C have fixed values. C
language is rich in operators and it contains 8 categories of operators: arithmetic, relational, logical,
increment and decrement, assignment, condition, bitwise and special operators. Expressions are formed
with variables, constants and operators. These operators certain precedence and associativity. If an
expression contains operands belonging to different data types automatic type conversion takes place
according to the predefined rules. Forced type conversion is also possible through cast operator.
EXERCISES
Basics of C 44
a) underscore b)uppercase alphabet c)lower case alphabet d)#
2.3 Which of the following is not a basic data type in C?
a) int b)double c)void d)printf
2.4 Which of the following is not a library function in C?
a) clrscr() b)exit() c)goto() d)getch()
2.5 What is the output of the following code?
char ch=‟A‟;
printf(“%d”,ch+10);
a)10 b)75 c)74 d)65
2.6 Regarding real values in C, which of the following is true?
i) A float occupies less memory than a double.
ii) The range of real numbers that can be represented by a double is less than those
represented by a float
a) only option i b)only option ii c)both i and ii d)neither i nor ii
2.7 Which of the following statements is/are true?
i)A char data type variable always occupies 1 byte independent of system
architecture.
ii)sizeof is a key word
iii)include is a key word.
iv)double is not a keyword.
a) both i&ii b) i only c)ii only d)neither i nor ii
2.8 The operator %d yields
a) Quotient value b)Remainder value
c)percentage value d)fractional part of the division.
2.9 What is the wrong assignment expression in the following?
float a ,b, x=8.2 , y=6.3;
a) a=x%6 b)b=x>y c)a=x+y/3.5 d)x-y*3.6
2.10 The modulus operator can be applied only to _____ types
2.11 What is the value assigned to x when the following statement is executed?
x = 2*8*6/ 15%13;
a) 96 b) 0 c) 13 d) 6
2.12 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int x = 10;
printf(“ %d , %d, %d “, x < = 20, x= 25, x >= 5);
}
a) 1,25,1 b) 1, 1, 1 c) 0, 1, 1 d) 0,25,1
Basics of C 45
a) x>=10&&x<=50||y==0 b)x<50 c)y!=10 d) x>=10|| x<=50||y==0
Basics of C 46
int a=10,b=6,c;
c=a++*b;
a)66 b)60 c) 16 d) 70
2.26 What is the value assigned to a?
int a, x=2;
a = x + 3 *++ x;
a) 11 b) 9 c) 12 d) 15
Basics of C 47
#include<stdio.h>
main()
{
int i = -3, j=2, k=0, m;
m= ++i && ++j || ++k;
printf(“ i = %d, j = %d, k = %d, m=%d\n”, i, j, k, m );
}
a)i= -2 , j=3 , k= 1 , m= 1 b) i= -2 , j= 3 , k=0 , m= 1
c) i= -2 , j=3 , k=0 , m= 1 d) i= -2 , j=3 , k= 1 , m= 0
2.35 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a = 0, b = 0, c;
c = (a+=2) && (b - = 1);
printf ( “ a = %d, b = % d, c= %d \n “, a, b, c);
}
a) a= 2 , b= 1 , c=0 b) a= 2 , b=-1 , c=1 c) a= 0 , b=0 , c=1 d) a=2 , b=-1 , c=0
2.36 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a=5,b,c;
b=++a;
c=a++;
printf(“a=%d,b=%d,c=%d”,a,b,c);
}
a) a=6 , b= 6 ,c=6 b) a=6 , b=6 ,c=7 c) a= 7 , b=6 ,c=6 d) a=7 , b= 6 ,c=7
2.37 What is the value of i and j
#include<stdio.h>
void main()
{
int i=3,j;
j= i++ + ++i;
printf("%d, %d",i,j);
}
a)8,7 b)5,9 c)5,8 d)5,7
2.38 What will be the output of the following program?
#include<stdio.h>
int main()
{
int i=5;
i=2+2++*i;
printf("%d",i);
return 0;
}
a)17 b)12 c)20 d)syntax error in the program
2.39 What are the values of k and i?
#include<stdio.h>
void main()
{
Basics of C 48
int i=5,k;
k= ++i + --i;
printf(“k=d, i=%d”,k,i );
}
a) k= 10 , i=5 b) k= 10 ,i=6 c) k=9, i=5 d)k=8,i=5
2.40 What is the output when the following code is executed?
main()
{
int a=20,b;
b=(a==1)?2:3;
printf(“\n a=%d,b=%d\n”,a,b);
}
a)a=20,b=2 b)a=1,b=2 c)a=20,b=3 d)a=1,b=3
2.41 What is the output when the following code is executed?
int a=5,b=6,c;
c=(a+b>a-b)?a*b : a%b ;
a)30 b)5 c)0 d)6
2.42 Whch of the following is a ternary operator?
a) ?: b)* c)sizeof d)&&
2.43 What is the output of the following program?
#include<stdio.h>
main()
{
int a = 5, b = 6, c ;
c = a < b ? a : a > b ? b : -1;
printf ( “ c = %d \n”, c );
}
a)c= -1 b) c= 6 c)c=5 d)c=0
2.44 What will be output of the following program?
#include<stdio.h>
void main()
{
int x;
x=(10,20,30);
printf("%d",x);
return 0;
}
a)10 b)30 c)20 d)none of these
2.45 Which of the operator is having highest precedence?
a) ,(comma) b)++ c)= d)&&
2.46 What is the output when the following program is executed?
#include<stdio.h>
void main()
{
float a= 7.8, b= 3.95, c, d;
c = (int) (a/b) ;
d = (int) a / (int) b;
printf( “ c = %d, d = %d \n”, c, d );
}
a) c=1 ,d= 2 b) c=2,d=2 c) c=1 ,d=1 d)c=1,d=0
Basics of C 49
Comprehensive Questions
2.1 What is the character set in C? write the syntax to declare and initialize int, float, character and
double type.
2.2 Discuss different built in data types available in C and give their size and range.
2.3 What are the different types of variables used in C programming? How do you assign values to
them?
2.4 Describe the format, width and search set for a scanf() statement in C with examples.
2.5 Explain the increment and decrement operators with suitable examples.
2.6 Explain the conditional operator with examples.
2.7 Explain the relational and logical operators with examples.
2.8 Explain the assignment operators, comma operator and sizeof operator with examples.
2.9 Explain arithmetic and relational operators with examples.
2.10 Explain the arithmetic and logical operators with examples.
2.11 What is conditional operator? Using conditional operator write a program to check whether a
number is even or odd.
2.12 Explain operator precedence and associativity rules followed in C through examples.
2.13 Discuss the implicit and explicit type conversion during expression evaluation.
2.14 Area of a triangle is given by the formula A = √s(s-a)(s-b)(s-c) where a,b,c are the sides of the
triangle and s= (a+b+c)/2. Write a program to compute area of triangle given the values of a,b and
c.
2.15 The solution to system of equation a1x + b1y =c1 and a2x + b2y = c2 is given by
x= (c1b2 –c2b1)/(a1b2 – a2b1)
y=(a1c2 –a2c1)/(a1b2 – a2b1)
Write a program to calculate and print the values of x and y.
2.16 A student appeared for an examination in 3 subjects. He will pass the examination if he secures at
least 40% marks in each subject. Write a program to accept the percentage marks in three subjects
from keyboard and check whether the student passed or failed the examination using conditional
operator.
2.17 Suppose that an automobile starts from rest and has constant acceleration „f‟ for „t‟ seconds. The
final velocity „v‟ and the distance travelled „d‟ by the automobile is given by the formula
v = u+ft and d = ut+1/2ft2
Write a program that reads f and t and prints t, d and v.
2.18 Write a program to read three numbers x1, x2 and x3 and compute their average „x‟ standard
deviation „sd‟ and the relative percentage „rp‟ for each number where
x= (x1+x2+x3)/3 sd2 = (x12 + x22 + x32- 3x2)/3
rp1= (( x1+ x2 + x3)/x1) * 100 and similarly for rp2 and rp3. Output the average standard
deviation and the three relative percentages.
2.19 Distance between two points (x1,y1) and (x2,y2) is governed by the formula D2=(x2-x1)2+(y2-y1)2
Write a program to compute D given the coordinates of the points
2.20 The straight-line method of computing the yearly depreciation of the value of an item is given by
Depreciation=(Purchase Price-Salvage Value)/Years of Service
Basics of C 50
Chapter 3
CONTROL STATEMENTS
LEARNING OBJECTIVES
After going through this chapter, the readers will be able to:
Learn different types of statements in C.
Develop algorithms and flow charts for simple engineering and mathematical problem
solving.
Write programs using if, if-else, nested if, nested if-else and else-if ladder.
Write programs using the looping structures while, do-while & for.
Learn usage of Jumping Statements: break, continue & goto in the programs.
3.1 INTRODUCTION
Control Statements determine the “flow of control” in a program and enable to specify the order in
which the various instructions in a program are to be executed by the computer. Normally high level
procedural programming languages require three basic control instructions.
The programming circumstances require selecting some statements for execution if some condition
is satisfied; and skipping the block of statements if the condition is not satisfied, thereby, resulting in a
change in the order of execution of statements. To be precise, selection of some statements for execution
depends on whether a condition is true or false. This kind of execution of statements is called
Conditional Execution or Selection.
Suppose, if there is a need for a group of statements to be executed repeatedly until some logical
condition is satisfied, then looping is required in the program. This can be carried out using various Loop
or Repetitive or Iterative control statements.
The Jumping statements are used to exit from loop or to go to the next repetition of the loop after
skipping the remaining statements of the loop or to transfer control from one part of the program to
another part of the program unconditionally.
The sequential control instruction ensures that the instructions are executed in the same order in
which they appear in the program. Decision and selection control instructions allow the computer to take
decision as to which instruction is to be executed next. The loop control instruction helps computer to
execute a group of statements repeatedly.
Decision and Selection control instructions allows a program to take different courses of action
depending on different conditions. C provides two selection structures.
if
switch
Control Statements 51
Repetition or loop control instruction allows a program to execute the same section of code more
than once. A section of code may either be executed a fixed number of times, or while some condition is
true. C provides three looping statements.
while
for
do-while
C provides three jumping statements
break
continue
goto
Assignment: A = A + 1;
Input: scanf(“%d”,&x);
goto: goto begin;
The C language uses semicolons as statement terminators. A semicolon follows every simple (non-
compound) statement.
Example3.1: if(x==y)
If the values of the variables x and y are same, then only the printf() statement gets executed. Otherwise,
it is skipped.
A set of simple or compound statements enclosed within a pair of opening and closing braces is
called a Compound Statement.
The terms compound statement and block both refer to a collection of statements that are enclosed in
braces to form a single unit. Compound statements have the form
Example3.2: {
printf(“….”);
scanf(“%d”,&a);
if(a>max)
max=a;
}
Example3.3: if(flag==1)
{
printf(“…”);
scanf(“%d”,&b);
}
Control Statements 52
3.3 NULL & EXPRESSIONS STATEMENTS
A "null statement" is an executable statement containing only a semicolon; it can appear wherever a
statement is expected. Nothing happens when a null statement is executed. The null statement is:
Statements such as do, for, if, and while require that an executable statement appear as the statement
body. The null statement satisfies the syntax requirement in cases that do not need a substantial statement
body.
;
Example3.4: for(i=0;i<10;line[i++]=0) ;
In this example, the loop expression of the for statement line[i++] = 0 initializes the first 10 elements
of line to 0.
3.3.2 Expression-statement
expression;
All side effects from the expression evaluation are completed before the next statement is executed.
x++; /* x is incremented */
i) if-statement
ii) switch-statement
3.4.1 if-statements
Control Statements 53
The syntax is as follows:
False
Condition
if(condition) ?
True
statement;
Statement
Exit
The above flow chart reflects the logical flow of the if statement. Where condition is the expression that
is to be evaluated .If this condition is true (non-zero), statement is executed. If it is false(zero), statement
is not executed and the program continues to the next instruction after the conditional statement.
Example3.6: if(a==b)
printf(“a and b are equal”);
if the values a and b are equal, then only the printf() statement gets executed. Otherwise, it is skipped.
Example3.7: if((a>b)&&(a>c))
If the value of the variable a is greater than the values of both b & c, then only the printf () statement gets
executed. Otherwise, the statement is skipped.
Example3.8: if(n%2)
printf(“n is odd”);
If the value of the variable n is not divisible by 2, i.e. if the remainder after division of n by 2 is 1, then
only printf () statement gets executed. Otherwise, the statement gets skipped.
Example3.9: if(a>b)
{
t=a;
a=b;
b=t;
}
Only when the value of a is greater than the value of b the statements within the pair of braces gets
executed. Otherwise, the statements are skipped.
If-else structure acts as a selector of one block of statements out of two blocks.
Control Statements 54
False True
Test-
Expression
if ( test-expression)
statement 1;
else
statement 2; Statement2 Statement1
statement x;
True Statements
The above flow chart reflects the logical flow of the if-else statement.
If test-expression evaluates to true, statement 1 will be executed, otherwise, statement2 will be executed.
Then the control is transferred to statement x.
The statement1 is called if-block and the statement2 flowing else is called else-block statement.
Example3.10: if(a>b)
printf(“a is larger than b”);
else
printf(“b is larger than a”);
Here if a is greater than b the message “a is larger than b“is displayed on the screen. Otherwise,” b is
larger than a” is displayed.
Example3.11: if(basic>5000)
{
da=basic*65;
hra=basic*15;
cca=200;
}
else
{
da=basic*57;
hra=basic*12;
cca=100;
}
Here, if the basic is greater than Rs.5000 then da and hra are calculated to be 65% and 15% of basic
respectively and the cca is assigned Rs.200. otherwise, i.e. the basic is less than or equal to 5000 than da
and hra are calculated to be 57% and 12% of basic respectively and cca is assigned Rs.150.
#include<stdio.h>
#include<conio.h>
int main(void)
{
int year, r4, r100,r400;
printf (“Enter a year\n”);
scanf (“%d”,&year);
Control Statements 55
Input-Output:
We know that if execution of a block of statements is conditional, we can use one if statement. What
if the conditional execution of the block of statements is itself conditional? Here, we need to enclose one
if statement within another if statement. On the similar lines, we can even enclose an if-else within
another if-else. If one if-else is enclosed within another if-else, the resulting structure is called nested if –
else.
if (test-expression 1 )
{ False True
if(test-expression 2) Test-expr
{
statement-1;
} False
else True
Statement Test-
{
Expression
statement-2;
}
}
Statement
else Statement
{
statement -3;
}
Here, one if-else is enclosed within another if-else. The if structure, which encloses another is called
outer-if. The if structure, which is enclosed within another is called inner-if. Statement-1, statement-2 and
statement-3 may be simple or block of statements. First, test-expression1 is checked. If it evaluates to
true, test-expression2 is checked. If test-expression2 also evaluates to true, then else-block of the inner-if,
statement-1 would get executed otherwise, statement-2 would be evaluated. If test-expression1 itself
evaluates to false, then else-block of the outer-if, statement-3 would get executed. Thus, this variation
acts as a selector of one out of three blocks of statements.
Control Statements 56
printf(“a is larger than b”);
else
printf(“a and b are equal”);
}
else
printf(“a is less than b”);
Example3.13: The following segment compares three values a ,b and c and collects the largest of them in
the variable largest.
if( a>=b)
{
if(a>c)
largest = a;
else
largest = c;
}
else
{
if(b>c)
largest = b;
else
largest = c;
}
3.4.1.4 The else-if Ladder
The else-if ladder helps select one out of many alternatives blocks of statements for execution depending
on the mutually exclusive conditions. The syntax of the else-if ladder is as follows.
False
if(test-expression 1) T
Statement-1;
True False
else if (test-expression2) T
statements True False
Statement-2;
else if(test-expression3) T
Statement-3; statements
True
: T - Test expression
statements
:
Statement -n;
else
Statement-
Here test-expression1, test-expression2… test-expression-n are mutually exclusive. That is only one test-
expression of all will be true. There are n+1 of statements. Initially, test-expression1 is checked. If it is
n+1;
statement x
Control Statements 57
true, then statement-1 would get executed; all the other blocks of statements would be skipped; then the
statement x gets executed. If test-expression1 is false, test-expression2 is checked. If it is true, then
statements-2 would be executed; all the other statements would be skipped. If test-expressions 2 is false,
test-expression3 is checked. If it is true, statements-3 would get executed; all the other statements would
be skipped. This is continued. In general, ith test-expressions is checked only when the first i-1 test-
expressions evaluate to false. If none of the expressions is found to be true, the last statement would get
executed. Thus, else-if ladder act as a selector of one out of n+1 blocks of statement.
void main()
{
int n;
printf (“Enter a number\n‟); Input-Output
scanf (“%d”,&n);
if(n>0) Enter a number
printf (“%d is positive”,n);
else if (number >0) 78
printf (“%d is negative”,n);
else 78 is positive number.
printf (“Zero”);
getch();
}
3.4.2 The Switch Statement
Switch statements provide a non-iterative choice between any numbers of paths based on specified
conditions. They compare an expression to a set of constant values. Selected statements are then executed
depending on which value, if any, matches the expression. Switch statements have the form
Here, expression is an integer or character expression. It evaluates to either integer or a
character.Value1, value 2…. Value N is the case values. The expression of the switch statement can take
any of the values. If it matches with value1, statement-1 will get executed and the break statement
following it causes the skipping of the switch structure. If the expression matches with value2, then
statement2 will get executed. If the value of expression matches with none of the case values then default
option will get executed.
Control Statements 58
switch ( expression) Test-expr
{
case value1:statement-1;
break;
case value2:statement -2; Case1 Statements1
break;
.
Case2 Statements1
.
case value n:statement -n;
break; Case3 Statements1
default :default statement;
break;
} Statements1
default
Points to Remember:
Control Statements 59
case 9 : Printf( “Nine”); break;
default : Printf( “Not a digit ”); break;
}
getch();
}
3.5 Looping or Iterative or Repetitive Statements in C
The repetition of execution of a block of statements as long as some condition is true is called
Looping. Looping is also called as Iteration.
i) while-loop
ii) for-loop
iii) do-while loop
When in a program a single statement or a certain group of statements are to be executed repeatedly
depending upon certain test condition, then while statement is used
The general form ofwhile loop is as follows:
while (expression)
Statement;
The statement may be simple or compound statement. The keyword “while” is followed by expression
enclosed within a pair of parenthesis. The expression can be an arithmetic expression, relational
expression or a logical expression. The expression is then followed by a set of one or more statements,
which are expected to be repeatedly executed.
The execution sequence effected by while looping construct is best illustrated by the following flow chart
segment.
Initialization
False
Test-
Expression
True
Statements
Example3.16: i=1;
sum =0;
while (i<=10)
{
sum+=i;
i++;
}
Control Statements 60
The purpose of the code is to find the sum of the first 10 natural numbers
Example3.17:while ((ch=getchar())!=‟\n‟)
{
printf (“%c\n”,toupper(ch));
}
The segment code enables us to accept characters of a line, one at a time till the new line character is
entered. Each character entered is converted to upper case and displayed.
After getting familiarized with the syntax and examples of the usage of the while loop, we will now write
some programs which make use of it.
Statement is executed repeatedly until the value of expr2 is 0. Before the first iteration, expr1 is evaluated
and then expr2 is evaluated. If expr2 is non-zero then only control enter the loop .expr1 is usually used to
initialize variables for the loop. After each iteration of the loop, expr3 is evaluated. This is usually used to
increment a loop counter. In fact, the for-loop is absolutely equivalent to the following sequence of
statements:
expr1;
while (expr2)
{
statement;
expr3;
}
Control Statements 61
That's why expr1 and expr3 must contain side effects, else they are useless.
Example3.18: for (i=0; i<100; i++)
printf(“%d\t”,i);
All the expressions are optional. If expr2 is left out, it is assumed to be 1. Statement may be a compound
statement as well.
The execution sequence effected by for looping construct is best illustrated by the following flow chart
segment.
Expression 1
False
Expression 2
TRUE
Statement
Expression 3
printf(“%d\n”,j);
Control Statements 62
Input-output:
scanf(“%f”,&x); Enter the number of values 6
large=x; Enter the first number 10
printf(“Enter the reaming numbers”);
Enter the reaming numbers
for ( i=1; i <n; ++i)
{ -3
scanf(“%f”,&x); 23
if(x>large) 78
large=x; -220
} 5
printf(“Largest of given numbers =%f\n”,large); Largest of given numbers=78
getch();
}
Program3.6: Program to generate multiplication table of a number
#include<stdio.h>
#include<conio.h>
void main() Input –Output:
{ Enter a number: 6
The multiplication of 6 is:
int num,i,product;
6 * 1 =6
printf( “\n Enter a number:”);
6 * 2=12
scanf(“%d”,&num); .
printf(“The multiplication table of %d is:”,num); .
for( i=1;i<=10; i++) .
{ 6 * 10 = 60
product= num*i;
printf( “%d * %d = %d \n”,num,i,product);
}
getch();
}
As mentioned earlier a for loop can be written without any one of the expressions or two expressions or
all the three.
Example3.20: for(sum=0;n>0;)
{
digit=n/10;
sum+=digit;
n/=10;
}
Here the segment is to find the sum of digits of a given integer. The loop is written without expression3.
#include<stdio.h>
void main() Input-output:
{
int a,b,rem,temp1,temp2; Enter two integers 36 24
printf(“Enter two integers”);
scanf(“%d%d”,&a,&b); gcd(36,24)=12
temp1=a; temp2=b;
for(;(r=a%b)>0;)
{
a=b;
Control Statements 63
b=r;
}
printf(“gcd(%d,%d)=%d\n”,temp1,temp2,b);
}
In the above program the loop is written without expression1 and expression3.
for( ; ; )
{
statements block;
}
The while and for loops test the termination condition at the top. By contrast, the third loop in C, the
do-while, tests at the end after making each pass through the loop body. Hence the body is always
executed at least once.
Thus while & for loops are entry-controlled loops, whereas do-while is exit controlled loop.
Initialization
Statements
do {
statements;
True
the statement block is executed, and then expression is evaluated. If it is true, statement block is evaluated
again, and so on. When the expression becomes false, the loop terminates.
Example3.21: i=1;
sum=0;
do
{
sum+=i;
i++;
}while ( i<= 10);
Control Statements 64
The statements in the body of the loop get repeatedly executed as long as i< =10 and it finds the sum of
the first 10 natural numbers.
Example3.22: do
{
scanf(“%d”, &n);
printf(“Do you want to continue? Enter Y or N”);
ch = getchar();
} while ( ch ==‟Y‟);
The above segment of code enables us to keep accepting integer value into the variable n as long as we
enter „Y‟ to the variable ch. Once we input „n‟ response to the statement ch = getchar (); the loop is
exited.
Like the method of if-else structures, loops also can be nested. In nested loops one loop should be
completely embedded within the other. There can be no overlap. The inner and outer loop structures can
be different.
Control Statements 65
for(i=1;i<n;++i) for(i=1;i<n;++i)
{ {
..... .......
..... .......
while( expression) for(j=1;j<n;j++)
{ {
…….. .....
………. .....
} }
....
}
Program 3.9 Program to print all prime numbers between two limits.
#include<stdio.h>
#include<math.h>
void main()
Input-output:
{
int ll,ul,k,n,r; Enter the lower and upper
printf(“Enter the lower and upper limits\n”); limits10 20
scanf (“%d%d”,&ll,&ul); The prime numbers between 10
printf (“The prime number between %d and %d are\n”,ll,ul); and 20 are
for( n=ll;n<=ul;++n)
{ 11
k=sqrt (n); 13
for (i=2;i<=k;++i) 17
{ 19
r=n%i;
if(r==0)
break;
}//end of inner for loop
if (i>k)
printf (“%d\n”,n);
}//end of outer loop
}// end of main
Inner for loop is written to check n is prime or not. Outer loop is written to execute this loop repeatedly
for n=ll to ul.
Jump statements transfer control unconditionally from one part of the program to another part of the
program.
i) goto identifier
ii) continue
iii) break
So far we have discussed ways of controlling the flow of execution based on certain specified
conditions. Like many other languages, C supports goto statement to branch unconditionally from one
point to another in the program. Although it may not be essential to use goto statement in a highly
structured language like C, there may be occasions when the use of goto might be desirable.
Control Statements 66
The goto require a label in order to identify the place where the branch is to be made. A label is
any valid variable name, and must be followed by a colon. The label is placed immediately before the
statement where the control is to be transferred. The general forms of goto and label statements are
shown below.
------ statement;
------ ------
------ ------
------ ------
Forward
label : jump goto label jump
Backward :
statement;
The label can be anywhere in the program either before or after the goto label; statement. During
running of a program when a statement like
goto begin;
is met, the flow of control will jump to the statement immediately following the label begin:. This
happens unconditionally.
Note that a goto breaks the normal sequential execution of the program. If the label: is before the
statement go to label; a loop will be formed and some statements will be executed repeatedly. Such a
jump is known as a backward jump. On the other hand, if the label: is placed after the go to label; some
statements will be skipped and the jump is known as forward jump.
A goto is often used at the end of a program to direct the control to go to the input statement, to read
further data.
Example3.23:double x, y;
read :
scanf(“%d”, &x);
if (x<0)
goto read;
y=sqrt(x);
printf(“%f %f”, x,y);
goto read;
The above example evaluates the square root of a series of numbers read from the terminal. The
program uses two goto statements, one at the end, after printing the results to transfer the control back to
the input statement and other to skip any further computation when the number is negative.
Due to the unconditional goto statement at the end, the control is always transferred back to the input
statement. In fact, this program puts the computer in a permanent loop known as an infinite loop. The
Control Statements 67
computer goes round and round until we take some special steps to terminate the loop-such infinite loops
should be avoided.
Sometimes, it is required to jump out of a loop irrespective of the conditional test value. Break
statement is used inside any loop to allow the control jump to the immediate statement following the
loop. The syntax is as follows:
break;
When nested loops are used, then break jumps the control from the loop where it has been used. Break
statement can be used inside any loop i.e., while, do-while, for and also in switch statement.
Unlike break statement, which is used to jump the control out of the loop, it is sometimes
required to skip some part of the loop and to continue the execution with next loop iteration. Continue
statement used inside the loop helps to bypass the section of a loop and passes the control to the
beginning of the loop to continue the execution with the next loop iteration. The syntax is as follows:
continue;
Let us see the Program 3.1 given below to know the working of the continue statement.
Program3.11 Program to print first 20 natural numbers skipping the numbers divisible by 5.
#include<stdio.h>
void main ( )
{
int i ;
Control Statements 68
for( i=1, i<=20; i++;
{ Output:
if(i%5)= = 0) 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19
continue;
printf(“%d”,i);
}
}
Here, the printf statement is by passed each time when value stored in i is divisible by 5.
Program3.12 Program to find sum of all non-negative integers in a list of n integers entered through key
board
void main()
{ Input-output:
int i,sum=0,n,x; Enter the number of values
printf(“Enter number of values”); 5
scanf(“%d”,&n); Enter the values
printf(“Enter the values”); 2
for( i=1;i<=n;i++) -12
{
5
scanf (“%d”,&x) ;
0
if( n <0)
continue; -4
sum+ = n; sum= 7
}
printf(“sm=%d\n”,sum);
}
SUMMARY
The program statements in C fall into three general types: assignment, input/output, and control. C has
two types of control structures: selection (decision) and a repetition (loops). The decision control
constructs are of two types: conditional and unconditional. The conditional control constructs are if, if-
else, if-else-if and switch. The unconditional control constructs are break, continue and goto. The loop
control constructs are for, while and do-while.
One-way decisions are handled with an if statement that either does some particular thing or does
nothing at all. The decision is based on a test expression that either valuates to true or false. Two-
way decisions are handled with if-else statements that either do one particular thing or do another.
Similar to one-way decisions, the decision is based on a test expression. Multi-way decision
statements use if-else-if ladder or nested ifs, or switch statements. They are all used to evaluate a test
expression that can have several possible values selecting different actions.
In a program by using loop control statements while, for, do-while you can execute set of statements
repeatedly, while and for are called entry-controlled loop which means that testing a condition is
checked before starting a loop. Do-while is called as exit-controlled loop in which the testing a
condition is checked after executing the loop.
Control Statements 69
Using break statement, we can leave a loop even if the test condition for its end is not fulfilled. It can
be used to end an infinite loop, or to force it to end before its natural end. The continue statement
causes the program to skip the rest of the loop in the present iteration as if the end of the
statement block would have reached, causing it to jump to the next jump iteration.
Using goto statement, we can make an absolute jumpto another part of the program. You should use
this feature carefully since its execution ignores any type of nesting limitation.
EXERCISES
Control Statements 70
z+=10;
else
z+=20;
}
a)21 b)11 c)1 d)the expression x=y%2 is not allowed
3.7 Which of the following is the correct output for the program given bellow?
#include<stdio.h>
int main()
{
float a=0.7;
if(0.7>a)
printf(“hi \n”);
else
printf(“hello \n”);
return 0;
}
a)Hi b) hello c)hi hello d)None of the above
3.8 Which of the following statements are correct about the problem given below?
#include<stdio.h>
main()
{
float a = 2.8, b = 2.87 ;
if (a = b)
printf(“ a and b are equal \n”);
else
printf(“a nd b are not equal \n”);
}
Control Statements 71
a)The statement if (a = b) results in a compilation error.
b)floats cannot be compared using if
c)conditional operator should be used to compare floats
d)switch_case should be used to compare floats.
3.9 What is the output when the following code is executed?
#include<stdio.h>
void main()
{
int a=0,b=1;
if(a<b || ++b)
a=5;
else
b=6;
printf(“a=%d ,b=%d \n” a,b);
}
3.10 What is the output when the following code is executed?
#include<stdio.h>
void main( )
{
int x=1,y=3,z=0;
switch(x)
{
case 0: x=2;
y=3;
break;
case 1: x=4;
break;
default : ++x;
}
printf (“x=%d,y=%d, z=%d”,x,y,z);
}
3.11 Originally x=4,y=3 and z=0 . What are values of x,y,z after executing the following code?
switch(x)
{
case 0 : x=2;y=3;
case 1 : z=4; break;
default : ++x;
}
a)x=0,y=3,z=4 b)x=2,y=3,z=4 c)x=1,y=3,z=4 d)x=5,y=3,z=0
3.12 When is default statement executed in switch case construct?
a) When ever there is exactly one match.
b)When ever break statement is omitted in all case statements
c)When ever there is no match with case labels.
d)options b and c.
3.13 Consider the following program segment
int n sum=1;
switch(n)
{
case 2: sum=sum+2;
case 3: sum*=2;
Control Statements 72
break;
default : sum=0;
}
If n=2 ,What is the value of sum
a)0 b)6 c)3 d)None of these
3.14 What will be printed by the following code?
#include< stdio.h>
main()
{
int x = 5;
switch(x);
{
case 5 : printf (“%d\t”, x * x) ;
case 6 : printf(“%d\t”, x + 1 * x+1);
default : break;
}
}
3.15 Omitting the break statement from a particular case in switch case construct
a) leads a syntax error
b)causes execution of the program to terminate after the case
c) causes execution to continue all subsequent cases.
d) causes execution to branch to the statement after the switch statement
3.16 How many times of the while loop in the following program will be excuted.
void main()
{
int j=1;
while(j<=255);
{
printf(“%d\n”,j);
j++;
}
}
Control Statements 73
printf(“%d\n”,j);
j=j+1;
}
}
3.19 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
while(i<=10);
{
printf(“%d”,i);
++i;
}
}
a) First 10 natural numbers can be displayed b) 11
c) Natural numbers starting from 1 are displayed indefinitely d) no output.
3.20 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a=5;
while(a-- >0)
printf(“%d\t”,a);
}
3.21 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int p=5;
while(p<8)
{
printf(“%d”,p);
p=9;
}
}
a)5 6 7 b)5 c)5 9 9 9 9 … d) no output
3.22 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int x=1;
while(1)
{
printf(“%d”,x);
++x;
}
}
3.23 What will be the output when the following code is executed?
#include<stdio.h>
main()
Control Statements 74
{
int a = 6;
while (a)
{
printf(“%d\t”, a);
a == 2;
}
}
3.24 What will be the output when the following code is executed?
void main()
{
int i;
for(i=0; j<=10; i++, printf(“%d \t”, i));
}
3.25 What will be the output when the following code is executed?
void main( )
{
int i;
for(i=0; i<3; i++)
printf(“%d\t”, i);
}
3.26 What will be the output when the following code is executed?
void main()
{
int a;
for(a=1;a<=32767;a++)
printf(“%d”,a);
}
3.27 What will be the output when the following code is executed?
void main()
{
int i=0;
for(;i++;)
printf(“%d”,i);
}
3.28 Which of the following statement is used to exit from a switch case statement?
Control Statements 75
}
a) prints numbers from 10 to 0 b) prints numbers from 10 to 1
c) prints numbers from 10 to -1 d)An indefinite loop is formed
3.33 How many times x is printed?
for(i=0,j=10;i<j;++i,--j)
printf(“x”);;
a)10 b)5 c)4 d)none
3.34 what is the value of a after the following code is executed?
void main()
{
int b,a=0;
for (b=0;b<10;b++)
{
switch(b)
{
case 0:
case 1:
case 2:
case 5:
++a;
case 3: break;
case 4: break;
default: break;
}
}
3.35 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
for(i=1;i<10;++i)
printf(“%d”,i);
}
a) First 10 natural numbers can be displayed b) 11
c) Natural numbers starting from 1 are displayed indefinitely d) no output.
3.36 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a=5;
for(a=5;a-- >0; )
printf(“%d\t”,a);
}
3.37 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a;
for(a=10;! i;-- i)
printf(“%d”,i);
}
Control Statements 76
a) First 10 natural numbers are printed in reverse order b)11
c) 10 d) no output.
What is the output when the following program is executed?
#include<stdio.h>
main()
{
int b;
for(b=3;b<10;b=7)
printf(“%d”,b);
}
a)3 4 5 6 7 8 9 b)3 7 8 c) 3 7 7 7 7 … d)3
3.38 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
for(i=10;++i;i-=5)
printf(“%d”,i);
}
3.39 What would be the output when the following program is executed?
#include<stdio.h>
main()
{
int i=5;
for(--i;--i;--i)
printf(“%d”,i);
}
3.40 What would be the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
for(i=0;i--;i--)
printf(“%d”,i);
}
3.41 What would be the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
for( ;x>0;d=x%10,sum+=d,d/=10);
printf(“%d”,sum);
}
3.42 What is the output when the following code is executed?
#include<stdio.h>
main()
{
int p;
for(p=-10 ; !p ; ++p)
printf(“\n%d”,--p);
}
Control Statements 77
3.43 Identify the error in the following program?
#include<stdio.h>
main()
{
int x=10,y=0;
do{
y+=x;
--x;
}while(x)
printf(“\n%d ” , y);
}
3.44 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a=10;
do
{
printf(“%d”,a);
--a;
}while(a<=1);
}
Control Statements 78
for(j=1;j<=3;++j)
printf(“%3d ”,i+j);
printf(“\n”);
}
}
3.49 What is the output when the following code is executed?
{
for(i=1;i<=5;++i)
{
if(i<=4)
break;
printf(“%d”,i);
}
}
3.50 What is the output when the following program is executed?
void main ( )
{
int num, sum;
for(num=2, sum=0; ;)
{
sum=sum+num;
if (num>10)
break ;
num = num+1;
}
printf(“%d”, sum);
}
3.51 What is the output when the following program is executed?
void main( )
{
int i=5;
while (i)
{
i=i-1;
if(i = = 3)
continue;
printf(“\n hello”);
}
}
3.52 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a=1;
while(a<=5)
{
if(a==2)
continue;
printf(“%d\t”,a);
++a;
}
Control Statements 79
}
3.53 How many times KLU is displayed when the following code is executed?
#include<stdio.h>
main()
{
int x;
for(x=-1;x<=5;++x)
{
if(x<3)
continue;
else
break;
printf(“KLU \n”);
}
3.54 What is the output when the following program is executed?
void main ()
{
int i,j;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
for(j=1;j<=i;j++)
{
if(j==3)
break;
printf(“%d”,i*j);
printf(“\n”);
}
}
}
3.55 What is the output when the following program is executed?
#include<stdio.h>
main ()
{
int x=1;
for( ; ; )
{
if(x==3)
break;
printf(“%d\t”,x);
break;
}
}
3.56 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;++i)
{
Control Statements 80
if(i==3)
continue;
printf(“%d\t”,i);
}
}
3.57 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
for(i=1;i<=10;++i)
{
if(i==3)
break;
printf(“%d \n”,i);
}
}
3.58 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i=1;
for( ; ; )
printf(“\n %d”,++i);
if( i>5)
break;
}
3.59 Difference between while and do-while?
3.60 Distinguish between break and continue statements?
Comprehensive Questions:
Control Statements 81
f(x) = { 10x2 -5x+4, if x<=0
Write a program to find the value of the function for given value of x.
3.7 Write a C program to print the roots of a quadratic equation after reading the value of
its coefficients a, b and c.
3.8 Write a program to convert the temperature from Fahrenheit to Centigrade and vice versa.
3.9 Write a program to accept the sides of a triangle and check whether a triangle is formed
or not. If formed determine the nature of the triangle(scalene, isosceles, equilateral).
3.10 write a menu driven program to compute electricity bill taking different categories
of users for different slabs.
3.11 In Mechanical System the applied force p is expressed as function of t in
{ 20 , if t<=3
Calculate and print the force dependent on the time provided by the user
at the prompt.
3.12 A company sells five different products with prices shown in the following table.
1 15.50
2 19.25
3 14.75
4 25.00
5 12.50
Write a program using switch-case construct that reads the product number and number
of units sold and display the amount to be paid.
3.13 The price for one copy of a software package is Rs 5000/-. The discount for the software depends
on the volume as shown in the table below
Number of copies Discount
num<10 10%
Write a program to calculate the cost with the number of copies of the softwarepackage provided
by the user at the prompt.
3.14 A company sells five different products with prices shown in the following table:
Product Number Retail Price Per unit (in Rs.)
1 15.50
2 19.25
3 14.75
4 25.00
5 12.50
Control Statements 82
3.15 Write a program using switch-case construct that reads the product number and number of units
sold and display the amount to be paid.
3.16 Write a program that determines a student‟s grade. It reads three tests scores (between 0 to 100)
and calls a function that calculate and returns a student‟s grade based on the following rules:
a)If the average score is 90% or more, the grade is A.
b)If the average scores are 70% or more and less than 90%, it checks the third score. If the third
score is more than 90%, the grade is A; otherwise, the grade is B.
c)If the average score is 50% or more and less than 70%, it checks the average of the second and
third scores. If the average of two is greater than 70%, the grade is C; otherwise, it is D.
d)If the average score is less than 50%, then the grade F.
3.17 Write a program that accepts 0, 1 or 2. If 0 is entered by the user, accept the necessary parameters
(radius, height etc.,) to calculate the volume of a cylinder. Inputs 1 and 2 correspond to cylinder
and cone respectively. The process must go on until the user enters „q‟ to terminate the program.
3.18 Given an integer between 0 and 6, write a program that prints the corresponding day of the week.
Assume that the first day of the week (O) is Sunday.
3.19 Write for loop to find the sum of squares of first N-natural numbers.
3.20 Write a program to find a factorial of a given integer.
3.21 Write a program to display the image of given number.
3.22 Write a program the prompts the user enter an integer ,n and then a floating point number as the
numbers are read the program will calculate the average of the positive numbers.
3.23 Euler‟s number,e, is used as the base of natural logarithms. It can be approximated using the
following formula;
e=1+1/1! +1/2! +1/3! +1/4! +1/5! +1/6! + . . . +1/ (n-1)! +1/n!
3.24 Write a program that approximates e using a loop that terminates when the difference between two
successive vales of e differ by less than 0.0000001.
3.25 Write a program to evaluate the following investment equation v=P (1+r) n and print the tables
which would give the value of v for various combinations of the following values of p,r and n.
P: 1000, 2000, 3000. . . , 10000
r: 0.10, 0.11,0.12,. . . ,0.20
n: 1, 2,3,. . . 10
(Hint, P is the principal amount and V is the value of money at the end of n years. The equation
can be recursively written as
V=P(1+r)
P=V
That is, the value of money at the end of first year becomes the principal amount for the next year
and soon.)
3.26 Write a program to print the following triangle
*
* *
* * *
* * * *
th
- - - upto n line
Control Statements 83
*
* *
* * *
* *
1
1 2
1 2 3
1 2 3 4
th
- - - - upto n line
1 2 3 5 8 13 21. . .
are called Fibonacci numbers. Write a program using a do-while loop to calculate and print the first m
numbers.(Hint: After the first two numbers in the series, each numbers is the sum of the two Preceding
numbers.)
3.28 Write a program that calculates and print the average of several integers. Assume that
the last value read with scanf () is sentinel number 9999.
3.29 Caluclate the values of the function
f(x) = 2xsinx +tan-1(x)+ex for x in the range of -1<=x<=5 with a step size of 0.25
3.30 Write a program that reads an integer and determines if it is a prime number. If it is not a prime
number, print out the smallest divisor. Otherwise, print out the prime number.
3.31 Write a program to read an integer number between 0 and 25. Print out the character
corresponding to the input number of the ASCII value. Give an error message if the
input number is outside the specified range. The program terminates when the input
number is -1.
3.32 The cosine function can be expanded as a Taylor series as follows:
cosx = 1- x2/2! + x4/4! – x6/6! + ------ . Write a program to find the value of cosx to a given
precision.
3.33 The sin function can be expanded as a Taylor series as follows:
sinx = x- x3/3! + x5/5! – x7/7! + … . Write a program to find the value of sinx to a given
precision.
3.34 The Taylor series expansion of ex is
ex=1+x+x2/2!+x3/3!+… Write a program to find the value of ex to a given precision
3.35 Calculate the values of the function
f(x,y)= x2-y2+5xy for x in the range of -1 ≤ x ≤ 5 with a step of size 1 and for y in the range of
2 ≤ y ≤ 4 with a step of size 0.5.
3.36 Write a program to check given number is prime or not.
3.37 Write a program to display the image of a given number.
3.38 Write a program to print the values of the function
Control Statements 84
f(x) = 3ex+ 4 sinx + 0.6 for x=0,0.1,0.2,………….1.0
3.39 Write a program to find maximum among a given list of numbers entered through keyboard
Stop reading the data whenever zero is entered.
3.40 Write a program to find the average of a given list of numbers entered through keyboard .Stop
reading the data whenever -1 is entered.
3.41 Write a program to find the sum of the first n terms of the series
Sin x = x – x3/3! + x5/5! - x7/7! + ---------
3.42 What are the various looping statements? Explain the syntax giving one example to each.
3.43 Write a program to read a particular number and to check whether it is a perfect number or not.
3.44 Write a program to print first n Fibonacci elements.
3.45 Write a program to check if a given number is an element of Fibonacci sequence.
3.46 Write a program to check if a given number is Armstrong or not.
3.47 Eulers formula e is used as the base of natural logarithm . It can be approximated using:
Write a program that approximates e using a loop that will be terminated when the new term of
the series is less than 0.000001.
3.48 To evaluate ∫ab f(x) dx,by numerical integration , divide the interval [a, b]into n sub-intervals,
taking the equidistant points of subdivision as
x 0, x1, …, xn . The trepizoidal rule is
Control Statements 85
3.64 Write a program to print all values of the function f(x,y)= ex+y-2(x+y) for all combinations of
x= -5,-3,-1,1,3,5 and y = 0, 0.5, 1.0,1.5,……………. 10.0.
3.65 Write a program to display each digit of a number as many times as the digit.
3.66 Write a program to check a given number is strong or not.
3.67 Given a set of integer numbers containing positive negative and zero values. Write a program to
find average of only positive values using continue statement.
3.68 Create an infinite for loop check each value of the for loop .If the value is odd display it otherwise
continue with iterations. Print even numbers from 1 to 100 use break statement to terminate the program.
Control Statements 86
Chapter 4
ARRAYS
LEARNING OBJECTIVES
After going through this chapter the reader will be able to
declare and use one-dimensional and two-dimensional arrays
initialize arrays
use subscripts to access individual array elements
write programs involving one-dimensional and two-dimensional arrays
write programs for matrix operations
4.1 INTRODUCTION
For example, we wish to arrange the total marks obtained by 100 students in ascending order. To do this,
it is needed to store all 100 values in the memory simultaneously. In this situation an array is used.
What is an array?
An array is a collective name given to a group of related quantities belonging to same data type. These
related quantities can be total marks of 100 students or salaries of 500 employees or heights of 200
students. For example, we can use an array name tmarks to represent a set of total marks of a group of
100 students in a class. We can refer to the individual marks by writing a number called index or
subscript in square brackets after the array name.
Example4.1:
To store the total marks of 100 students an array will be declared as follows,
float tmarks[100];
tmarks [0], tmarks [1], tmarks [2] etc. represents the total marks of 1 st, 2nd, 3rd etc. students. In general,
tmarks[i], i can take values 0,1,2,3, represent the total marks of (i+1)th student. Here tmarks is the array
name and i is its subscript.
Thus the array tmarks is the collection of 100 memory locations referred as below:
Arrays 87
In the above figure, it is assumed that integer value occupies 2 bytes. Thus 200 bytes of space will be
allocated to the array tmarks.
We can use arrays to represent not only single lists of values but also tables of data(like matrix, marks of
100 students in 6 subjects, sales of a departmental store in a week) in two, three or more dimensions.
This chapter explain the use of arrays, types of arrays, declaration and initialization of one dimensional
and two dimensional arrays with the help of examples.
Before discussing an array, first of all let us look at the characteristic features of an array
i) Array is a data structure storing a group of elements, all of which are of the same
data type.
ii) All the elements of the array share the same name, and they are distinguished from one another
with the help of an index called subscript
iii) Random access to every element using a numeric index (subscript) is possible
iv) A simple data structure which is extremely useful
The declaration of an array is just like any variable declaration with additional size part, indicating the
number of elements of the array. Like other variables, arrays must be declared at the beginning of a
function.
The declaration specifies the data type of the array, the name and its size or dimension.
data-type array-name[constant-size]
[constant-size];
data-type refers to the type of elements to store and constant-size is the maximum number of elements.
It is convenient to define array size in terms of a symbolic constant rather than a fixed integer quantity.
This makes it easier to modify a program that utilizes an array, since all references to the maximum array
size (eg. within for loops as well as in array definitions) can be altered simply by changing the value of
the symbolic constant.
Arrays 88
4.3 SUBSCRIPT
To refer the elements of an array subscript is used. In an array a with 50 elements, the individual
elements are referred by a[0], a[1], a[2], . . , a[48], a[49] as shown below:
The sub scripts of an array can be integer constants, integer variables or expressions that yield integers.
Example4.4:
If we want to represent a set of 5 numbers, say {10, 4, 18, 20, 35} by an array variable a, then we declare
the array a as follows:
This could cause the array a to store the values as shown below:
10 4 18 20 35
When an array is declared, memory is allocated automatically with respect to its type and size.
Array elements are stored in contagious memory locations. For example, a sample layout for the one-
dimensional integer array a of size 6 elements declared as
2000 1
2002 2
2004 3
2006 4
2008 5
2010 6
a[0],a[1],a[2],………… represent the first, second, third etc. elements of the list &a[0],&a[1],&a[2] etc
represent the addresses of the first, second, third etc positions of the array
Arrays 89
4.5 INITIALIZATION OF ARRAY
After an array is declared, its elements must be initialized. Otherwise, they will contain
“garbage”. An array can be initialized at either of the following stages.
i) At compile time
ii) At run time
Arrays can be initialized at the time of declaration. The initial values must appear in the order in
which they will be assigned to the individual array elements, enclosed within the braces and separated by
commas.
val1 is the value for the first array element, val2 is the value for the second array element, and valn is the
value for the nth array element.
Arrays 90
Example4.8: int = {10, 5, 8, 12, 7, 14, 20};
would result in syntax error.
An array can be initialized without specifying the array size. In this case, the number of
initializers is used to determine the size of the array.
The first 5 elements of the array a are initialized to zero while the remaining 15 elements are initialized
to 1 at run time.
int ;
will initialize the array elements with the values entered through the keyboard.
Program 4.1 Program to store n values in an array and display them in reverse order
#define SIZE 50
void main( )
{
int a[SIZE],i,n;
printf(“Enter the number of values: “);
scanf(“%d”,&n);
printf(“Enter the values: “);
for(i=0; i<n; ++i)
scanf(“%d”,&a[i]);
printf(“Given values in reverse order is: \n”);
for(i=n-1; i>=0; --i)
printf(“%d\n”,a[i]);
}
Arrays 91
Program 4.2 Program to find the mean of n values.
#include<stdio.h>
#include<conio.h>
#define SIZE 50
main ( )
{
float a[SIZE], sum, mean;
int n,i;
clrscr ( );
printf(“Enter the number of values : ”);
scanf(“%d”, &n);
printf(“Enter the values : ”);
for (i=0; i < n; ++i)
scanf(“%f”, & );
/* find sum */
sum = 0 ;
for (i=0; i < n; ++i)
sum = sum + ;
mean= sum / (float)n ;
printf (“Mean of the n values : = % f \n”, mean);
}
Program 4.3 Program to arrange a list of numbers in increasing order.
To arrange a list of numbers in order is called sorting. Many sorting methods are available in literature.
The present program uses a simple sorting method known as Bubble sort.
If the list contains n elements, this method require (n-1) passes. In the first pass, adjacent pairs of
elements , ... are compared and the larger element is
pushed down. After the first pass largest element is pushed down to the last location. In the second pass,
the pairs of elements , ... are compared and the larger
element is pushed down . At the end of second pass, second largest element is pushed down to the last
but one location. Like this at the end of the (n-1)th pass, entire array will be re-arranged in increasing
order.
if
temp = ;
= temp;
Arrays 92
This loop is to be repeated (n-1) times for the values of pass number p=1,2,3,…..,(n-1).
Given a list of n numbers, the program will search for a given number say, key in the list. Compare key
with ,a[n-1], whenever the key match with one of the values of the list stop the
comparisons and display a message that the number is found in the list. If the key does not match with
any element of the list display the message that the number is not found in the list.
# include<stdio.h>
# include<conio.h>
# define SIZE 50
void main ( )
{
int i, key, n, flag = 0;
int
clrscr( );
printf(“Enter the number of values in the list: ”);
scanf(“%d”, & n);
Arrays 93
printf(“Enter the values : ”);
for(i=0; i < n; ++i)
scanf(“%d”, & );
printf(“Enter the number to be searched:”);
scanf(“%d”, &key);
for(i=0; i<n; ++i)
{
if(key = = )
{
flag = 1;
break ;
}
}
if (flag = = 1)
printf(“%d is in the list at the position %d \n”, key, i+1);
else
printf (“%d is not in the list \n”, key); }
Program 4.5 Program to merge two sorted lists
The two input sorted lists are stored in the arrays a and b respectively. Merged list is stored in
array c. Corresponding elements of arrays a and b are compared and the smaller element is copied into
the array c. The process is repeated until one of the lists is exhausted ,If the elements of array are
exhausted then the remaining elements of array a are copied into the array c, This is accomplished by the
loop.
while (i<m)
{
c[k]=a[i];
++i ; ++k ;
}
If the elements of array a are exhausted then the remaining elements of array b are copied into c. This is
accomplished by the loop
while(j<n)
{
c[k]=b[j];
++j;++k;
}
This procedure is implemented in the following program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10],b[10],c[20],i,j,k,m,n;
printf("Enter the number of elements of the first list: ");
scanf("%d",&m);
printf("Enter the elements of the first list: ");
for(i=0; i<m; ++i)
scanf("%d",&a[i]);
printf("Enter the number of elements of the second list: ");
scanf("%d",&n);
Arrays 94
for(i=0; i<n; ++i)
scanf("%d",&b[i]);
i=j=k=0;
while(i<m&&j<n)
{
if(a[i]<b[j])
{
c[k]=a[i];
++i;
}
else
{
c[k]=b[j];
++j;
}
++k;
}
while(i<m)
{
c[k]=a[i];
++i;
++k;
}
while(j<n)
{
c[k]=b[j];
++j;
++k;
}
printf("the merged list is: \n”);
for(i=0; i<m+n; ++i)
printf("%d",c[i]);
}/*end of main*/
Program 4.6 Program to find the binary representation of decimal integer
Divide given decimal integer by 2, remainder is the least significant digit of the binary representation .
Take the quotient and divide it by 2,remainder is the next binary digit . Take the new quotient and divide
it by 2. Repeat this process till the quotient is zero . The remainders obtained in reverse order are the
digits of the binary representation . Since the remainders are to be displayed in reverse order, store them
in a one-dimensional array and display them in reverse order. This procedure is implemented in the
following program
#include<stdio.h>
#include<conio.h>
void main( )
{
short int bdigit[[16],nd,num,digit,i=0,j;
clrscr();
printf(“Enter the decimal number :”);
scanf(“%d”,&num);
while(n>0)
Arrays 95
{
digit=n%2;
bdigit[i]=digit;
++i;
n=n/2;
}
nd=i; // nd is the number of digits in binary representation
for(j=0;j<nd;++j)
printf(“%d”,bdigit[j]);
getch();
}
Program 4.7 Program to insert an element at a given position in a list.
Let the given element be represented by key and the position be represented by „pos‟. Move down all the
elements from the given position to the end by one position. Then assign the given elements to a[pos-1].
If the list contains 7 elements and the position to be inserted is 3,then move a[6] to a[7],a[5] to a[6],
…..a[2] to a[3]. For this , the following code can be used
for(i=7;i>=3;--i)
a[i]=a[i-1];
Since an element will be inserted, the new list contains one extra element. Therefore increment the value
of n by 1. If this increment is done before the moving process, the code for n elements would be
++n;
for(i=n-1;i>=pos;--i)
a[i]=a[i-1];
a[pos]=key;
Arrays 96
for(i=0;i<n;++i)
printf(“%d\t”,a[i]);
getch();
}
Program 4.8 Program to delete an element from the list at a given position.
Let the position of element to be deleted be represented by pos. It is not possible to delete an element
physically from an array , but it can be overwritten by another number. After reading the value of pos
move up all elements of the array from pos to the end . If the list contains 7 elements and the value of pos
is 3, the following code can be used to implement this process
for(i=2;i<6;++i)
a[i]=a[i+1];
Since an element is to be deleted , new list contains n-1 elements only. Therefore the value of n should be
decrement by 1. If this decrement is done before the process, the code for n elements would be
--n;
for(i=pos-1;i<n;++i)
a[i]=a[i+1];
The program is
#include<stdio.h>
#include<conio.h>
void main( )
int a[10],i,pos,n;
scanf(“%d”,&n);
for(i=0;i<n;++i)
scanf(“%d”,&a[i]);
scanf(“%d”,&pos);
if(pos<1 || pos>n)
Arrays 97
exit(0);
--n;
for(i=pos-1;i<n;++i)
a[i]=a[i+1];
for(i=0;i<n;++i)
printf(“%d\t”,a[i]);
getch();
Two-dimensional array is defined as a set of one dimensional arrays each of same size. Two-
dimensional array is declared in the same manner as one-dimensional arrays. It will require two pairs of
square brackets.
a0 0 a0 1 a0 2 a0 n 1
Row 0
a1 0 a1 1 a1 2 a1 n 1
Row 1
a2 0 a2 1 a2 2 a2 n 1
Row 2
am 1 0 am 2 1 am 3 2 am 1 n 1
Row (m-1)
Arrays 98
Some typical two-dimensional array definitions are shown below.
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declarations with a list of initial values enclosed in braces. For example,
initializes the elements of the first row to zero and the second row to one. The initialization is done row
by row and is called row major ordering.
When the array is completely initialized with all values, explicitly, we need not specify the row size.
That is, the statement
If the values are missing in an initialization, they are automatically set to zero. For instance, the
statement
int a[ 2 ][3] = {{1,1}, {2}}; is permitted and will initialize the first two elements of the first row
to one, the first element of the second row to two, and all other elements to zero, that is
a[0][0]=1 a[1][0]=2
a[0][1]=1 a[1][1]=0
a[0][2]=0 a[1][2]=0
When all the elements are to be initialized to zero, the following short-cut method may be used.
The first element of each row is explicitly initialized to zero while other elements are automatically
initialized to zero. The following statement also will achieve the same result:
The following initialization of the array will result in syntax error, since the number of values in each
inner pair of braces exceeds the defined size of the array.
int a[2][3]={{1,2,3,4},{9,8,6,4,7}};
Example4.12: To store the elements of a 3x4 matrix in a two-dimensional array a, the array declaration
will be
Arrays 99
int a[3][4];
First row elements are stored in a[0][0],a[0][1],a[0][2] and a[0][3],second row elements are stored in
a[1][0], a[1][1], a[1][2] and a[1][3] and third row elements are stored in a[2][0], a[2][1], a[2][2] and
a[2][3].
scanf("%d",&a[i][j]);
To store the elements of all the rows, repeat this loop for i=0, 1, 2.
for(i=0; i<3;++i)
scanf("%d",&a[i][j]);
To display the elements of a 3x4 matrix in the natural form first row elements are to be displayed on the
first line, second row elements are on second line and third row elements on third line. For this the
following code can be used.
for(i=0; i<3;++i)
printf("%8d",a[i][j]);
printf(“\n”);
Given two matrices A of order r1×c1 and B of order r2×c2, we write a program to find
To find the sum matrix we have to find each element of the sum matrix .In general (i,j)th
Arrays 100
#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
#define ROWSIZE 5
#define COLSIZE 5
void main ( )
if
printf (“Given matrices are not of same order and hence addition is not possible \n”);
exit (0);
printf (“Enter the elements of the first matrix row wise : \n”);
Arrays 101
{
printf (“%8d”, ;
printf(“\n”);
}/*end of main*/
If A is a matrix of order m × p and B is a matrix of order p × n, then the (i, j)th element of the product
matrix is obtained by
b0 j
b1 j
ciJ aio ai1 ai 2 .... aip 1 b2 j
bP 1 j
=[ai0b0j+ai1b1j+ai2b2j+……+aip-1bp-1j]
p 1
= a ik bkj
k 0
Thus, the following loop can be used to find the (i, j)th element
#include<stdio.h>
Arrays 102
#include<conio.h>
#include<stdlib.h>
#define ROWSIZE 5
#define COLSIZE 5
void main ( )
if (c1 ! = r2)
exit (0);
scanf(“%d”, &a
scanf(“%d”, & b
Arrays 103
c[i][j] = 0;
c[i][j] + = ;
printf(“\n”);
}/*end of main */
#include<stdio.h>
#include<conio.h>
void main ( )
int n,a[5][5],i,j,flag=0;
scanf(“%d”, &a
Arrays 104
for(i=0;i<n-1;++i)
for(j=i+1;j<n;++j)
if(a[i][j]!=a[j][i])
flag=1;
break;
if(flag==1)
break;
if(flag)
else
getch();
Note that, if any pair of elements are unequal, 1 is assigned to flag and break is executed. Since this break
statement is in the inner loop only that loop execution is terminated. Hence the value of flag must be
compared with 1 in the outer loop.
Program4.12 Programto displayn linesof the Pascal triangle. When n=6, the triangle is as follows
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
In each row, first and last elements are 1‟s. In general ith row elements are obtained as follows:
a[i][0]=a[i][i]=1
a[i][j]=a[i-1][j-1]+a[i-1][j], j=1,2,……….(i-1)
Arrays 105
Repeat this for i=0,1,2…..n-1
#include<stdio.h>
#include<conio.h>
void main ( )
int a[10][10],i,j,n;
for(i=0;i<n;++i)
a[i][0]=a[i][i]=1;
for(j=1;j<i;++j)
a[i][j]=a[i-1][j-1]+a[i-1][j];
for(i=0;i<n;++i)
printf(“ “);
for(j=0;j<=i;++j)
printf(“%3d “,a[i][j]);
Program4.13 Given the roll number and marks in three subjects of 100 students, write a program to
determine the following:
Arrays 106
marks, maximum marks in the first three columns for subject wise maximum and maximum marks in
fourth column for highest total marks. Display the output in a tabular form
#include<stdio.h>
#include<conio.h>
void main ( )
int rno[100],i,s1_rno,s2_rno,s3_rno,total_rno;
printf(“ Enter the Roll no. and marks in 3 subjects of 100 students: \n”);
for(i=0;i<100,++i)
scanf(“%d%f%f%f”,&rno[i],&m[i][0],&m[i][1],&m[i][2]);
for(i=0;i<100;++i)
m[i][3]=m[i][0]+m[i][1]+m[i][2];
/* To find subject wise maximum marks and the roll numbers of the students who secured
them */
s1_max=m[0][0];
s2_max=m[0][1];
s3_max=m[0][2];
total_max=m[0][3];
s1_rno=rno[0];
s2_rno=rno[0];
s3_rno=rno[0];
total_rno=rno[0];
for(i=1;i<100;++i)
if(s1_max<m[i][0])
s1_max=m[i][0];
s1_rno=rno[i];
Arrays 107
}
if(s2_max<m[i][1])
s2_max=m[i][1];
s2_rno=rno[i];
if(s3_max<m[i][2])
s3_max=m[i][2];
s3_rno=rno[i];
if(total_max<m[i][3])
total_max=m[i][3];
total_rno=rno[i];
for(i=0;i<100;++i)
printf(“Maximum marks in subject 1 is %6.2f and the roll number of the student is %d \n”,
s1_max,s1_rno);
printf(“Maximum marks in subject 2 is %6.2f and the roll number of the student is %d \n”,
s2_max, s2_rno);
printf(“Maximum marks in subject 3 is %6.2f and the roll number of the student is %d \n”,
s3_max, s3_rno);
printf(“Highest total marks is %6.2f and the roll number of the student is %d \n”, total_max, total_rno);
getch();
Arrays 108
}
SUMMARY
C uses arrays as a way of describing a collection of data items with identical properties. The
group has a single name for all its members, with the individual member being selected by an
index. We have learnt in this unit, the basic purpose of using an array in the program, declaration
of array and assigning values to the arrays. All elements of the arrays are stored in the contagious
memory locations. Without exception, all arrays in C are indexed from 0 up to one less than the
bound given in the declaration.
One important point about array declaration is that they don‟t permit the use of varying
subscripts. The numbers given must be constant expressions which can be evaluated at compile
time, not run time.
Global and static array elements are initialized to 0 by default, and automatic array elements are
filled with garbage values.
C never check whether the array index is valid – either at compile time or when the program is
running.
Single operations, which involve entire arrays, like copying one array into another array, input or
output of all the elements of the array without subscripts are not permitted in C.
EXERCISES
int a[5]={71,82,69,69,78};
for(i=0;i<5;++i)
printf(“%c”,a[i])
#include<stdio.h>
void main()
int arr[6]={12,13};
printf(“\n %d , %d”,a[1],a[3]);
4.3.Array name is
Arrays 109
4.4. Array elements occupy
d) no space in memory.
4.7.If the size of the array is less than the number of initializes, then
b) it is an error
#include<stdio.h>
main()
int a[5]={1,2,3,4,5},sum=0,i=0
begin:
sum+=a[i];
++i;
if(i<5)
goto begin;
printf(“%d”,sum);
Arrays 110
a) 10 b) 1 c) 15 d)21
#include<stdio.h>
main()
x = ++a[1];
y = a[i++];
z = a[i]++;
printf( “ x= %d , y = %d, z = %d \n “ , x, y, z );
#include<stdio.h>
main()
Arrays 111
{
int a[5]={9,11,3,6,4},b[5],i;
b=a;
for(i=0;i<5;++i)
printf(“\n %d”,b[i]);
b) since the array b is not initialized we cannot display the values of the array b
int a, b = 0 ;
for(a=0; a < 10 ; + + a)
if
b+=c ;
a) b= 25 b) b= 20 c)b=45 d)15
int a, b = 0 ;
if((c[a]%2)= = 0)
b+= ;
printf(“b=%d”, b);
a) b= 25 b) b= 20 c)b=45 d)15
int i ;
int a[5]={0};
Arrays 112
for(i = 1; i < 5 ; ++i)
=i+
int a, b, c ;
{ c = 999 ;
if (
c =x ;
#include<stdio.h>
int main()
while(i<5)
arr[i]=++i;
return 0;
Arrays 113
#include<stdio.h>
main()
int x[10],i,sum=0;
for(i=0;i<10;i+=3)
{ x[i]=i;
sum=sum+x[i];
printf(“%d \n”,sum);
a) 55 b) 45 c) 65 d)unpredictable output
Comprehensive Questions:
4.1 Write a program to rearrange the elements of an array in reverse order without using
a second array
4.2 Write a C program to find the binary equivalent of an integer number using array
4.4 Write a program to compare two one dimensional arrays containing two sets of numbers
4.7 A list of failed registered numbers of students is stored in an array. Write a program to
determine whether a given register number is in the list using linear search
4.8 Write a program for fitting a straight line through a set of points (x i, yi), i =1,2, . . . n.
y = mx + c
Arrays 114
4.9 Given a list of 200 integers each of them ranges from 0 to 10 write a program to count
the number of occurrences of each character
4.10 The annual examinations results of 100 students are tabulated as follows:
4.14 Write a program to sort the elements of each row of a matrix in ascending order
4.16 Write a program to find the transpose of a matrix without using additional array
4.18 Write a program to input 10 integers and sort them. Use a menu system to determine
whether the sort should be ascending or descending order. Also determine whether the elements
have to be sorted by their actual value or absolute value. The process should continue till the user
desires to exit.
Arrays 115
Chapter 5
FUNCTIONS
LEARNING OBJECTIVES
After going through this chapter, the readers will be able to
understand the need of writing a function.
write user defined functions for a task.
write programs using structured programming concept.
understand the use of global and local variables.
apply the storage classes of variables and functions.
5.1 INTRODUCTION
Consider the following program to calculate area of a circle
void main ()
{
float r, area;
printf(“\nEnter radius of circle:”);
scanf(“%f”,&r);
area=3.14159*r*r;
printf(“\narea=%f”,area);
}
The above example is one of the functions which contain its own set of statements for the task to find
area of a circle. Now we can understand what is a function
A function is self-contained program segment which performs a specific task. For example
A function to find area of a circle
A function to find factorial of a number
A function to find gcd of two numbers
Here the task of each example is different and writing the set of statements is also independent to each
other.
Generally a C program consists of one or more modules called functions, one of these functions must be
called main. Execution of the program will always begin by carrying out the instructions in main. Other
functions are subordinate to main and perhaps to one another.
Program5.1 Program to read a negative number and find square root of its absolute value
void main ()
{
int a, b , c ;
printf(“ \n enter a negative number : ”);
scanf(“%d”, &a );
b = abs( a );
d = sqrt( b );
printf( “ \n a=%d b=%d c=%d ”, a, b, c );
}
In this program the different functions are
main() is the main function of the program
printf(), scanf(), abs() and sqrt() are the functions that are called by main( )
C functions can be classified as
i) Built-in functions(Library functions)
ii) User-defined functions
Functions 116
Built-in functions
These functions are already defined and stored in C Library files. The meaning and purpose of
these functions are fixed. It is not possible to change its meaning and purpose by the user, but user can
utilize these functions in their programs by including the corresponding header file.
Examples of library functions are
printf(), scanf(), sqrt(), abs(), fabs(), sin(), strlen(), toupper(), isalpha(), etc....
User-defined functions
These functions will be developed by the user at the time of writing the program. The function
name, meaning and the task of the function is decided by the user. However, a user-defined function can
later become a part of the C library. main() is also a user defined function.
Example5.1: Function to find area of a circle
float area(float radius)
{
float a;
a=3.14159*radius*radius;
return(a);
}
5.2 STRUCTURE OF A FUNCTION
The structure of a function is
Functions 117
Example5.2: Function to return the sum of two integers
Function_name
Return type List of arguments
return(s);
Note1: Any function whether the library or user defined function will follow the same general form.
Note2: The return-type and arguments in a function are optional. When a function does not return a value
then its return-type is void and for the function with no arguments the function-name is followed by
void in the parentheses. With the combination of return-type and arguments the functions may be of
different categories shown as follows.
Example5.3: A function returns biggest of two integers
int big( int x, int y)
{
if( x > y)
return(x);
else
return(y);
}
if( n%2 = = 0 )
else
Functions 118
Example5.5: A function to display the message “WELCOME”
void wel(void )
{
printf(“\n WELCOME \n”);
Example5.6: A function
} to returns a mile in terms of kilometers
return(1.6093440);
If such big program is divided into functional parts, then each part may be independently coded, compiled
and later integrated into a single unit. These independently coded program modules are called
subprograms. In C these subprograms are called functions and they have the following advantages.
Every C program must have a function with the name main and may have one or more other functions.
Calling of a function means referring its name in a statement for utilizing its purpose at that point. For
example the following fun1 () is called in main function.
Program5.2 Program to display a message by calling a function in main to display the message.
void fun1()
{
printf(“\n My Name is Raju \n”); Output
}
main() My Name is Raju
{
fun1( );
}
Functions 119
Here the fun1() is termed as called function and the function main() is termed as calling function.
A function can be called by any other function but main cannot be called by other functions. Execution of
the program begins with main irrespective of the order of the functions.
Example5.7:
main()
{ ………..
fun3( );
………..
}
void fun1( )
{ ………….
………….
}
void fun2( )
{ ………….
fun1( );
………….
}
void fun3( )
{ ……………
fun2( );
……………}
Here fun3( ) is called by main( ) and fun3( ) calls fun2( ) which calls fun1( ).
5.3.1 Calling function with no return value
Since the function does not return any value, its call cannot be written in an expression but has to be by
an independent statement. For example,
Example5.8:
void main()
{
int x;
h_line();
}
void h_line()
{ int i;
for(i=0;i<10;i++)
printf(“-“);
}
Exampple5.9:
void main() Wrong
{
int x;
} x=h_line();
void h_line()
{ int i;
for(i=0;i<10;i++)
printf(“-“);
}
Functions 120
5.3.2 Calling function with a return value
Since the function will return a value its call is written in expressions like assignment expression, logical
expression and as an argument of another function call. For example,
Example5.10: Example5.11:
float PI(void); void main()
void main() { float p,r=5.5,area;
{ float r=5.5 printf(“\narea=%f”, PI()*r*r);
p=PI(); prinf(“\nArea of circle =%.2f”,area);
}
}
float PI(void)
{
return(3.14159);
}
Program 5.3 Write a function to return GCD of two numbers and call this function in main to find GCD
and LCM of four given numbers;
#include<stdio.h>
void main()
int n1,n2,n3,n4,gc1,gc2,gc,lc1,lc2,lc;
scanf(“%d%d%d%d”,&n1,&n2,&n3,&n4);
gc1=gcd(n1,n2);
gc2=gcd(n3,n4);
gc=gcd(gc1,gc2);
lc1=n1*n2/gc1;
lc2=n3*n4/gc2;
lc=lc1*lc2/gcd(lc1,lc2);
Functions 121
5.3.3 Calling a function with arguments
The function call with arguments is used to pass the data to the called function by the calling function.
The arguments in the function call are called actual arguments / parameters and arguments in the
function header are called formal parameters or dummy arguments
Passing data
Data can be passed from calling function to the called function in two ways
1. Call by value
2. Call by reference
In call by value a copy of the values of actual arguments from calling function are passed to the formal
parameters of the called function
Functions 122
Example5.15:
Output:
values of x and y before swap
x=20 y=30
values of x and y after swap
x=20 y=30
Note:It is noticed that there is no change in the values of x and y of the function main after the call of the
function swap. Because, the function swap interchanged the values of a and b in the copy and this change
is not reflected in the original arguments x and y.
In call by reference the addresses of actual arguments are passed to the formal parameters. Since the
formal parameters hold addresses, they must be declared as pointers.
Example5.16:
Functions 123
Note: since addresses of the actual parameters x and y are passed to the function swap, the interchange
made by the function swap is reflected in the actual arguments
5.4 FUNCTION PROTOTYPE
In a multi-function program there is no restriction on the order of the functions. That is the definition of
calling function can precede the called function definition and vice-versa.
But the convention is to write the definition of calling function before the definition of called function.
In this case if the called function returns a non-integer value, the calling function definition should be
preceded by a forward declaration about the type of value returned by the called function. This forward
declaration is called function prototype
Example5.17: Program to find area of a circle using a function which will calculate and return area
float area( float radius)
{
return(3.14159*radius*radius);
}
void main()
{
float r,a;
printf(“\n Enter radius of circle:”);
scanf(“%f”,&f);
a=area(r);
printf(“\n area value=%f”,a);
}
Since the definition of the called function area appears before the calling function there will be no syntax
error, as the function area is compiled before main.
But the convention is to write the definition of the calling function before the called function shown as
follows.
void main()
{
float r,a;
printf(“\n Enter radius of circle:”);
scanf(“%f”,&r);
a=area(r);
printf(“\n area value=%f”,a);
}
float area( float radius)
{
return(3.14159*radius*radius); }
In this case as the function main is compiled first, as there is no declaration regarding the function area
compiler assumes that area is the name of a function and it return, an integer value. But in the function
header
float area( float radius)
it is mentioned that the return data type is float. Hence, syntax error will occur when the function header
is encountered during compilation . To avoid this error we give advance information to the compiler
Functions 124
about the type of value returned by the function and the number and type of arguments. This is achieved
by writing the function prototype before the definition of main.
Note: Function prototype is required for all the functions except the functions of return_type int.
Program5.5 Program tofind median of a list of numbers using a function to sort the list of numbers.
void bub_sort( int n, float a[10]); // Function prototype
void main()
{
int n,i;
float a[10], median;
printf(“\n Enter the no of values:”);
scanf(“%d”, &n);
printf(“\n Enter the values”)
for(i=0; i<n; ++i)
scanf(“%f”, &a[i]);
bub_sort(n,a);
if(n%2)
median = a[(n-1)/2];
else
median = (a[n/2] + a[n/2-1])/2;
printf(“\n median =%.2f”, median);
}
void bub_sort(int n, float a[10])
{
int p,j; float temp;
for (p=1; p<n; ++p)
for(j=1; j<n-p; ++j)
if(a[j]>a[j+1])
{
temp= a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
return;
}
Functions 125
5.5 CATEGORIES OF FUNCTIONS
Based on the arguments present or not and a value is returned or not, the function may belong to one of
the following categories.
1. Functions with arguments and return value
2. Functions with arguments and no return value
3. Functions with no arguments and return value
4. Functions with no arguments and no return value
#include<stdio.h>
double power(int x, int y);
void main()
{
int y ;
float x;
double p;
printf(“\n Enter base and exponent:”);
scanf(“%f%d”,&x,&y);
if(y>0)
p=power(x,y);
else
Functions 126
p = 1.0/power(x,y);
printf(“\n value of %f to the power of %d is %lf”,x,y,p);
}
double power(int x,int y)
{
double p=1;
while(y--)
p*=x;
return(p); }
void function_name (data type arg_1, data type arg_2,…data type arg_n)
{ ……………………..
……………………..
……………………..
return; }
Example5.20: Function to display a matrix
void display(int m,int n,int a[10][10])
{
int i,j;
for(i=0;i<m;++i)
{
for(j=0;j<n;++j)
printf(“%5d”a[i][j]);
printf(“\n”);
}
return;
}
In the above function the called function receive the address of the array which contains the matrix and
display it. It does not return any value to the calling function.
Example5.21: Function to print the given title.
void title(char str[] )
{
printf (“%s”, str);
return;
}
5.5.3 Functions with no arguments and return value
Functions with no arguments means, no data is passed from the calling function to the called function
through the arguments, and with return value means, the called function will return a value of type
return_type to the calling function.
return_type function_name ( void)
{ ……………………..
……………………..
……………………..
return(expression);
}
Functions 127
Eample5.22: Function to return pi value
float pi ( void)
{
return(3.14159);
}
#include<stdio.h>
long int factorial(int n);
void main()
{
int n,r;
long ncr;
printf(“\n Enter the values of n and r :”);
scanf(“%d%d”, &n, &r);
ncr = factorial(n)/(factorial( r )*factorial(n-r));
printf(“\n C(%d, %d) = %ld”, n, r, ncr);
}
long int factorial(int n)
{
long int f=1;
int i;
for(i=1; i<=n; i++)
f = f * i;
Functions 128
return(f);
}
5.6 PASSING ARRAYS TO FUNCTIONS
Functions 129
{
int p,i,temp;
for(p=1; p<n; ++p)
{
for(i=0; i<n-p;++ i)
{
if(x[i]>x[i+1])
{
temp=x[i];
x[i]=x[i+1];
x[i+1]=temp;
}
}
}
}
Program 5.10 Write function to reverse the elements of an array .Use this in main to display the given
list in reverse order.
#include<stdio.h>
void print_rev(int a[ ], int );
void main()
{
int a[50],n,i;
printf(„\n Enter no of elements in the array:”);
scanf(“%d”,&n);
printf(“\n Enter %d number of elements:”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nElements in reverse order:\n”);
for(i=0;i<n;i++)
printf(“%5d”,a[i]);
}
void reverse( int a[50],int n)
{
for(i=0,j=n-1;i<j;++i,--j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
return;
}
5.6.2 Functions with Two-Dimensional Arrays
To pass multi-dimensional array to a function we should fallow the following rules
In the function definition, the formal parameter must be two-dimensional array by indicating two
subscripts.
The size of second subscript must be specified.
The prototype declaration should be similar to the function definition
The function must be called simply by passing the array name only.
Functions 130
Program 5.11 Writefunctions to read and display a matric .Call them in the main to read the elements of
a matrix from key board and display it.
#include<stdio.h>
void read_mat(int a[10][10], int r, int c);
void print_mat(int a[10][10], int r, int c);
void main()
{
int a[10][10],m,n;
printf(“\n Enter no of rows and calms of matrix:”);
scanf(“%d%d”,&m,&n);
printf(“\n Enter the elements of the matrix row wise:”);
read_mat(a,m,n);
printf(“\n Given matrix is:\n”);
print_mat(a,m,n);
}
void read_mat(int a[10][10], int r, int c)
{ int i,j;
for(i=0; i<r; i++)
for (j=0; j<c; j++)
scanf(“%d”, &a[i][j]);
}
void print_mat(int a[][10], int r, int c)
{ int i,j;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
printf(“%5d”,a[i][j]);
printf(“\n”);
}
}
Program 5.12 Program for addition of two given matrices using the functions to read ,display and add
the matrices.
#include<stdio.h>
void read_mat(int a[10][10], int r, int c);
void print_mat(int a[10][10], int r, int c);
void add_mat(int a[10][10], int b[10][10], int c[10][10], int r1, int c1);
void main()
{
int a[10][10], b[10][10], c[10][10], m1, m2, n1, n2;
printf(“\n Enter the no rows and columns of 1st matrix:”);
scanf(“%d%d”, &m1, &n1);
printf(“\n Enter the no rows and columns of 2nd matrix :”);
scanf(“%d%d”, &m2, &n2)
if(m1!=m2 ||n1!=n2)
{ printf(“Addition not possible \n”);
exit(0);
}
printf(“\n Enter the elements of 1st matrix row wise :\n”);
read_mat(a,m1,n1);
printf(“\n Enter the elements of 2nd matrix row wise :\n”);
read_mat(b,m2,n2);
Functions 131
add_mat(a,b,c,m1,n1);
printf(“\n Sum matrix is:\n”);
print_mat(c,m1,n1);
}
void add_mat(int a[10][10], b[10][10], c[10][10], int r1, int c1)
{
int i,j;
{
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
c[i][j]=a[i][j]+b[i][j];
}
return;
}
void read_mat(int a[10][10], int r, int c)
{ int i,j;
for(i=0; i<r; i++)
for (j=0; j<c; j++)
scanf(“%d”, &a[i][j]);
}
void print_mat(int a[][10], int r, int c)
{ int i,j;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
printf(“%5d”,a[i][j]);
printf(“\n”);
}
}
Program 5.13 Program for multiplication of two given matrices using functions.
#include<stdio.h>
void read_mat(int a[10][10], int r, int c);
void print_mat(int a[10][10], int r, int c);
void mult_mat(int a[10][10], int b[10][10], int c[10][10], int r1, int c1, int r2, int c2);
void main()
{
int a[10][10],b[10][10],c[10][10],m1,m2,n1,n2;
printf(“\n Enter the no rows and columns of 1st matrix:”);
scanf(“%d%d”, &m1, &n1);
printf(“\n Enter the no rows and columns of 2nd matrix :”);
scanf(“%d%d”, &m2, &n2)
if(n1!=m2)
{printf(“multiplication not possible \n”);
exit(0);
}
printf(“\n Enter the elements of 1st matrix row wise :\n”);
read_mat(a,m1,n1);
printf(“\n Enter the elements of 2nd matrix row wise :\n”);
read_mat(b,m2,n2);
mult_mat(a,b,c,m1,n1,m2,n2);
printf(“\n Product matrix is:\n”);
Functions 132
print_mat(c,m1,n2);
}
void mult_mat(int a[10][10], b[10][10], c[10][10], int r1, int c1, int r2, int c2)
{
int i,j,k;
for(i=0; i<r1; i++)
{ for(j=0;j<c2;j++)
{c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
}
void read_mat(int a[10][10], int r, int c)
{int i,j;
for(i=0; i<r; i++)
for (j=0; j<c; j++)
scanf(“%d”, &a[i][j]);
}
void print_mat(int a[][10], int r, int c)
{int i,j;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
printf(“%5d”,a[i][j]);
printf(“\n”);
}
}
5.7 BUILT-IN FUNCTION
In C library, several functions are available to perform various tasks like data input/output, calculation of
the values of mathematical functions, string manipulations, etc….which are needed in writing different
application programs. These functions are called library functions or built-in functions. Since a large
number of built-in functions are available they are classified into different categories and their headers are
stored in different header files
Functions 133
6 tan( ) Calculates the tangent of the input value
7 asin( ) Computes the arc sin of the value
8 acos( ) Computes the arc cosine of the input value
9 atan( ) Calculates the arc tangent of the input value
10 exp( ) Calculates e to the x the power
11 pow( ) Calculates x to the power y
12 log( ) Calculates natural logarithm of input value
13 log10( ) Calculates bse10 logarithm of input value
14 scanf() To read input data in a given format through key board
15 printf( ) To display data in a given format on the screen
16 getchar( ) To read a character through key board
17 stdio.h putchar( ) To display a character on the screen
18 gets( ) To read a string through key board
19 puts( ) To display string on the screen
20 flushall( ) Clears all buffers associated with open input stream
21 strlen( ) Calculates length of a string
22 strcpy( ) Copies one string into another string
string.h
23 strcmp( ) Compares two strings
24 strcat( ) Joins two strings together
25 toupper() Convert the given alphabet into uppercase
26 tolower() Convert the given character into lower case
ctype.h
27 isalpha() Check whether the given character is alphabetic or not
double r=5.45, s;
y=abs(x);
s=fabs(r);
result = sqrt(x);
a1=sin(3.14159*angle/180);
a2=cos(3.14159*angle/180);
a3=tan(3.14159*angle/180);
Functions 134
exp( ) its prototype is double exp(double x);
r1 = exp(p);
r2 = log(p);
r3 = pow(x,y);
5.8 RECURSION
Functions 135
long int factorial( int n );
void main( )
{ int n,f;
printf(“\n Enter a number:”);
scanf(“%d”, &n);
f=factorial(n);
printf(“\n factorial of given num %d is %”, n, f);
}long int factorial(int n)
{ long int f;
1. Local variables
2. Global variables
In all the programs written so far variables are declared inside of the functions. Such variables are called
local variables, However, variables may be declared outside the scope of a function such variables are
called global variables.
Local Variables:
Local variables scope is confined within the block or function where it is defined. That is, it is
recognized within the block or the function
Example5.32:
Output
main()
{ int i=4; value of i inside the block = 100
int j=10; value of i outside the block=5
Functions 136
i++;
if (j > 0)
{
int i=100;
printf("value of i inside the block = %d\n",i);
}
printf("value of i outside the block= %d\n",i);
}
Global Variables
Scope of the global variables is from the point of declaration through the remainder of the program. i.e.
any
function which falls in their scope can access their values.
If the global variables declaration does not include initial values they are initialized by the system as
follows:
Datatype initialser
int 0
char „\0‟
float 0
pointer NULL
If same variable name is being used for global and local variable then local variable takes precedence
in its scope. But it is not a good practice to use same name for both global and local variable.
Example5.33:
int i=4; /* Global definition */
main()
{ i++; /* Global variable scces */
func();
printf( "Value of global variable\ n i = %d\n", i );
}
func()
{ int i=10; /* Local declaration of i */
i++;
printf( "Value of local variable in the function func \n i = %d\n", i );
}
Output
Value of local variable in the function func
i = 11
Value of global variable
i=5
Functions 137
Note: differences between local and global variables
…….. { …….
} }
1 data type
2 storage class
Data type refers the type of data to be stored in the memory location allotted to that variable.
int x,y; // x and y are integer variables and represent integer data
Storage class refers to the scope and longevity(life time) of a variable. It also describes the
default initial value and memory location
The scope actually determines the portion of the program that the variable is recognized.
The longevity of the variable determines how long the variable is alive or active.
There are four different storage classes in C and they are represented by the keywords
auto - automatic variables,
Functions 138
static - static variables and
For example
auto int x; // x is an automatic integer variable
static float y // y is static floating point variable
Life time: The lifetime of automatic variable is temporary. i.e. it is defined when a function is called
for execution and is destroyed when the control is exited from its defining function
void main( )
{ int i;
for(i=1; i<5; i++)
printf(“%d\n”, fun1( )); Output
}
x=11
int fun1( )
x=11
{ x=10;
return(++x); x=11
}
x=11
Since x is automatic variable and is reinitialized with 10 in every call of fun1( ). Hence, fun1( ) returns
same value 11 to main( ) in every call.
Functions 139
Default initial value: The default initial value of automatic variable is garbage
void main( )
{
Output
int y;
y= garbage
printf(“\n y=%d”, y+=5);
Since y is automatic variable and is not initialized, its default initial value is garbage. Automatic variables
can be initialized with expressions. For example,
int a=10, b=5, c = a+b; is allowed.
Memory location: These variables are located in main memory.
Note1: Variable defined in one function is not accessible to any other function.
Example5.34:
void main()
{ int x=25;
printf(“\n x=%d”,x);
}
x- is local to main( ) but
void fun1()
{ int y=50; not accessed in fun1( )
printf(“\n x=%d”,x);
printf(“\n y=%d”, y);
} x- is local to main( ) and y- is
void fun2() local to fun1( ) but not
{ x=1000; accessed in fun2( )
y=2000;
}
Note2: If the name of global and local variables is same then in the scope of local variable the first
priority is for local variables. In such cases the value of global variable is temporarily put on shelf and
beyond the scope of local variable.
Example5.35: what is the output of the following program?
Functions 140
5.9.2.2 External variables
Variables that are declared outside the scope of any function are external variables. All global variables
are
external variables.
int s;
void main()
{ s=96; // s is global variable
………..
…………
}
float r;
void fun1()
{
r=5.4; // r is global variable
……….
}
Scope: The scope of external variables extends from the point of definition through the remainder of
the
Program
Life time: The lifetime of global variables is permanent i.e. they retain their values throughout the
execution of
the program
Default initial value: The default initial value of external variable is zero. External variables cannot be
initialized with expressions. For example,
int a=5, b=10, c=a+b; is not allowed, if a,b,c are external variables
Memory location: These variables are located in main memory.
Note1: Since external variables are recognized globally, they can be accessed from any function that falls
within their scope, thus, an external variable can be assigned a value within one function, and this value
can be used within another function.
Example5.36: what is the output of the following program?
int x=96;
Functions 141
void main( )
{ Output
printf(“\n x=%d”x)‟
fun1(); x=96
fun2();
printf(“\n x=%d”,x); x=200
}
void fun1( ) x=200
{ x=200;
printf(“\n x=%d”, x); x=500
}
void fun2()
{ printf(“\n x=%d”,x);
x=500; }
Note2: If a global variable is accessed before it is defined then it needs to be declared as an external
variable using the key word extern
Example5.37: What is the output of the following program
void main( )
{ extern int x; External variable
printf(“\n x=%d”, x ); declaration (memory not
fun1(); allocated)
}
int x; External variable
void fun1() definition (memory is
{ allocated)
x=200;
printf(„\n x=%d”, x ); Output
}
x=200
x=200
Declaration Vs definition
The external declaration of x inside the function main informs the compiler that x is an integer type
defined
somewhere else in the program. Note that the extern declaration does not allocate storage space for
variable x, where as variable definition outside the function does allocate storage space for variable
The assignment of initial values can be included within an external variable definition whereas the
external
variable declaration cannot include initial values as no storage space is allocated.
The storage class specifier extern is not required in an external variable definition whereas external
declaration must begin with the storage class specifier extern.
Functions 142
static int c; // c is static external
int s; // s is external
void main()
{ static int x; //x is static internal variable
int i,j; // i and j are automatic variables
…….
…..
}
void fun1(void)
{ static int c,k; // c and k are static internal variable
……..
}
Scope: The scope of internal static internal is local to the function in which it is defined and the scope
of static external variable is from the point of declaration through the remainder of the program
Life time: The lifetime of static variable is permanent. Internal static variable retain its value even after
the control is exited from the function
void main( )
Output
{ int i;
x=11
for(i=1; i<5; i++)
x=12
printf(“%d\n”, fun1( ));
x=13
}
x=14
int fun1(void )
return(++x);
The internal static variable x initialized only once at compilation time. Since it retains its values during
successive function calls the values returned by fun1( ) to the function main( ) are 11, 12, 13 and 14 in the
first, second, third and fourth calls.
Functions 143
Default initial value: The default initial value of internal or external static variable is zero
static int x;
void main( )
Output
{
static int y; x=1
printf(“\n x=%d”,
++x); y=5
printf(“\n y=%d”,
y+=5);
}
Since x and y are static variables they are initialized with zero rather than garbage.
Memory location: Both these variables are located in main memory.
The difference between static external variable and a simple external variable is that the static variable
is available only within the file where it is defined , while the simple external variable can be accessed by
other files.
5.9.2.4 Register variables
Storage space normally allocated for variable in main memory.
It is possible to tell the compiler that a variable should be kept in the CPU registers by defining it as
register
variable.
Since a register access is much faster than memory access, keeping the frequently accessed variables
(like loop control variables) in the register will make the execution of the program faster.
Except the memory space allocation all the other properties of register variables are similar to that of
automatic
variables.
Very few variables can be placed in the registers. Normally two or three per function.
Only local variables of type int, char can be declared with the storage class register
void main( )
…………………
………………..
………………...
Functions 144
SUMMARY
A function is a module or block of program code which deals with a particular task. Defining
functions for each task is a way of isolating one block of code from other independent blocks of code.
A function can take a number of parameters, do required for processing and then return a value. There
may be a function which does not return any value, but perform a given task.
You already have seen couple of built-in functions like printf( ); Similar way you can define your
own functions in C language.
Consider the following code
int total = 20;
printf(“Hellow World”);
total = total+1;
To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single
compound statement and write the name that you want to give it in front of the brackets:
demo( )
printf("Hello World");
total = total + l;
Curly brackets after the function's name are required. One or more parameters to a function can be
passed as
follows
{ int total;
printf("Hello World");
total = a + b;
By default function does not return anything. But you can make a function to return any value as
follows:
int demo( int a, int b)
{ int total;
printf("Hello World");
total = a + b;
return (total);
}
Functions 145
A return keyword is used to return a value and datatype of the returned value is specified before the
name of function. In this case function returns total which is int type. If a function does not return a
value then the return data type is void.
Once a function is defined it can be used within a program:
main()
{ int s;
s=demo(20,30);
Each function behaves the same way as C language standard function main(). So a function will have
its own local variables defined. In the above example the variable total is local to the function demo.
A global variable can be accessed in any function in a similar way as it is accessed in main() function.
A function declaration does not have any body.
A function declaration is usually declared at the top of a C source file, or in a separate header file.
A function declaration is sometimes called function prototype. For the above demo() function which
returns an integer, and takes two parameters a function declaration will be as follows:
int demo( int a, int b);
A function can be called recursively. The following code prints the word Hallow repeatedly because the
main( ) is called recursively
void main( )
printf(“Hallow”);
main();
A recursive function code involves if....else control to decide whether the recursive call is to be
continued or to be stop. The following code prints the output 0 1 2
void f( )
static int x;
if(x==3) return;
else
Functions 146
x++;
f( );
Pass by Value mechanism is used when you don't want to change the value of passed paramters. When
parameters are passed by value then functions in C create copies of the passed variables and do
required processing on these copied values.
Pass by Reference mechanism is used when you want a function to do the changes in passed
parameters and reflect those changes back to the calling function. In this case only addresses of the
variables are passed to a function so that function can work directly with original data through
addresses.
EXERCISES
Functions 147
a) 1 1 1 1 1 b) 1 2 3 4 5 c) 0 1 2 3 4 d)Garbage
value as x is not initialized in function fun
3.What is the output when the following code is executed?
#include<stdio.h>
int i;
int fun();
int main()
{
while(i)
{
fun();
main();
}
printf("Hello\n");
return 0;
}
int fun()
{
printf("Hi");
}
a) Hello indefinitely b)Hello c)Hello two times on separate lines d) No Output
4. What is the output when the following code is executed?
#include<stdio.h>
int reverse(int);
int main()
{
int no=5;
reverse(no);
return 0;
}
int reverse(int no)
{
if(no == 0)
return 0;
else
printf("%d \t ", no);
reverse (reverse(--no);
}
a) 5 4 3 2 1 b) 5 4 3 2 1 0 c)5 5 5 5 5 d) 1 2 3 4 5
Functions 148
if(n > 0)
{
fun(--n);
printf("%d,", n);
fun(--n);
}
}
6. There is an error in the following program. Which statement will you add to remove it?
#include<stdio.h>
int main()
{
int a;
a = f(10, 3.14);
printf("%d\n", a);
return 0;
}
float f(int aa, float bb)
{
return ((float)aa + bb);
}
a) a separate statement to add aa and bb in function f b)Type declaration in the function f
c)function prototype d) none of these
int count(int i)
{
if ( i < 0) return(i);
Functions 149
else
return( count(i-2) + count(i-1));
}
a) -17 b) -10 c)-4 d) 4
9. What will be the output when the flowing program segment is executed?
#include<stdio.h>
int i;
void increment(int i)
{
i++;
}
int main()
{
for(i=0;i<10;increment(i))
{
}
printf(“i=%d\t “,i)
return 0;
}
a) 1 2 3 …. 10 b)10 c)1 2 3 …. 11 d) No ouput
10.What will be the output when the flowing program segment is executed?
#include<stdio.h>
void func()
{
int x=0;
static int y=0;
x++; y++;
printf(“ x=%d,y= %d \t”,x,y);
}
int main()
{
func();
func();
return 0;
}
a)x=1,y=1 x=1,y=2 b) x=1,y=0 x=1,y=1
c) x=1,y=1 x=2,y=2 d) x=1,y=1 x=1,y=1
11. What is the output when the flowing program segment is executed?
int a=1,b=2;
int f1(int a,int b);
main()
{
int i=1,c,d;
c=5*(i+1);
d=10*(i-1);
printf(“% d, %d “,f1(a,c),f1(b,d));
}
}
int f1(int x,int y)
{
Functions 150
return(x*y);
}
a) 10,0 b)11,0 c)10,1 d)11,1
Comprehensive Questions:
5.1 Discuss how parameters are passed between functions in C by writing a function swap to exchange
the values of two integers passed to it by the main function.
5.2 Write about storage classes in C along with their location, scope and life span.
5.3 What is a recursion ? Write a recursive function two find n!
5.4 Write a non-recursive function to find the factorial of a given integer.
5.5 Write a function to find the greatest common divisor(gcd) of two integers passed as parameters to it
and a
program to call the function repeatedly to find the gcd of four integers.
5.6 How do you pass data to a function? Explain the concept of call by value and call by reference
through
suitable examples.
5.7 Write a function to find the factorial of an integer and use it to write a program for finding the
number of
combinations C(n,r) possible, given the values of n and r.
C(n,r) = n!/ (n-r)!r!
5.8 Write a recursive function that will generate a given element of Fibonacci sequence. Use this
function in
main to print first n elements of Fibonacci sequence.
5.9 Write a function to find gcd of two numbers and use this function to find their lcm .
5.10 Write a recursive function for binary search with function prototype.
Functions 151
int binsearch(int data[], int key,int ll,int ul); and call this function in main() to test this function.
5.11 Write a function which imitates the behavior of strlen() function. Use this function to check if a
given string is a palindrome or not.
5.12 Write a recursive function power that computes a x w here a is a real constants and x is an integer.
5.13 Write a function that will scan a character string passed as an argument and convert all lower case
character into their uppercase equivalents.
5.14 Write a function that can be called to find the largest element of an m X n matrix
5.15 Write a function that converts miles to kilometers. Note that 1 mile equals 1.6093440 km.
5.16 Write a function that will round a floating-point number. For example the number 17.457 would
yield the value 17.46 when it is rounded off to two decimal places.
5.17 Write a recursive function to find the binary code of a decimal inreger.
5.18 Write a program to find the reverse of a number using function
5.19 Write a function isprime that returns 1 if its argument is a prime number and returns zero otherwise.
5.20 Write a function to evaluate the formula y = xn where y and x are floating-point variables and n is
an integer variable
5.21 Calculate factorials n! for n from 1 to 20 using a factorial function with return type of unsigned long
long.
5.22 Discuss how parameters are passed between functions in C by writing a function „SWAP‟ to
exchange the values of two integers passed to it by the main( ) function.
5.23 Write a function sort to sort a list of values and call this function in main to find the median of a list
of n numbers
5.24 Write a program to reverse an integer using a recursive function
5.25 The Fibonacci numbers are defined recursively as follows
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 if n>2
i) Write a recursive function that will find n th element of the Fibonacci sequence
ii) Write a function with local static variables to find n th element of Fibonacci sequence
5.26 Write a recursive function for binary search with function prototype int binsearch( int n, double
data[], double key ); and call this function in main to test binary search function
5.27 Write a recursive function to find gcd of two numbers, use this function to find their lcm
Functions 152
Chapter 6
POINTERS AND DYNAMIC MEMORY ALLOCATION
LEARNING OBJECTIVES
After reading this chapter, the readers will be able to
understand the concept of pointer
know the operations on pointers.
learn the passing of pointers to functions
learn handling one-dimensional and two-dimensional numerical arrays and string manipulations
through pointers.
learn the `concept of dynamic memory allocation and usage of DMA functions.
6.1 INTRODUCTION
Pointer is a variable that refers to the location of another item such as a variable or array. Pointers have
number of applications, for example pointer can be used to back and forth between a function and its
point of reference. Using pointers we can pass multiple values through arguments and also return multiple
values. Arrays and pointers resemble in their operations to access or process elements. Multidimensional
arrays can be represented and processed through pointers. This feature enables us to represent
multidimensional arrays as lower-dimensional array of pointers. The above feature helps in representing a
string or a group of strings. Pointers can be used for implementation of DMA which reduce the wastage
of memory.
Background
The statements
float x;
x = 10.5;
Requests the compiler to reserve 4 bytes of memory (machine dependent) for the floating-point variable
x, then stores value 10.5 in it.
`Sometimes we want to know where a variable resides in memory. The address (location in memory) of
any variable is obtained by placing the operator „&‟ before its name.
1562
Address of location
referring/pointing
Address of x Value of x
ptr_variable Variable _x
Example 6.1:
Memory
Declaration Interpretation
occupied
int *iptr iptr is a pointer variable holding address of an integer. Variable 2bytes
float *fptr fptr is a pointer variable holding address of a float variable 2bytes
char *cptr cptr is a pointer variable holding address of a character variable 2bytes
Address of a variable of any data type is unsigned integral value. Hence each pointer variable occupies
2bytes for 16 bit processor or 4 bytes for 32 bit processor.
Address operator( &):The address operator & is used to get the address of the memory location allotted
to a variable.
Example 6.2:
ptr=&x ; Here ptr is a pointer variable holding the address of the variable x.
& is a unary operator that operates on variables and the associatively is from Right to Left and is of same
precedence group as other unary operators -,++, --, sizeof etc.. This group has higher precedence over the
other groups containing arithmetical operators.
& operator must act upon the operand that is associated with unique address, such as ordinary variables
or single array elements.
&150, &(x+y) is not allowed.
*ptr;
*2000 =>10.23
In the above example ptr is a pointer variable storing the address of the variable x. * with ptr is called as
indirection operator used to give the value at the address ptr holds.
* is unary operator operating from Right to Left and is of same precedence group as other unary operators
-,++, --, sizeof etc.. This group has higher precedence over the other groups containing arithmetical
operators.
*operator must act upon the operand that is a pointer. It gives the value at that address or is said to refer to
the location so called as indirect reference operator.
We will get the same result by assigning the value of sum to an ordinary (non pointer) variable. The
benefit is that we can also refer to the pointer variable as *ptr the asterisk tells the computer that we are
not interested in the address, but in the value stored in that memory location. Hence first and second
printf statements will result in the same output.
Program 6.2 Program to display the contents of the variable their address using pointer variable
#include <stdio.h>
main()
{
int num, *intptr;
float x, *floptr;
char ch, *cptr;
num=123;
x=12.34;
ch=‟a‟;
Pointer Variable
A variable that is a pointer to a pointer must be declared as below. This is done by placing an additional *
in front of the variable name.
int **ptr; where ptr is a pointer which holds the address of another pointer.
Program 6.3 Program to declare pointer to pointer variable and to display their contents
#include<stdio.h>
void main(void)
int x,*ptr1,**ptr2;
x=10;
printf(“ x= %d”,x);
ptr1=&x;
printf(“x= %d”,*ptr1);
ptr2=&ptr1;
printf(“x= %d”,**ptr2);
All the three printf() statements display the same output x=10
main() Output:
{
int a, *aptr,**aaptr; 10 is the value of a
a==*&a==*aptr==**aaptr==***&aaptr
&a==aptr==*&aptr==**&aaptr
&aptr==aaptr==*&aaptr==*&aaptr
Like any other variable, pointer variable can be used in arithmetic expressions.
For example if p1 and p2 are properly declared and initialized pointers, then the following statements are
valid.
y = *p1 * *p2;
sum = sum + *p1;
z = 5 - *p2/p1;
*p2 = *p2 + 10;
x=3+5/ *p1;
Note that there must be a gap between / and *,otherwise /* is taken as the beginning of a comment.
Increment and decrement operations can be applied on pointers. The expressions ++p1,--p2 etc are
allowed.
#include <stdio.h>
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a; ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a is %u”,ptr1);
printf(“\nAddress of b is %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr1;
printf(“\na=%d, b=%d”,a,b);
1. An integer constant or variable can be added to a pointer or subtracted from the pointer.
int x,*p1,i;
p1=&x;
the expressions such as p1+1,p1+3,p1+i,
p1-1,p1-2,p1-i are allowed.
Pointers (addresses) can be passed to a function through arguments. This mechanism of passing is called
as pass by reference. In this mechanism any changes done to the parameters in function definition will
affect the actual parameters.
When addresses are passed through the actual parameters to the formal parameters, formal parameters
must be pointer type variables.
Program 6.6 Program to swap two integral values by passing pointers to the function swap
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
a b aptr bptr
10 20 2000 4000
Swapping of values
temp=*aptr *aptr=*bptr *bptr=temp
a b
10
8000 10 20 20 10
a a
2000 4000
We know that a function can return single value only. However, multiple values can be returned through
pointer parameters. The following program will illustrate this.
Program 6.7 Write a functionthat will find the area and parameter of a triangle and return them through
pointer parameters. Call this function in main() to find area and circumference of a given triangle
Arrays are abstract data types which store a group of logically related items belonging to same data type
and are referred by a common name.
Array is identified by its name (common name) .Which is nothing but the base address of the array or
address of first element of the array. Array name is pointer to the array.
10 20 30 40 50
2000 2002 2004 2006 2006
2002 2002 2002 a (array name)
&a[0]
Let int a[5] be an array and the computer reserve 5 storage locations as follows:
In general &a[i] is represented as a+i to get the i th elements address of the array.
In general a[i] gives the value at i th location and is represented in pointers by *(a+i)
From the above we can say that the array name appearing as formal argument within the function
definition can be declared as pointer or as array of unspecified size. This will determine in which manner
the individual array elements are to be accessed within the function.
Program 6.8 Program to read and print the elements of one-dimensional array using functions and
pointers
#include<stdio.h>
#include<conio.h>
void READARRAY(int n,int *aptr);
void PRINTARRAY(int n,int *aptr);
void main(void)
{
int n,a[20];
clrscr();
printf("\n\n\t\t Enter the no. of elements to be read of the list : ");
scanf("%d",&n);
printf(“\n\n\t\t Enter n elements of the list :”);
READARRAY(n,a);
printf(“\n\n\t\t Elements of array are : \n “);
for(i=0;i<n;i++)
here aptr+i is equivalent to &a[i]
scanf(“%d”,aptr+i);
if aptr+i gives address of ith location in the array then *(aptr+i) gives the value at ith location.
The following segment of PRINTARRAY displays the values stored in the array
for(i=0;i<n;i++)
Program 6.9 Program to SORT elements of one-dimensional array using functions and
pointers
#include<stdio.h>
#include<conio.h>
void READARRAY(int ,int *);
void PRINTARRAY(int ,int *);
void SORTARRAY(int ,int *);
void main(void)
{
int n,,a[20]; clrscr();
printf("\n\n\t\t Enter the no. of elements to be read to the array : ");
scanf("%d",&n);
printf(“\n\n\t\t Enter elements of the array for sorting:”);
READARRAY(n,a);
SORTARRAY(n,a);
printf(“\n\n\t\t Elements of array after sorting are : \n “);
PRINTARRAY(n,a);
}
Array „a‟ is declared as int array of size 20. „n‟ is declared as int ,is used to accept the no. of elements to
be stored in „a‟, the value of which is between 1 and 20 and the variable is subscript for the array.
Reading of elements is defined through a function READARRAY, as explained in the previous example.
In the calling functions „n‟ is passed by value and „a‟ which is the array name giving the base
address/address of first location of the array. In the function definition „aptr‟ stores the address passed by
„a‟. The expression *(aptr+i) gives the address of ith element of the array in the function SORTARRAY.
*(aptr+i) and *(aptr+i+1) are compared in the functionand performs swapping as already discussed. The
segment of code for displaying elements of the array is done through PRINTARRAY as discussed in the
previous example.
Program 6.10 Program to SEARCH (BINARY SEARCH) for an element in one-dimensionalarray using
functions and pointers
base address
a[1][0] a[1][1] a[1][2]
th 2002
1 I Dim. array
a+1
2006 2008 2010
……………………………………………………………………………… so on 2002
The parenthesis that surrounds the array name and the preceding * is the pointer version of the
declaration. Without which the declaration would be considered as array of pointers rather than pointer to
a group of arrays.
If you have difficulty in memorizing what notation is for pointer to array and array of pointers, try this
:
int (*array)[4] : (, ) operators have higher priority because it is on the left of the [,]. So, it is a POINTER
to [4]. Again it is a POINTER. So, it means it is a pointer to array.
int *array[4] : [,] have higher priority than *, so, it is ARRAY of pointers. It is not pointer, it is ARRAY.
Example 6.11 Program to print base address of each one dimensional array & address of each location of
every one dimensional array
#include<stdio.h>
#include<conio.h>
void rowaddress(int,int (*) []);
void coladdress(int,int,int (*) []);
void main(void)
{
int a[4][6];
clrscr();
printf("\n\n\t\t Base address of each one dimensional array is : \n");
rowaddress(4,a);
printf("\n\n\t\t Address of each element in two dimensional array is : \n");
coladdress(4,6,a);
}
void rowaddress(int r,int(*a)[6])
Here „a[3][4]‟ is the array which is allocated with 3 one dimensional arrays where each one dimensional
array contains 4 elements. It will occupy 12*2 bytes overall. The program contain two functions;
„rowaddress‟ which displays address of each one dimensional array as discussed in introduction;
‟address‟ gives address of each location of each element of the two dimensional array. „i‟ & „j‟are to
select rows and columns respectively.
(a+i) is pointing to base address of each one dimensional array. *(a+i)+j in the function „address‟ gives
the address of each element of one-dimensional array.
Program 6.12 Program to read and print the elements of a matrix using functions and pointers
#include<stdio.h>
#include<conio.h>
void readmatrix(int,int,int (*) []);
void printmatrix(int,int,int (*) []);
void main(void)
{
int a[4][6],r,c;
clrscr();
printf("\n\n\t\t Enter order of the matrix: ");
scanf("%d%d",&r,&c);
printf("\n\n\t\t Enter the elements of matrix row wise:\n");
readmatrix(r,c,a);
printf("\n\n\t\t Elements of the matrix in natural form is \n");
printmatrix(r,c,a);
}
void readmatrix(int r,int c,int(*aptr)[6])
{
register int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",(*(aptr+i)+j));
}
}
}
void printmatrix(int r,int c,int(*aptr)[6])
{
register int i,j;
for(i=0;i<r;i++)
{
}
}
Here „a[4][6]‟ is the array which is allocated with 4 one dimensional arrays where each one dimensional
array contains 6 elements. It occupies 24*2 bytes overall. The program contain two functions;
„readmatrix‟ which reads and stores the elements of matrix at a particular location;
‟printmatrix‟displayselements of the matrix in matrix form.
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",(*(aptr+i)+j));
observe that &a[i][j] used for reading elements in to the array is replaced by *(aptr+i)+j
for(i=0;i<r;i++)
for(j=0;j<c;j++)
printf("%d",*(*(aptr+i)+j));
observe that a[i][j] is replaced by *(*(aptr+i)+j)
Program 6.13 Program to multiply two matrices using functions and explicit pointers
#include<stdio.h>
#include<conio.h>
void readmatrix(int,int,int (*) []);
void printmatrix(int,int,int (*) []);
void matmultiplication(int ,int,int,int(*)[],int (*)[6],int (*)[6]);
void main(void)
{
int F[4][6],r1,c1,S[4][6],r2,c2,R[6][6]={0,0};
clrscr();
printf("\n\n\t\t Enter order of first matrix: ");
scanf("%d%d",&r1,&c1);
printf("\n\n\t\t Enter order of second matrix: ");
scanf("%d%d",&r2,&c2);
if(c1==r2)
{
printf("\n\n\t\t Enter the elements of first matrix row wise:\n");
readmatrix(r1,c1,F);
printf("\n\n\t\t Enter the elements of second matrix row wise:\n:");
readmatrix(r2,c2,S);
matmultiplication(r1,c1,c2,F,S,R);
printf("\n\n\t\t The product matrix is \n");
printmatrix(r1,c2,R);
}
else
*(*(rptr+i)+j)=*(*(rptr+i)+j)+((*(*(fptr+i)+k)) * (*(*(sptr+k)+j)));
}
}
}
}
Here „a‟ is the array which is allocated with 4 one dimensional arrays where each one dimensional array
contains 6 elements. It will occupy 24*2 bytes overall. The program contain two functions;
‘readmatrixs’ which reads and stores the elements of matrix at a particular location; ‟printmatrix‟
displayselements of the matrix in matrix format. Processing of these functions is done as same as the
previous program. i, j ,k are register variables which whose values can be used for identifying different
elements of the array through pointers.
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
Program 6.14 Write a function that receive pointers to two integers and return pointer to the smaller. Call
this in main() to find the smallest of two integers.
#include<stdio.h>
int *small(int *a,int *b)
void main()
{
int a,b;
int *p;
printf(“enter two integers:”);
scanf(“%d,%d”,&a,&b);
p=small(&a,&b);
printf(“the smaller number is %d”,*p);
}
int *small(int *a,int *a)
{
return((*a>*b)?a:b);
}
Variables are named memory locations and they are to hold data to be manipulated by the programs.
Memory allocation for the variables used so far is static memory allocation. Staticmemory allocation
is the phenomenon of allocation of memory during compilation time. The Allocated memory is released
at the end of program execution.
The declaration
int a;
allocates 2 bytes of memory to the variable a at compilation time where as the array declaration
int b[6];
i) If we want to deal with more memory than size of the array during runtime of the
program, we cannot increase the size of array at runtime.
ii) Many a times all the memory allocated during compile time are not used; we cannot
decrease the wastage of memory at runtime.
To overcome the above problems we have the concept of Dynamic Memory Allocation.
Dynamic Memory Allocation is the phenomenon of allocationof memory during run time. Allocated
memory can be released during runtime.
1. malloc()
2. calloc()
3. realloc()
4. free()
The above functions are available in alloc.h, and stdlib.h. Either of the header files can be included.
1. malloc()
The general form of malloc is:
ptr_variable=(cast type) malloc(size of block);
The function allocates a block of memory. On successful memory allocation the function returns a pointer
to the first byte of the block. Allocated space is initialized with garbage.
In the above syntax size of block is block size to be allocated. (cast type) is the cast expression which
indicate the type of data that will be stored in the allocated block. ptr_variableis a pointer of the cast-
type which holds the address of the first byte of the block.
Example: ptr=(int *)malloc(10*sizeof(int));
Allocates 20 bytes of space and returns a pointer to the block which is assigned to the pointer ptr of type
int. This is illustrated in the following figure.
ptr
Size of the block= (10 *2) bytes
2000
2000
The storage space allocated will have no name and hence must be accessed through the pointer only. If
the allocation fails, malloc() function returns a null pointer. Therefore check whether the allocation is
successful before using the pointer.
If sufficient memory is not available malloc() returns a null pointer.
free (ptr_variable);
3. calloc( )
„calloc‟ is used to allocate multiple blocks of memory, all of which are of same size and returns a
pointer to the first byte of the first block. Initialize the allocated space with 0‟s .
„calloc‟has two parameters first is the „no. of blocks to be allocated‟ and the second is the „size
ofblock‟.
ptr_variable is a pointer, which stores the address of the first byte of the first block allocated. If the
function is unable to allocate the requisite space, null pointer is returned and is assigned to the ptr
variable.
Program6.16 Program to read two matrices and find out their product with proper validation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *pa,*pb,m,n,i,j,p,q ,*pc;
printf(“Enter the number of rows and cols of first matrix : \n”);
scanf(“ %d%d “, &m,&n);
printf(“Enter the number of rows and cols of second matrix : \n”);
scanf(“ %d%d “, &p,&q);
if(n!=p)
{
printf(“Multiplication of matrices is not possible”);
exit(0);
}
pa=(int *)calloc(m , n*sizeof(int));
if(pa==NULL)
{
printf(“Memory not allocated”);
exit(0);
}
printf(“Enter the elements of the first matrix in row wise\n”);
for(i=0;i<m;++i)
for(j=0;j<n;++j)
for(i=0;i<p;++i)
for(j=0;j<q;++j)
scanf(“%d ” , (pb+i*q)+j ) ;
for(i=0;i<m;++i)
for(j=0;j<q;j++)
{
*(pc+i*q+j)=0;
for(k=0;k<n;++k)
*(pc+i*q+j)+=(*(pa+i*n+k))*(*(pb+k*q+j));
}
printf(“Product matrix is:”);
for(i=0;i<m;++i)
{
for(j=0;j<q;++j)
printf( %5d” *(pc+i*q+j));
printf(“\n”);
}
getch();
}
The problem is to store the elements of a matrix with m rows and n columns. So m blocks of memory
each of them to hold n integers is to be allocated.
4. realloc()
malloc() and calloc() are functions used to dynamically allocate memory for storage. But in some
circumstances we need to alter the memory allocated by the above functions during runtime. This is
achieved with the help of realloc().
Here old_ptr is the pointer to the block which has been allocated and is to be altered (increased/
decreased).
ptr1=(char *)realloc(ptr1,sizeof("K.L.University"));
Above statement allocates memory to be reallocated for the pointer „ptr1‟ which will set the pointer to 15
bytes.
strcat(ptr1,ptr2); statement appends the second string to the first string, resulting in “K.L.University”
SUMMARY
Pointer is a variable which stores address of another variable or address of block of memory.
Concept of pointers are extensively used with their operators & and *. Operators are used toexplain
different operations that are possible. Arithmetic‟s of pointers are used to relate pointers and
arrays. Accessing of elements of array are done through pointers. Strings can also be dealt with
pointers. Allocation of memory at run-time is done through Dynamic Memory Allocation. malloc,
calloc are dealt as memory allocation functions where as realloc as memory reallocation to change
the memory and free to de-allocate memory that has been allocated.
6.1. Which of the following statements is true after execution of following program segment?
int a[5]={2,3},*p=a;
(*p)--;
(a) the value of a [0] will be 1 (b)the value of a[0] will be 2
(c) the value of a[1] will be 2 (d)none of these.
6.2. The fastest way to exchange two rows in a two- dimensional array is
a) exchange the address of each element in the two rows.
b) exchange the elements of two rows.
c) store the addresses of the rows in an array of pointers and exchange the pointers.
d) none of these.
6.3. Which is the correct way to declare a pointer ?
a ) int *ptr; b) *int ptr; c) int ptr*; d) int ptr x;
6.4. What will be the result of the following program?
main()
{
int a=8,b=2,c,*p=&c;
c=(a=a+b,b=a/b,a=a*b,b=a-b);
printf(“\n %d”,++*p);
}
a)45 b)46 c)50 d)51
6.5. What will be the value of x after execution of the following program?
void main()
{
int x,*p;
p=&x;
*p=2;
printf(“\n x=%d”,x);
}
a)x=2 b)x=0 c)x=65504 d)none of the above .
6.6. What will be the value of variable a1 and a2 after execution?
main()
{
int a1,a2,c=3,*p;
p=&c;
a1=3*(c+5);
a2=3*(*p+5);
}
a)a1=24,a2=24 b)a1=12,a2=24 c)a1=12,a2=24 d)none of the above.
6.41. If p1 and p2 are valid pointers in the same array, then which of the following statements is
valid?
a) p1 + 2 b) p1 – p2 c) p1 * p2 d) both a and b
6.42. What will be the output of the following code is executed
main ()
{
int a [5] = {1,2,3,4,5};
int *b= &a [2];
printf(“%d”, *(b-1));
}
a) 2 b) 3 c) 4 d)
6.43. int x, y [10];
6.71. p and q are pointers to same type of data items which of the following expressions is invalid?
a) p+2 b)q-p c)q-p+1 d) q+p
6.72. p and q are pointers to same type of data items which of the following expressions is valid?
i) *(p+q) ii)*(q-p) iii)(*p)*(*q)
a) all b) (i) and (ii) c) (ii)and(iii) d) (ii) and (iii)
6.73. What is the output ?
main()
{
int a[5],*p;
for(p=a;p<&a[5];p++)
{ *p=p-a;
printf(“%d”,*p);
}
}
a) 0 1 2 3 4 b) 0 2 4 6 8 c) 1 2 3 4 5 d) compilation error
LEARNING OBJECTIVES
After reading this chapter, the readers will be able to
understand input and output concepts as they apply to C programs.
use different input and output functions available in the C library.
understand formatted input & output using prinf() & scanf() functions.
7.1 INTRODUCTION
One of the essential operations performed in a C language program is to provide input values to the
program and output the data produced by the program to a standard output device. We can assign values
to variable through assignment statements such as x = 5; a = 0; or initialize variables in the type
declaration statement like
Another method is to use scanf() function which can be used to read data from the key board. For
outputting results we have used extensively the function printf() which sends results out to a terminal.
There exists several functions in „C‟ language that can carry out input output operations. These functions
are collectively known as standard Input/Output Library.
where variable_name is any valid C identifier that has been declared as single character type. When this
statement is encountered, the compiler waits until a key is pressed and then assigns this character as a
value to getchar(). Since getchar() is used on the right-hand side of an assignment statement, the character
value of getchar() is in turn assigned to the variable_name on the left-hand side.
For example:
char ch;
ch=getchar();
will assign the character ‟H‟ to the single character variable ch when we press the key ‟H‟ on the
keyboard. Since getchar() is a function, it requires a set of parentheses as shown in the above example. It
accepts no arguments and returns a single character constant.
Program 7.1 Program for reading & writing a character
Output:
Type one character
K
The character you typed is =K
C supports many other similar functions which are given in the table below .These character functions
are contained in header file ctype.h .Assume ch is declared as character type variable
#include,stdio.h>
#include<ctype.h>
The only one argument that is specified in the pair of parentheses should be either a single character
variable (or) a single character constant (or) an integer constant (or) any expression whose result should
be of single character type. No other data type is allowed.
variable is any C identifier containing a character declared as a single character type. If variable is used
as an argument to putchar(), the character that is stored in that variable is displayed.
Constant is any single character constant (or) an integer constant. If a single character constant is
used as an argument to the putchar(), it is directly displayed on the output terminal whereas if an integer
constant is used as an argument to putchar(), the character whose ASCII value is equivalent to the
specified integer constant will be displayed on the output terminal.
If an expression is used as an argument to the putchar() function, the result of that expression
which is of single character type will be displayed directly on the output terminal. If the expression whose
result is of integer type is used as an argument, its ASCII character will be displayed on the output
terminal.
Example 7.1:
G R E E N F I E L D S \0
Output
This is printed with the puts() function!
Example 7.3:
puts("This prints on the first line. \nThis prints on the second line.");
puts("This prints on the third line.");
puts("If we used printf( ) instead of puts( ), all four lines would be on two lines!");
Output
This prints on the first line.
This prints on the second line.
This prints on the third line.
If we used printf( ) instead of puts( ), all four lines would be on two lines!
#include<stdio.h> Output:
main() Type a string less than 80
{ char s[80]; characters
printf (“Type a string less than 80 characters”); the string typed is
gets(s); K L UNIVERSITY
printf(“\n the string typed is\n”);
puts(s);
}
7.4 FORMATTED INPUT
The formatted input refers to input data that has been arranged in a particular format. Input values are
generally taken by using the scanf() function. The scanf() function has the general form.
scanf(“control string”,&variable1,&variable2,….);
The control string contains format of the data being received. The ampersand symbol (&) before each
variable name is the address operator that specifies variable name‟s address. The use of & is must in
scanf() function.
The control string also specifies the field format which includes format specifications. Each format
specification must begin with % sign followed by conversion character which indicates the type of
corresponding data item. and optional number specifying field. width.
The blanks, tabs and newlines will be real but are ignored. Multiple format specifiers can be contiguous,
or they can be separated by white space characters. If whitespace characters are used to separate the
formats, then they will be read but are ignored.
%s – read a string
%[ character set]-read only the characters specified with in brackets when inputting string
%[^character set]- The characters specified after ^(circumflex) are not permitted in the input
string.
%wd
Here
percent sign (%) denotes that a specifier for conversion follows
w is an integer number which specifies the width of the field of the number that is being read.
The data type character d indicates that the number should read is integer mode.
Example7.4:
scanf (“%3d %4d”, &sum1, &sum2);
If the input is
175 1342 sum1
175 sum2
1342
If the input is
1342 175 . 134 2
If floating point numbers are assigned then the decimal or fractional part is skipped by the computer and
scanf() skips reading further input.
Assignment Suppression:
An input data item may be skipped without assigning it to the designated variable or array by placing *
after the % sign. For example,
scanf(%d %*d %d”,&a,&b);
If the input is 123 789
123 456 789
123 assigned to a a b
456 skipped (because of *)
789 assigned to b
In the above example, as the second format contains the input suppression character „*‟, the second input
item 23 is not assigned to any variable. Hence, 12 and 45 are assigned to a and b and c holds garbage
value.
Field specifications are not to be used while representing a real number. Therefore real numbers are
specified in a straight forward manner using %f or %e specifier. The general format of specifying a real
number input is
scanf (“%f ”, &variable);
or
scanf (“%e”, &variable);
For example,
Output:
Enter values of x & y 12.3456 17.5e-2
x=12.345600 y=0.175000
Enter values of p & q 4.142857142857 18.5678901234567890
P=4.142857142857 q= 1.856789e+01
In section 7.2.1 we have seen that a single character can be read from the terminal using getchar()
function .The same can be achieved using scanf() function also using „%c‟ format specifier or %1s
specifier The general format is %c or %1s. For example,
char ch;
scanf(“%c”, &ch);
Suppose the input data item is V, then the character V is assigned to ch.
If the control string contains multiple character formats same care must be taken to skip whitespace
characters in the control string. As the whitespace character is also interpreted as a data item, to skip such
whitespace characters and read the next nonwhite space character , the format %1s can be used.
Example 7.5: Consider the following program
#include<stdio.h>
main( )
{
char ch1, ch2, ch3;
scanf(“%c%c%c”, &ch1, &ch2, &ch3);
printf(“%c %c %c \n”, ch1, ch2, ch3);
}
If the input data consists of
p q r
then the following assignments would result:
ch1=p , ch2 =<blank space> , ch3= q
We could have written the scanf function as
scanf(“%c %c %c”, &ch1, &ch2, &ch3);
with white blank spaces seperaing the format specifier %c or we could have used original scanf
statement with the input data as consecutive characters without blanks; i.e., pqr.
A scanf() function with %wc or %ws can be used to input strings containing more than one character.
The general format is
% wc or %ws
Where c and s represents character and string respectively and w represents the field width.
scanf () function supports the following conversion specifications for strings.
%[character set] and %[^character set] :
%[character set] specification means that only the characters specified with in brackets are
permissible in the input string. If the input string contains any other character, the string will be
terminated at the first occurrence of such a character.
%[^character set] specification does exactly the reverse.. i.e. The characters specified after
^(circumflex) are not permitted in the input string .The reading of string will be terminated when one of
these characters is encountered.
The address operator need not be specified while we input strings.
The specification %s terminates reading at the encounter of a white space character.
For example
Char str[25]
scanf(“%4c”, str);
Reads characters from keyboard until the user enters a white space character. . Only first four characters
of the string will be assigned to the string variable str.
1. If the user input is
“abcd ef” ,the string variable str holds ”abcd”
2. scanf(“%s”,str)
In the above example when newline(\n) is entered, reading will be terminated. Hence string
variable address will be “Vijayawada 520001”
printf(“control string”,exp1,exp2,exp3,……);
The control string contains format of the data to be displayed and exp1,exp2,exp3…are output
expressions.
%wd
where
w-specifies minimum field width for the output .However , if a number is greater than specified
width it will be printed in full
d- specifies that value to be printed is an integer.
The number will be right justified
Negative numbers will be printed with – sign
printf(“%d”,9876); 9 8 7 6
printf(“%6d”,9876); 9 8 7 6
printf(“%2d”,9876); 9 8 7 6
printf(“%-6d”,9876); 9 8 7 6
printf(“%06d”,9876);
0 0 9 8 7 6
placing - sign after % causes the output left justified with in the field. Remaining field will be
blank
placing 0 before the filed width specifier causes leading blanks padded with zeros.
Let x=98.7654
Format output
printf(“%7.4f”,x) 9 8 . 7 6 5 4
printf(“%7.2f”,x) 9 8 . 7 7
printf(“%-7.2f”,x) 9 8 . 7 7
9 8 . 7 6 5 4 0 0
printf(“%f”,x)
printf(“%10.2e”,x) 9 . 8 8 e + 0 1
printf(“%-10.2e”,x) 9 . 8 8 e + 0 1
printf(“%11.4e”,-x) - 9 . 8 7 6 5 e + 0 1
%wc
%s
K L U N I V E R S I T Y
%20s K L U N I V E R E S I T Y
%20.5s K L U
%.5s K L U
%-20.8s
K L U N I V
%5s K L U N I V E R S I T Y
%g- print a floating point value using either e-type or f-type, conversion depending on
value. Trailing zeros and trailing decimal points will not be displayed
%s – print a string
The following letters may be used as prefixes for certain conversion characters‟
none
Output is right-justified
Justification
-
Output is left-justified
None Positive Value: no sign
Negative Value: -
sign
+ Positive Value: +
Negative Value: -
None
Space padding
0
Causes leading 0‟s to appear(Zero padding)
#(with 0 or
padding Causes octal and Hexa decimal numbers to be
0x)
preceeded by 0 or 0x,respectively
Causes a decimal point to be present in all
#(with e,f,g)
floating point numbers even for whole number.
Prevents truncation of trailing 0‟s in g-type
Example 7.8:
#include<stdio.h>
main()
Output:
{
Enter two integers
int a,b,;
12 -23
printf (“\n Enter two integers\n”);
12 -23
scanf(“%d %d”,&a,&b);
+12 -23
printf(“ \n%5d\t %5d”,a,b);
00012 00-23
printf(“ \n%+5d\t %+5d”,a,b);
printf(“ \n%05d\t %05d”,a,b);
}
Example 7.9:
#include<stdio.h>
main()
Output:
{
Enter two octal integers
int a,b,c,d;
12 45
printf (“\n Enter two octal integers\n”);
Enter two hexadecimal integers
scanf(“%0 %0”,&a,&b);
94 2d
printf (“\n Enter two hexadecimal integers\n”);
12 45
scanf(“%x %x”,&c,&d);
94 2d
printf(“ \n%o\t %o”,a,b,);
012 045
printf(“ \n%x\t %x”,c,d,);
0x94 0x2d
printf(“ \n%#o\t %#o”,a,b,);
printf(“ \n%#x\t %#x”,c,d,);
}
Comprehensive questions
7.1. Write a small program that will prompt for the input of a value for each of the following types:
%c - Yes or No
%s - Your Name
%f - Your Height
%ld - The Circumference of the Earth
%f - Your Bank Balance
%lf - The Distance from the Earth to the Moon
Read the values with scanf() and then print those values out on the display using printf().
7.2. Write a program that will prompt for the input of a temperature in Fahrenheit and will display as
output both the Fahrenheit value and the temperature converted to Celsius. Use the formula
Celsius Degrees = (Fahrenheit Degrees - 32) * 5/9
LEARNING OBJECTIVES
After going this chapter the reader will be able to
Use different input/output functions for string
Learn the usage of important string manipulation functions available in the header file string.h
Write his own functions for string manipulation
Learn the storage and manipulation of multiple strings.
8.1. INTRODUCTION:
C does not support string data type . Strings in C are represented by arrays of characters.
The end of the string is marked with a special character , the null character „\0‟ whose ASCII value is
zero.
\0
A string variable is any valid C variable name and it is always declared as an array. Hence to declare a
string variable we use character array. The general format is
Strings 204
char str[size];
Where str is a string variable and the size determines the number of characters in the string. Consider the
following array declarations
char city[10],name[20],address[25];
Where city, name and address are character arrays which can hold strings of length 9,19 and 24 characters
respectively
Initializing strings:
We can initialize a string the same way that we initialize any other variable by assigning a value to it
when it is defined. In this case the value is a string. For example
If we declare city as
then the null character will not be appended automatically to the character array . because , city can hold
9 characters and the string HYDERABAD has already 9 characters filling the 9 spaces.
Since a string is stored in a character array , while initializing through type declaration, size of the array
can be omitted as shown below.
In this case compiler will create an array of 10 bytes and initialize it with HYDERABAD followed by
null character
Since a string variable is a character array, one string variable cannot be assigned to another
string variable.
char str1[6 ] = “green”,str2[6];
str2 = str1;
When pointers are initialized with strings we can assign one string to another string.
char *str1=”green”,*str2;
str2=str1;
Strings 205
A character array cannot be initialized with a string by an assignment statement.
char city[10];
city = “HYDERABAD”;
The familiar input function scanf ( ) can be used with %s conversion specification to read string of
characters.
Example 8.1:
char city[15];
scanf(“%s”,city);
If the input is
VIJAYAWADA
V I J A Y A W A D A \0 ? ? ? ?
The „\0‟ (null character) is appended automatically after the last character to designate the end of the
string.
The problem with the scanf function is that it terminates its input on the occurrence of first white space .
Example8.2:
char city[20];
scanf(“%s”,city);
If the input is
GREEN FIELDS
Only first word GREEN is read and is stored in the memory as given below
G R E E N \0
gets() function is useful to read strings from the keyboard. The general syntax is
Strings 206
gets(str);
str is any valid string variable name and it will read a string of characters until enter key is pressed(i.e
until new line character is entered).
Example8.3:
char city[20];
gets(str);
If the input is
GREEN FIELDS
G R E E N F I E L D S \0
The „\0‟ (null character) is appended automatically at the end of the string to designate the end of the
string.
The function scanf() also allows for the input of string through the scan set , which is a sequence of
characters enclosed in square brackets[] and proceeded by a % sign . The scan set causes the function
scanf() to search for the characters in the input string that matches those in the scan set. Only those
matching characters are stored in the corresponding array. The scan set operation terminates once a
character not contained in the scan set is encountered.
Example 8.4:
char str[10];
scanf(“%[pqrst]”,str);
p q r s \0
The inverted scan set can also be used for character input. The inverted scan set does the opposite of scan
set. This means that only characters not appearing with in the square brackets are stored inside the
character array. An inverted scan set is identified by a caret ^ with in the square brackets and preceding
the character sets
Example 8.5:
char str[20];
Strings 207
scanf(”%[^\n]”,str);
The string entered through key board until new line character is taken and is stored in the array str.
G R E E N F I E L D S \0
Example8.6:
char str[50];
int i=0;
while((str[i]=getchar()) !=‟\n‟)
++i;
str[i] =‟\0‟;
Note that null character(„\0‟) must be appended explicitly in this case. We can also use any other
character in place of „\n‟ and the string will be read until that character is entered.
printf(“%s”,str);
Unlike scanf() even if the string contains white space characters entire string is displayed
Example8.7:
printf(“%s”,str);
would output
GREEN FIELDS
Strings 208
Using puts() function :
puts() function is useful to print/display string on the screen. The general syntax is
puts(str);
Program 8.1 program to read and write string using gets and puts functions.
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf(“enter string from keyboard\n”);
gets(name);
printf(“the string is\n “);
puts(name);
getch();
}
The output for above program is
Enter string from keyboard
Good morning
The string is
Good morning
Program 8.2 Program to copy one string into another string
#include<stdio.h>
#include<conio.h>
void main()
{
char source[20],destination[20];
int i=0;
clrscr();
printf(“enter any string from keyboard\n”);
gets(source);
while((source[i] = destination[i] ) !=‟\0‟)
i++;
printf(“the destination string is \n”,);
puts(destination);
getch();
}
The character of the string destination are copied into the string source one by one until null character is
copied. After the null character is copied, while loop condition becomes false and control is exited from
the loop.
C language supports several functions useful for string manipulation. Whenever these functions are used
the header file string.h must be included. Some of the functions are:
1. strlen(): This function returns length of a string, that is counts no of characters in the string
excluding null character. If the string is empty it returns zero. The general format of this function is
Strings 209
n=strlen(str);
Where n is an integer variable which receives the length of the string str.
Welcome
2.strcat(): This function is useful to join two strings together. The general format of strcat() function is
strcat(str1,str2);
str1, str2 are two string variables. When strcat() function is executed str2 is appended to strg1 and str2
remains unchanged.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20] =“hello”,str2[20] =”world”;
clrscr();
printf(“the two strings before concatenation\n”);
printf(“the first string is %s”,str1);
printf(“\n second string is %s”,str2);
Strings 210
strcat(str1,str2);
printf(“the two strings after concatenation\n”);
printf(“\nthe first string is %s”,str1);
printf(“\n second string is %s”,str2);
getch();
}
3.strcmp(): This function is useful to compare to strings. If the two strings are similar then it returns 0 ,
otherwise , it returns the difference between the ASCII values of first pair of non-matching characters.
The general syntax is
strcmp(str1,str2);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int n;
char str1[20],str2[20];
clrscr();
printf(“enter any two strings\n”);
scanf(“%s%s”,str1,str2);
n=strcmp(str1,str2);
if (n==0)
printf(“two strings are same”);
else
printf(“strings are not same”);
getch();
}
4.strcpy(): This function is useful to copy one string into another string. The general syntax is
strcpy(str1,str2);
Strings 211
The content of str2 will be copied into str1.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf(“Enter the first string\n”);
gets(str1);
printf(“Enter the second string\n”);
gets(str2);
printf(“strings before copying\n”)
printf(“%s\t%s”,str1,str2);
strcpy(str1,str2);
printf(“two strings after copying\n”);
printf((“%s\t%s”,str1,str2);
getch();
}
Program8.7 : Program to check the given string is palindrome.
#include<stdio.h>
#include<string.h>
void main()
{
char str[100];
int i,n,j,flag=0;
printf(“enter the string to be checked\n”);
gets(str);
n=strlen(str);
for(i=0, j=n-1; i<j; ++i, --j)
{
if(str[i] != str[j])
{
flag=1;
break;
}
}
if (flag ==1)
printf(“given string is not a palindrome”);
else
print(“given string is palindrome”);
}
Using the function strlen() length of the string is obtained and is assigned to n. Initial values of i and j
are 0 and n-1 respectively, represents the first and last positions of the string. If the given string is not
palindrome, a pair of corresponding characters from the beginning and end are unequal and the loop is
Strings 212
terminated after 1 is assigned to flag, otherwise, the initial value of flag 0 is not changed.
The following are some other string functions which we commonly use in c programming language.
strrev(string);
Example 8.8:
Output:
2.strstr(): This function is used to locate a sub string in a string. The general syntax is
strstr(str1,str2);
This function searches str1 to see whether str2 is contained in str1.If yes, then the function returns the
position of the first occurrence of the sub string str2 otherwise, it returns a NULL pointer.
3.strchr() This function is used to locate the first occurrence of a character in a string. The general
syntax is
strchr(str1,character);
Example 8.9:
strchr(“this is an example”,‟a‟);
4.strlwr(): This function is useful to convert upper case string into lower case. The general syntax is
Strings 213
String is any valid string variable which holds upper case data.
strlwr(str);
5.strupr(): This function is useful to convert lower-case data into upper-case.The
general format for this function is
strupr(str);
A list of names can be treated as a table of strings and two dimensional character arrays can be used to
store the entire list.
Since a two dimensional array is an array of one dimensional arrays, str[0],str[1],str[2] etc represent the
pointers to first, second third etc rows of the two dimensional array str.Thus the following code can be
used to store the list of names in the two dimensional array.
for(i=0;i<n;++i)
gets(str[i]);
Similarly , the following code can be used to display the list of names.
for(i=0;i<n;++i)
puts(str[i]);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[10][20],temp[20];
int n,p,i,j;
clrscr();
printf(“Enter the strings one by one ,at the end of the list type END:\n”);
i=0;
while(i)
{
gets(str[i]);
if(strcmp(str[i],”END”)==0)
break;
++i;
}
n=i;
/* sorting process begins*/
for(p= 1; p < n;pi++)
{
Strings 214
for(j = 0; j <= n-p; j++)
{
if (strcmp(str[j],str[j+1]>0)
{
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
printf(“\n The sorted list of names is :\n”);
for(i=0; i<n; i++)
printf(“%s\n”,str[i]);
getch();
}
This program allows the user to enter unspecified number of strings until the string END is entered. The
program will count the strings as they are entered, ignoring the last string END. Here str is a two-
dimensional character array.str[0],str[1], str[2] etc are pointers to 0 th, 1st, 2nd etc rows of it, i.e they are
pointers to 1st, 2nd, 3rd etc strings entered through keyboard. strcmp( ) function used at two places: while
testing for a stopping condition, and in rearrange, to test the need for interchange of strings. The actual
interchange of strings is done through strcpy( )function.
8.7.POINTER TO STRINGS
In section 8.1 we have seen that strings are one-dimensional arrays of type char and therefore they are
declared and initialized as follows.
char str[10]=”GREEN”;
The compiler automatically append null character at the end of the string.
The following examples specify that how the pointers are used in string manipulation functions.
while(*p!=‟\0‟)
++p;
is executed until the end of the string is reached . When the while loop is terminated, the pointer p holds
the address of the null character. Hence the expression (p-q) gives the length of the string.
Strings 215
Example 8.11: Function to copy one string to another string.
void str_cpy(char *ptr1, char *ptr2)
{
while((*ptr1 = *ptr2) !=‟\0‟)
{
++ptr1;
++ptr2;
}
return;
}
The content of the second string represented by pointer ptr2 is copied in to the string represented by ptr1
until the null character is copied.
Example 8.12: Function to concatenate one string at the end of another string.
Example 8.13:
char *str[10]=”EXAMPLE”;
char *p=&str[0];
E X A M P L E \0
P
A character pointer may be initialized with a string constant
Strings 216
The address of the constant is stored in the pointer variable str . The pointer str now points to the first
character of the string “EXAMPLE” as:
Where p represent the address 2000 of E and p+1 ,P+2,p+3, etc.. represent the addresses (2001,2002,2003
etc..) of the characters X,A,M etc.. We can also give values to the string pointer by assigning strings
during runtime using scanf() with %s format or gets() function.
Example 8.14:
char *str;
p+1
scanf(“%s”,str); (or)
gets(str);
The contents of the string str can be printed using either printf() or puts() functions.
printf(“%s”,str); (or)
puts(str);
Strings 217
A constant character string always represents a pointer to that string Hence the following statements are
valid.
char *ptr;
so the character string “GREEN FIELDS”; is assigned to the pointer to character str.
Example8.15:
char place[20];
is not allowed.
The comparison of the strings is done until there is a mismatch or one of the strings terminated in to a null
character, whichever occurs first When the control exits from the loop the difference between the ASCII
value of the first pair of non-matching characters is returned.
Strings 218
++eptr;
is executed eptr points to the null character .When it is decremented in the initial expression of the for
loop it points to the last character of the string.Initially first and last characters are interchanged and then
second and last but one characters are interchanged and so on . To access the next characters starting
pointer str is incremented by 1 and the end pointer eptr is decremented by 1 in each repetition.
A list of strings can be stored in the memory in another way. For each string, a memory block is allocated
through malloc() function and the pointer to that block is stored in an array of pointers to strings . The
declaration
char *str[20];
The following program code can be used to allocate the memory block for each string and store the string
in that block
for(i=0;i<n;++i)
gets(str[i]);
The following program will illustrate the sorting a list of names using array of pointers.
Program 8.10 Program to arrange a list of names in alphabetical order using array of pointers
#include<stdio.h>
#include<conio.h>
void main()
{
char *str[20],*temp;
int i,n;
printf(“Enter the number of names:”);
scanf(“%d”,&n);
printf(“Enter the names:\n”);
for(i=0;i<n;++i)
{
str[i]=(char*)malloc(15*sizeof(char));
flushall();
gets(str[i]);
}
for(p=1;p<n;++p)
for(i=0;i<n-p;++i)
if(strcmp(str[i],str[i+1]>0)
{
temp=str[i];
str[i]=str[i+1];
Strings 219
str[i+1]=temp;
}
printf(“The list of names in alphabetical order :\n”);
for(i=0;i<n;++i)
puts(str[i]);
getch();
}
Note that if the strings are not in alphabetical order the pointers to the strings are interchanged rather than
the strings. This would result in the saving of execution time.
SUMMARY
A single character is assigned to 0 character variable , that is stored in the memory allocated to
a character variable .
A string is a group of characters and is stored in a character array.
Although C does not have a string data type , it allows string constant
scanf() function with %s conversion, gets[] function, scan set inverted scan set, using getchar()
function repeatedly can be used to input strings
When stored in the memory the string will be terminated by the null character „\0‟ and is used to
identify the end of the string.
printf() function with %s conversion , puts() functions can be used for string output.
There are several library functions in the header file <string.h> for manipulations of strings
List of strings can be stored in a two dimensional character array.
EXERCISES
Review Questions:
8.1 Describe the limitations of getchar(), gets() and scanf() functions in reading string
8.6 _______ function does not require any conversion specification to read a string from the key board.
8.7 When reading a string with scanf() , terminating null character is automatically inserted(T/F).
8.8 When reading a string with scanf() using the conversion specification %s , stop reading when
white space character is encountered (T/F)
8.9 While concatenating two strings the function strcat() insert a space between them (T/F)
8.10 ______ string manipulation function is used to determine whether a character is present in a
string.
1. Which library function is used to append one string at the end of another string
Strings 220
1) strcpy 2) strstr 3) strcat 4) strcmp
#include<stdio.h>
main()
int i=0;
while(str[i]!=‟\0‟)
if(i%2==0)
printf(“%c”,str[i]);++i;
char str[][10]={“BLUE”,”RED”,”ORANGE”,”GREEN”,”YELLOW”}
puts(str[2]);
Strings 221
a) char str[10],str2[10]=”HELLO”; b) char str[6],str2[10]=”HELLO”;
strcpy(str1,str2); strcpy(str1,str2);
str1=str2; str=”HELLO”;
printf(“%d”,strcmp(“Rahul”,”Rajiv”));
9) Which of the following statements will correctly store the concatenation of the strings str1 and str2 in
the str3
a) strcpy(str3,strcpy(str1,str2)); b) strcpy(str1,str2,str3);
c) strcpy(str3,strcat(str1,str2)); d) strcpy(strcat(str1,str2),str3);
char str[10]=”GREEN”;
int i=0;
while(str[i]!=‟\0‟)
{
putchar(str[i]+1);
++i;
}
a) HSFFO b)5 c)FQDDM d)Invalid code
8.1 What are the different ways in which a single character and a string can be accepted and
displayed
8.2 Write a program to read two strings and compare them using the function strcmp() and print a
message that the first string is equal , lesser or grater than the second one
8.3 Develop a program to check given name is present in the given list or not.
8.4 Write a program to accept a list of strings and display the largest string.
Strings 222
8.5 Write a program to accept a string and a character and find out whether this character is present in
the string.
8.6 Write a program to find length of string including and excluding spaces.
8.7 Write a program to copy source string to destination string up to a specified length. Length is to
be entered through the keyboard.
8.8 Write a program to extract a substring of given length from a string starting from a given
position.
8.9 Write a program to delete all occurrence of vowels in a given text assume that the text length will
be of one line.
8.10 Write a program to encrypt the text “INDIA” the output should be ”KPFKC” („A‟ should be
replaced with „C‟, „B‟ with ‟D‟ and „C‟ with „E‟ and so on).
8.11 Write a program which will read a text and count all occurrences of a particular word.
8.12 Write a program which will read a string and rewrite it in alphabetical order. for
example the word HELLO should be written as OLLEH.
8.13 Write a program to enter a string containing combination of capital, small, symbols and
numerical characters. Carry out separation of capitals, small, symbols and numerical by using
ASCII values from 48 to 122.
8.14 Write a program to display alphabets as given below .
az by cx dw ev fu gt hs ir jq kp lo mn nm ol pk qj ri sh tg uf ve wd xc yb za.
8.15 Given a string
char str[]=”123456789”;
write a program that displays the following:
1
232
34543
4567654
567898765
K
KL
KLU
KLUB
KLUB S
KLUB
KLU
KL
K
8.17 Write a program to convert each character of a string into the next character and print the same.
8.18 Write a function that takes a string and number between 0 and 9 as parameters and display the string
that many times and returns its length.
8.19 Write a program to read a sentence and count the number of times each of the vowels appears in it,
count the consonants separately.
Strings 223
STRUCTURES, UNIONS AND ENUMERATED DATA TYPES
LEARNING OBJECTIVES
After reading this chapter, the readers will be able to
understand the purpose of the user defined data types – Structures, Unions and Enumerated data
types.
declaration of structure data types and variables.
access, initialize and process the structure members and the entire structures.
use array of structures and nested structures.
use structures as function arguments and return values.
use pointers to access structures and their members.
learn about union data types.
learn the purpose of enumerated data types.
9.0 typedef
The typedef keyword allows the programmer to create a new data type name for an existing data type. No
new data type is created but an alternative name is given to any standard data type or derived data type.
The general form of the declaration statement using the keyword typedef is
typedef statements can be placed anywhere in a C program as long as they precede to their first use in
the program.
The typedef identifier is traditionally coded in uppercase.
Example 9.0
typedef int MARKS;
typedef int ID_NUMBER;
typedef float HEIGHT;
typedef char UPPER_CASE;
In the first two statements typedef used to give new data type name MARKS and ID_NUMBER
respectively to the standard type int, while HEIGHT is the new name given to the data type float and
UPPER_CASE is the new name given to the data type char .
MARKS English, physics, chemistry;
ID_NUMBER student, employee;
HEIGHT building, tower, hill;
9.1. INTRODUCTION:
We have seen that arrays can be used to represent logically related data items that belong to the same data
type using a single name. However, array cannot be used to represent a collection of logically related
items belonging to different data types using a single name. To tackle this suitably, C supports a user
defined data type known as structure that can store related information of same data type or different data
types together under a single name. For example, it can be used to store the related items of different data
types : employee number, name, basic pay, da, hra, gross pay and net pay together under a single name.
Some other examples of structure are:
Each element in a structure is called a field. It has many of the characteristics of the variables that have
been used in the programs so far. It has a type, and it exists in memory. It can be assigned values, which
in turn can be accessed for selection or manipulation. The primary difference between a field and variable
is field is part of a structure.
The difference between an array and a structure is that all elements in an array must be of the same type,
while the elements in a structure can be of the same or different types.
There are two ways to declare a structure : tagged structure and type – defined structures.
Tagged structure
A tagged structure can be used to define variables, parameters, and return types. The general syntax is
struct TAG
{
data type field1;
data type field2;
…. … ….;
data type fieldn;
};
A tagged structure begins with the key word struct followed by TAG. The TAG is the identifier for the
structure, and it allows us to declare structure variables, function parameters and return type. Field1
,field2, … fieldn can be variables ,arrays, pointers or other structure variables. After the closing brace, if
semicolon is there no variables are declared.
Example 9.1:
struct student
{
long int id_no;
char name[20];
int age;
float cgpa;
};
Type declaration with typedef
The more powerful way to declare a structure is to use a type definition typedef . The general syntax is
…. … ….;
}TYPE;
An identification TYPE is required at the end of the block , The identifier is the type definition name.
Example 9.2:
typedef struct
{
long int id_no;
char name[20];
int age;
float cgpa;
}STUDENT;
Structure
STUDENT
9.3 Declaring structure variables
After a structure has been declared, we can declare variables using it. The structure variable declaration is
similar to the declaration of any other data type. The following examples will demonstrate the declaration
of structure type and the variables that use it.
Example 9.3:
typedef struct
struct student
{ {
long int id_no; long int id_no;
char name[20]; char name[20];
int age; int age;
float cgpa;
}; float cgpa;
struct student first, second , third; }STUDENT;
STUDENT first , second, third;
Remember that the fields of structure themselves are not variables. They do not occupy any memory until
they are associated with structure variables such as first, second, third. When the compiler encounters
declaration statement, it allocates memory space for the structure variables.
The declaration of structure variables can be combined with the definition of tagged structure as
shown in the following example.
Example 9.4:
struct student
{
long int id_no;
char name[20];
int age;
float cgpa;
}first, second, third;
If the variables are declared in the definition of tagged structure the use of tag is optional
Example9.5:
struct
{
long int id_no;
char name[20];
int age;
float cgpa;
}first, second, third;
But the problem with this definition is without tag name we cannot use it for future declarations.
Initialization:
We can initialize structure. The rules for structure initialization are similar to the rules for array
initialization. The initializers are enclosed in braces and separated by commas. They must match with
corresponding types in the structure definition.
Example 9.6:
typedef struct
{
long int id_no;
int age;
char gender;
float cgpa;
}STUDENT;
STUDENT ex6={11000136,16,‟M‟,7.8};
In this example there is an initial value for each structure member.
11000136 16 M 7.8
Id_no age gender cgpa
Example 9.7:
Since there are no initial values for gender and cgpa, they are initialized with null and zero respectively.
Individual members cannot be initialized in the structure definition .The following initialization is not
valid
struct student
{
long int id_no=11000035;
char name[20]=”XXX”;
int age=16;
float cgpa=7.2;
};
9.4 ACCESSING STRUCTURE MEMBERS
Any field of a structure cannot be accessed directly. It can be accessed through the structure variable by
using the operator „.‟ Which is also known as „dot operator‟ or period operator. The general syntax is
<structure variable name>.<fieldname>
In example 9.3, the fields of the structure id_no, name, age and cgpa through the structure variable first
can be accessed by
first.id_no
first.name
first.age
first.cgpa
Structure fields can be used in expressions like ordinary variables or array elements.
We can read data into and write data for structure members just as we can for individual variables. The
value for the fields of the structure in example 9.3 can be read from the keyboard and placed in the
structure variable first using the following scanf() statement.
scanf(“%d%[^\n]%d%f”,&first.id_no,first.name,&first.age,&first.cgpa);
Note that the address operator at the beginning of the structure variable name.
The structure member operator „ .„ has highest priority along with the operators( ) and [ ], and the
associatively is left to right.
Increment and decrement operators can be applied to numeric type members
first.age ++;
typedef struct
{
long int id_no;
char name[20];
int age;
float cgpa;
}STUDENT;
#include<stdio.h>
void main()
{
STUDENT first;
printf(“Enter the Id number:”);
scanf(“%ld”,&first.id_no);
printf(“Enter the name :”) ;
gets(first.name);
printf(“”Enter the age:”);
scanf(“%d”,&first.age);
printf(“Enter the CGPA:”);
scanf(“%f”,&first.cgpa);
printf(“ID number=%ld\n”,first.id_no);
printf(“Name=%s\n”,first.name);
printf(“Age=%d\n”,first.age);
printf(“CGPA=%.ef\n”,first.cgpa);
}
Operations on structures
Only one operation , assignment is allowed on the structure itself. That is, a structure can only be copied
to another structure of the same type using the assignment operator.
Example 9.8:
STUDENT x={11000025,”xxx”,16,9.1};
y={11000047,”yyy”,16,9.3};
Before
We can create the array of structures like array of integers. For example, to store the data of a group of
students, we can use an array of structures. By putting the data in an array,we can quickly and easily work
with the data.
Example 9.9
struct stinfo
{
int rno;
float height;
float weight;
};
strut stinfo stary[10];
stary[0].rno, stary[1].rno, stary[2].rno etc will refer the roll numbers of first, second and third students.
Write a program to read roll number, name and marks in three subjects of n students and find the total
marks of each student. Display all the above student details sorted by total marks.
typedef struct
{
int rno;
char name[20];
float marks1,marks2,marks3;
float total;
}STUDENT;
#include<stdio.h>
void main()
{
STUDENT stary[10],temp;
int i,n,p;
printf(“Enter the number of students:”);
scanf(“%d”,&n);
for(i=0;i<n;++i)
{
printf(“Enter the roll number:”);
scanf(“%d”,&stary[i].rno);
flushall();
printf(“Enter the name:”);
gets(stary[i].name);
printf(“Enter the marks in 3 subjects:”);
scanf(“%f%f%f”,&star[i].marks1,&stary[i].marks2,&stary[i].marks3”);
}
/* To find the total marks of each students */
for(i=0;i<n;++i)
stary[i].total=stary[i].marks1+stary[i].marks2+stary[i].marks3;
/*To sort the student details on total marks */
for(p=1;p<n;++p)
for(i=0;i<n-p;++i)
if(stary[i].total<stary[i+1].total)
{
temp=stary[i];
stray[i]=stary[i+1];
stary[i+1]=temp;
}
Structures can have one or more arrays as members. We have already used arrays of characters inside a
structure. Similarly we can use one-dimensional or multidimensional arrays of type int or float
Example 9.10:
struct strecord
{
int rno;
float sub[6];
float total;
}stary[10];
In the above structure definition sub[6] is a field of the structure strecord.
The elements of the array sub[6] can be accessed using appropriate subscripts.
stary[0].sub[0], stary[0].sub[1], stary[0].sub[1], stary[0].sub[2] would refer to the marks of first student in
first, second ,third subjects.
Id.Number;
marks in six subjects;
total marks.
typedef struct
{
long int id_no;
float sub[6];
float total;
}STUDENT;
#include<stdio.h>
void main()
{
STUDENT stary[10];
int i,n;
i=0;
while(1)
{
printf(“Enter the Id.Number at the end enter 0:”);
scanf(“%ld”,&stary[i].id_no);
if(stary[i].id_no ==0)
{
n=i;
break;
}
printf(“Enter the marks in six subjects:”);
for(j=0;j<6;++j)
scanf(“%f”,&stary[i].sub[j]);
++i;
}
/* To find the total marks of each student */
for(i=0;i<n;++i)
{
stary[i].total=0;
for(j=0;j<6;++j)
stary[i].total=stary[i].total+stary[i].sub[j];
}
printf(“ID-NUMBER \t SUB1 \t SUB2 \t SUB3 \t SUB4 \t SUB5 \t SUB6 \t TOTAL\n”);
for(i=0;i<n;++i)
{
printf(“%ld\t”,stary[i].id_no);
for(j=0;j<6;++j)
printf(“%6.2f \t”,stary[i].sub[j]);
printf(“%6.2f\n”,stary[i].total);
}
}//end of main
Marks in the six subjects are stored in a one dimensional array sub[6] . Marks of the (i+1) th student in
(j+1)th subject is referred by stary[i].sub[j]
The following loop is used to read the marks ith student and store in the array sub[6]
for(j=0;j<6;++j)
scanf(“%f”,stary[i].sub[j]);
Structure member can be another structure. When a structure includes another structure, it is a nested
structure. For example, we can have a structure called birth that stores the date and time of birth of a
baby. The DATE is a member structure that stores the day, month and year. The TIME is another member
structure that stores the hour, minute and second . The structure design is shown below.
Although it is possible to declare a nested structure with one declaration it is not recommended. But it
will be more clear and easier if each structure is declared separately and then grouped in the higher level
structure
The nesting must be done from the lowest level to the most inclusive level.
Example9.11:
typedef struct
{
int day;
int month;
int year;
}DATE;
typedef struct
{
int hour;
int min;
int sec;
}TIME;
typedef struct
{
DATE dob;
TIME tob;
}BIRTH;
BIRTH baby;
There is no limit to the number of structures that can be nested, normally we do not go beyond three
The complete set of references for the structure baby are given below:
Initialization procedure for nested structure is same as the simple structure initialization. Each lower
level structure member values are enclosed in as set of braces. Definition and initialization for the
structure variable baby are shown below.
BIRTH baby={{05,06,2012},{15,30,20}};
First inner pair of braces contains values for day, month and year, and second inner pair of braces
contains the values for hour, minute and second.
Program 9.6: Program to read the roll number and date births of a list of students and display the output
sorted on date of birth.
typedef struct
{
int day;
int month;
int year;
}DATE;
typedef struct
{
int rno;
DATE dob;
}STUDENT;
#include<stdio.h>
void main()
{
STUDENT x[10],temp;
int i,n,p;
i=0;
while(1)
{
printf(“Enter the roll number, at the end enter 0:”);
scanf(“%d”,&x[i].rno);
if(x[i].rno==0)
{
n=i;
break;
}
printf(“Enter the date of birth in the format dd-mm-yy:\n”);
scanf(“%d-%d-%d”,&x[i].dob.day,&x[i].dob.month,&x[i].dob.year);
}
for(p=1;p<n;++p)
{
for(i=0;i<n-p;++i)
if(x[i].dob.year<x[i+1].dob.year)
{
temp=x[i];
x[i]=x[i+1];
x[i+1]=temp;
}
else if(x[i].dob.year==x[i+1].dob.year)
{
if(x[i].dob.month<x[i+1].dob.month)
{
temp=x[i];
x[i]=x[i+1];
x[i+1]=temp;
}
else if(x[i].dob.month==x[i+1].dob.month)
{
if(x[i].dob.day<x[i+1].dob.day)
{
temp=x[i];
x[i]=x[i+1];
x[i+1]=temp;
}
}
}
}//end of outer for loop
for(i=0;i<n;++i)
printf(“%d\t\t%d-%d-%d\n”,x[i].rno,x[i].dob.day,x[i].dob.month,x[i].dob.year);
}
After sorting the student records are arranged in the order of youngest to oldest.
C supports the passing of structure members and structures to functions and return them. A function can
accesses the members of a structure in three ways:
1. Individual members of a structure can be passed through arguments in the function call and they
are treated as ordinary variables in the called function.
2. The second method is a copy of the whole structure can be passed, that is the structure can be
passed by value. Any changes to structure members within the function are not reflected in the
original structure. Therefore it is necessary to return the whole structure back to the calling
function.
3. The third method is to pass the address of a structure or member and the function can accesses
the members through indirection operator.
The following program will demonstrate the passing of structure members to a function.
typedef struct
{
float real;
float imaginary;
}COMPLEX;
#include<stdio.h>
#include<math.h>
float find_modulus(float x, float y);
void main()
{
COMPLEX z;
float modulus;
printf(“Enter the real and imaginary parts of the complex number:”);
scanf(“%f%f”,&z.real,&z.imaginary);
modulus=find_modulus(z.real,z.imaginary);
printf(“Modulus of given complex number = %f\n”,modulus);
}
float find_modulus(float x,float y)
{
return(sqrt(x*x+y*y));
}
In the above program the structure members z.real and z.imaginary are passed to the function
find_modulus through arguments. They are copied to the dummy arguments x and y.
The following program demonstrate the passing of structures by value and the function returning a
structure.
Program 9.8: Program to find the product of two given complex numbers, using a function which will
find the product
typedef struct
{
float real;
float imaginary;
}COMPLEX;
#include<stdio.h>
void main()
{
COMPLEX z1,z2z3;
printf(“Enter the real and imaginary parts of the first complex number:”);
scanf(“%f%f”,&z1.real,&z1.imaginary);
printf(“Enter the real and imaginary parts of the second complex number:”);
scanf(“%f%f”,&z2.real,&z2.imaginary);
z3=product(z1,z2);
printf(“Product=(%.2f,%.2f)\n”,z3.real,z3.imaginary);
}
COMPLEX product(COMPLEX z1,COMPLEX z2)
{
COMPLEX z3;
z3.real=z1.real*z2.real-z1.imaginary*z2.imaginary;
z3.imaginay=z1.real*z2.imaginay+z1.imaginary*z2.real;
Structure can be passed through pointers. When the structure is in dynamic memory, it is common to pass
structure through pointer. now let us rewrite Program9.8 by passing structures through pointers
Program 9.9: Passing structures through pointers.
#include<stdio.h>
typedef struct
{ float real;
float imaginary;
}COMPLEX;
void main()
{
COMPLEX z1,z2,z3;
printf(“Enter the real and imaginary parts of first complex number:”);
read_num(&z1);
printf(“Enter the real and imaginary parts of second complex number:”);
read_num(&z2);
product(&z1,&z2,&z3);
print_num(&z3);
}
void read_num(COMPLEX*pz)
{
scanf(“%f%f”,&pz real,&pz imaginary);
return;
}
void product(COMPLEX *pz1,COMPLEX *pz2,COMPLEX *pz3)
{
pz3 real=pz1 real*pz2 real-pz1 imaginary*pz2 imaginary;
pz3 imaginary=pz1 real*pz2 imaginary+pz2 imaginary*pz2 real;
return;
}
void print_num(COMPLEX *pz)
{
printf(“Product=(%f,%f)\n”,pz real,pz imaginary);
return;
}
1. The function read_num() is written to read the complex number. The pointers to the structure
variables z1and z2 are passed in the first and second calls of the function.
2. In the header of the function read_num() the dummy argument pz is a pointer to the structure.
3. Pointers to the structure variables z1,z2 andz3 are passed to the function product which will return
the pointer to the product of the two complex numbers z3.
The operator sizeof can be used to find the size of a defined structure data type . The expression
sizeof(struct ex)
will evaluate the number of bytes required to hold all the structure members.
sizeof(a)
9.8 UNIONS
The union is a user defined data type that allows the memory to be shared by different types of data. The
union follows same syntax as the structure .Except the keywords struct and union, the formats are the
same but there is a major difference in the storage. In structure, each member has its own storage
location, where as all the members of a union share a common memory location.
Even though union contain many members in the program only one member is available at a time. The
general syntax of union declaration is
Example 9.12:
union student_id
{
int rno;
long int id_number;
}x;
Both rno and id_number start at the same memory address
rno/id_number
student_id
rno/id_number
Union may be initialized only with a value of the same type as the first union member. Other members
can be initialized either assigning values or reading from the keyboard.
Example 9.13:
union student_id
{
int rno;
long int id_number;
};
union student_id x={35};
printf(“rno=%d\n”,x.rno);
printf(“id_number=%ld\n”,x.id_number);
The output of the above program segment is
rno=35
id_number=0
Example 9.14:
union ex
{
int a ;
float b;
};
union ex x={19.75};
is invalid declaration . Because the type of first member is int , but x is initialized with float value.
When a union is defined, enough space is allocated to store the largest data type member in the definition.
In the above example the size of rno is 2 bytes and the size of id_number is 4 bytes. Therefore 4 bytes of
space is allocated regardless of what type of data is being stored.
Storage of 4 bytes
2146 2147 2148 2149
rno
id_number
During the accessing of union members we should make sure that we can access the member whose
value is currently stored.
x.rno=50;
x.id_number=11000132;
printf(“%d”,x.rno);
would produce erroneous output(which is machine dependent)
The enumerated type is a user defined data type based on the standard integer type. In an enumerated
type, each integer is given an identifier called an enumerated constant. We can thus use the enumerated
constants as symbolic names, which make our programs more readable.
Where enum is a keyword, typename is the name given to the enumerated type and identifier 1,
identifier2, ... are a set of enumerated. constants enclosed in a pair of braces.
Enumeration identifiers are assigned integer values beginning with 0. That is , the identifier 1 is assigned
0, identifier 2 is assigned 1 and so on.
Example 9.15:
The enumerated type color has five possible values. The range of values BLUE representing the value
0,GREEN representing the value 1, ORANGE the value 2, PURPLE the value 3 and RED the value 4.
The automatic assignments can be overridden by assigning values explicitly to the enumeration
constant.
Example 9.16:
Here the identifier BLUE is assigned the value 1. The remaining identifiers are assigned values that
increase successively by 1.
The explicit assignment can be made to any one of the identifier in the list
Example 9.17:
Here the identifier ORANGE is assigned the value 3. The remaining identifiers are assigned values that
increase successively by 1 in the forward direction and decrease successively by 1 in the backward
direction.
The enumerated variables can have one of the values identifier 1,identifier 2, … identifier n;
Example 9.18:
Foreground=GREEN;
Background=RED;
The value of one enumerated variable can be assigned to another enumerated variable.
foreground=background;
Enumerated types can be compared using the relational operators. Given two variables of enum type
color, they can be compared for equal, lesser than, greater than, not equal to. We can also compare
them to enumeration identifiers as shown follow:
if (foreground==background)
…..
if (foreground==ORANGE)
.....
Since enumerated types are derived from integer types they can be used in switch statement.
Example 9.19:
enum day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY};
enum day birthday;
switch (birthday)
{
case MONDAY: printf(“The birthday is on MONDAY”);
break;
case TUESDAY: printf(“The birthday is on TUESDAY”);
break;
---
}
Enumerated variable can be used as index of for loop.
for (birthday=MONDAY; birthday<=SUNDAY; ++birthday)
Input/output Operations:
Since enumerated types are derived data types they cannot be read and written using the formatted
input/output functions. An enumerated type must be read as an integer and written as an integer.
scanf(“%d%d”,&holiday,&birthday”);
12
The output is
1 2
SUMMARY
Structure is used to pack a collection of logically related data items, possibly of different data types,
having a common name.
Each element of a structure is called a field or member.
One difference between array and structure is that all elements of the array must be of same data type
while the elements in a structure can be same or different data types.
Unlike arrays, structure data type must be defined first that will be used later for declaring structure
variables.
Structure members cannot be initialized in the structure data type definition
Structure variables can be initialized in the declaration. The rule for initialization is the same as that for
array initialization.
Structure members can be accessed using the dot(.) operator.
Structure members can also be accessed through structure pointer. For this the arrow ( ) operator is
used.
Structure members can be used in expressions like ordinary variable names or array elements.
The only operator allowed on entire structure is assignment.
The individual members or the whole structure or the pointer to the structure can be passed to a
function through arguments and a function can return a structure.
An array of structures can be declared and structure members can be arrays.
One structure can be embedded in another structure .This is called nesting of structure
A union is a structure all of whose members share the same storage.
A union can store only one of its members at a time.
An enumerated data type is a user defined data type to improve the readability of the program. It is built
on the integer data type.
An enumerated data type consists of collection of enumeration constants which are represented by
identifiers. Each identifier is given an integer value.
EXERCISES
Review Questions
int i;
float f;
} x;
void main()
x.i=10;
x.f=14.5;
printf(“i=%d; f=%f\n”,x.i,x.f);
a) i=10, f=14.500000 b) error in the program as the structure members cannot be initialized through
assignment statement c) 10, 14.50000
2. What is the output when the following program is executed?
(Assume that the program is run on a 16 bit machine)
#include<stdio.h>
main()
struct ex;
int a;
float b;
char ch;
LEARNING OBJECTIVES
After reading this chapter the reader will be able to
understand the need of data file.
learn the operations on files.
use different data input/output functions on files.
write simple programs for creating a data file, reading data from the file for processing and
display.
10.1 INTRODUCTION
What is a file?
With any C program there are two major operations between the user and the program which are
How to send data (input)into the program and
How to get results data (output) from the program
So far we have done these two operation using the following input/output functions
scanf( ) printf( )
Input functions Output functions
getchar( ) putchar( )
gets( ) puts( )
…….. ……..
…… ……
For example the following program reads input data and prints the out data
5 7 10 11 13 #include<stdio.h> x=5
14 void main( )
{ FILE fp1, fp2;
int x;
Input fp1=fopen(“INPUT.DAT”, “r”);
fp2=fopen(“RESULT.DAT”, Output
(Through (To the file)
“w”);
file)
f scanf(fp1, “%d”, &x );
fprintf(fp2, “\n x=%d”, x);
}
where
fscanf( ) – is file input function used to read data from the file to the program
fprintf( ) – is file output function used to write data to the file from the
program
STUDENT.IN
RNO NAME SUB1 SUB2 SUB3
10 Ramu 18 15 16
11 Gopi 20 18 15
Example 10.2: Student data output with the file name “OUTPUT.DAT”
OUTPUT.DAT
RNO NAME SUB1 SUB2 SUB3 TOTAL AVG
10 Ramu 18 15 16 410 16.33
11 Gopi 20 18 15 53 17.67
where
fp – is a file pointer which is of structure data type FILE declared in stdio.h
The general syntax to declare the file pointer is
FILE *file-pointer;
For example,
FILE *p1, *p2, *fp;
“filename” – is the name of the file and is a string of characters that make up a valid filename for the
operating system. It may contain two parts, a primary name and an optional period with the extension.
For example,
“input.data”
“STUDENT.DAT”
“RESULTS.OUT”
“mode” – specifies the purpose of opening the file. The mode of the file may be one of the following
“w” -- open a new file for writing data
“r” -- open an existing file for reading data
“a” -- open an existing file for appending data to it
“r+” -- open an existing file for both readingandwritingdata
“w+” -- same as “w” except both for reading and writing
“a+” -- same as “a” except both for reading and appending
#include<stdio.h> fp STUDENT.IN
void main( )
{
FILE *fp;
fp = fopen( “STUDENT.IN”, “w” );
……………………
……………………
}
A new file with the name “STUDENT.IN” is created. If the file already exists, contents of the file are
deleted.
Example10.4: Open an existing file “STUDENT.IN” for data reading
#include<stdio.h>
void main( ) STUDENT.IN
{ fp
FILE *fp;
fp = fopen( “STUDENT.IN” , “r” );
………………
……………………
}
An existing file with the name “STUDENT.IN” is opened for reading data. If the file does not exist an
error will occur.
Example10.5: open the file “STUDENT.IN” for appending data
#include<stdio.h> fp STUDENT.IN
void main( )
{
FILE *fp;
fp = fopen( “STUDENT.IN” , “a” );
……………………
……………………
}
An existing file with the name “STUDENT.IN” is opened for appending data to it .If the file does not
exist a new file with the name “STUDENT.IN” is opened.
fclose( ) is the counterpart of fopen( ). Closing file means delinking the file from the program and saving
the contents of the file. Its general form is
fclose(fp);
This would close the file associated with the file pointer fp.
#include<stdio.h>
void main( )
{
In the above example two files are opened and will be closed after all operations on them have been
completed. Once a file is closed its file pointer can be used to open another file.
INPUT.DAT RESULT.DAT
5 7 10 11 13 14 Example1.c x=5
#include<stdio.h>
Input void main( ) Output
(Through file) { (To the file)
fgetc(), fgets(), fscanf() ………………. fputc(), fputs(), fprintf()
……………….
……………….
Input data ……………….
Output data
(Through keyboard) (On the screen)
}
getchar(), gets(), scanf() Putchar(), puts(), printf()
After a file is opened, we can read data stored in the file or write new data to it depending on the mode of
opening. C standard library supports a good number of functions which can be used for performing I/O
operations. File I/O functions are broadly classified into two types.
1. High level file I/O functions
2. Low level file I/O functions
Where the character/char-variable represents a character and fp is a pointer to the FILE. The function
writes the character or content of char-variable to the file pointed by fp.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen(“TEXT.DAT”,”w”);
if(fp==NULL)
{
printf(“file is not opened\n”);
exit(0);
}
while((ch=getchar())!=EOF)
fputc(ch,fp);
fclose(fp);
}
Text is read character by character from the keyboard and is written to the file. The end of the text is
indicated by entering an EOF character, which is control-Z in the DOS environment.(this may be control-
D on other environments).After the EOF is encountered the file is closed.
fgetc( ) : This function is used to read a single character from a file. Its general form is
Program10.2: A file named TEXT.DAT is on the disk. Program to read the text from the file and
display the text on the monitor after converting to upper case.
Program10.3:A file named INTEXT contains a text .Program to copy the text from this file to the file
OUTTEXT.
#include<stdio.h>
void main()
{
File *fp1,*fp2;
char ch;
if((fp1=fopen(“INTEXT”,”r”))==NULLl)
{
prinf(“Unable to open the file INTEXT\n”);
exit(0);
}
if((fp2=fopen(“OUTEXT”,”w”))==NULL)
{
printf(“Unable to open the file OUTTEXT\n”);
exit(1);
}
while((ch=fgetc(fp1))!=EOF)
fputc(ch,fp2);
fclose(fp1);
fclose(fp2);
}
Program10.4: Program to count the number of words in a text stored in a file. Words are separated by
one or more whitespace charactersthat is ,by a space, a tab or a new line.
#include<stdio.h>
void main()
{
FILe *fp;
fputs(
Where the string/string-variable string/string-variable,
represents fp);fp is a pointer to FILE. The function
a string constant and
writes the string or content of string-variable to the file pointed by fp. Also, fputs() does not add a new
line to the end of the string. It must be included explicitly.
Program10.6: Program to create a file for writing strings to it using fputs( )
#include<stdio.h>
void main( )
{ DATA.IN
FILE *fp;
char str[] = “NEW” ;
fp = fopen(“DATA.IN” , “w” );
fputs(str , fp);
fputc(“\n”,fp); NEW
fputs(“OLD” , fp);
fputc(“\n”,fp); OLD
fputs(“OLD OLD”, fp);
fputc(“\n”,fp);
OLD OLD
fclose(fp);
}
The function fputs() writes the content of string variable str first and then the strings “OLD” and “OLD
OLD” to the file
fgets( ) : This function is used to read a string from a file. Its general form is
fgets(string-variable , n, fp);
The function reads a string of n-1 characters from the file pointed by fp and returns the string value,
which is collected by the string-variable.
It will stop reading when any one of the following conditions is satisfied
It has read(n-1)characters
It encounters a new line character
It reaches the end of file
A read error occurs
fprintf( ) :The function is used to write multiple data items which may (or may not) be of different
types to a file. Its general form is.
#include<stdio.h>
void main( )
{
FILE *fp;
char name[30] = “RAMU”; STUDENT.IN
The contents of rollno, name and total_marks are written to the file pointed by fp.
fscanf( ) :- This function is used to read multiple data items which may be of different types from a
file. Its general form is
Program 10.9: Program To read student data from the file ”STUDENT.IN” using fscanf()
#include<stdio.h>
void main( )
STUDENT.IN {
FILE *fp;
25 RAMU 450 char name[30];
int rollno;
float total_mark ;
fp = fopen(“STUDENT.IN” , “r” );
fscanf( fp,“%d%s%f”, &rollno,name,&total_marks);
fclose(fp);
}
The data values from the file “STUDENT.IN” are read and the values are collected by rollno, name and
total_marks respectively.
Program10.10: Program to read integers through key board and write to the file “DATA”. Later read the
integers from the file “DATA”, and write even numbers to the file “EVEN” and odd numbers to the file
“ODD”. Read data from the files “EVEN”, “ODD” and display on the screen
Program10.11: Program to read inventory data; item, number, price and quantity for three items and
writes the data to the file. Later read the data from the file and display on the screen with total value.
#include<stdio.h>
struct emp
{
int empno;
char name[30];
float salary;
}
void main( )
{
int n,i;
FILE *fp;
struct emp e;
fp = fopen(“EMP.DAT”, “w”);
printf(“\nEnter number of employees:”);
scanf(“%d”, &n);
printf(“\n Enter empno, name and sal for %d number of employees:\n”, n);
for(i=0; i<n; ++i)
{
scanf(“%d%[^\n]%f”, &e.empno, e.name, &e.salary);
fprintf(fp, “\n%d\t%s\n%f”, e.empno, e.name, e.salary);
}
fclose(fp);
fp=fopen(“EMP.DAT”, “r”);
printf(“\nContents of the file EMP.DAT”);
while(!feof(fp))
{
fscanf(fp, “%d%[^\n]%f”, &e.empno, e.name, &e.salary);
printf(“\n%d\t%s\t%f”, e.empno, e.name, e.salary);
}
fclose(fp);
}
SUMMARY
Real life situations involve large volume of data and in such cases the console oriented I/O operations
pose two major problems. It becomes cumbersome and time consuming to handle large volumes of data
through terminals. The entire data is lost when either the program is terminated or computer is turned off.
Therefore, it is necessary to have more flexible approach where data can be stored on the disks and read
whenever necessary, without destroying the data. This method employs the concept of files to store data.
The concept of files enables us to store large amount of data permanently on the secondary storage
devices. A defined data type FILE is used to represent a file within program. It acts as an internal file
name for a file. Before performing any operation over a file, it has to be opened. The purpose of the
opened file may be for writing data or reading data or may be for appending data to the file. Once the
intended operation is over the file has to be closed. The file input/output operations are by using the
functions fgetc( ), fputc( ) which are the character oriented file I/O functions, fgets( ),fputs( ) are the
string oriented functions and fscanf( ) and fprintf() are the mixed data oriented functions.