Professional Documents
Culture Documents
THROUGH
PROGRAMMING
DEPARTMENT OF MATHEMATICS
K L UNIVERSITY
PROBLEM SOLVING
THROUGH
PROGRAMMING
The objective of this book is only for preliminary guidance for entrance
from intermediate education to technical education to get complete understanding
and acquiring the required skill in problem solving through C. Students will
undergo the suggested reading mentioned at the end of each chapter.
CONTENTS
Page
S.No Name of the Topic
No
1 PROBLEM SOLVING 1
1.1 Introduction 1
1.2 Problem solving techniques 2
1.2.1 Problem definition phase 2
1.2.2 Getting started on a problem 2
1.2.3 The use of specific examples 2
1.2.4 Similarities among problems 3
1.2.5 Working backwards from the solution 3
1.3 Using computer as a problem-solving toll 3
1.4 Design of algorithms 3
1.4.1 Definition 3
1.4.2 Features of Algorithm 3
1.4.3 Criteria to be followed by an algorithm 4
1.4.4 Top down Design 7
1.5 Flow charts 8
1.5.1 Flowchart Symbols 8
1.5.2 Significance of flowchart 8
1.5.3 Guidelines for drawing a flowchart 9
1.5.4 Advantages of using Flowcharts 17
1.5.5 Limitations of using Flowcharts 17
1.6 Language 17
1.7 Program and a programming language 17
1.7.1 Machine level Language 17
1.7.2 Assembly language 18
1.7.3 High level language 18
Summary 18
Multiple choice questions 19
Comprehensive questions 19
2 BASICS OF C 20
2.1 Overview of C 20
2.1.1 History of C 20
2.1.2 Features of C 20
2.2 Structure of C Program 21
2.2.1 A sample C Program 21
2.2.2 Compiling a C Program 22
2.2.3 Link and Run the C Program 22
2.3 Character set, identifiers, keywords and variables 22
2.3.1 Character set 22
2.3.2 Identifiers 23
2.3.3 Key words 23
2.4 Constants 23
2.4.1 Integer constants 24
2.4.2 Real constants 25
2.4.3 Character constants 26
2.4.4 Backslash character constants 27
2.5 Data Types 27
2.5.1 Integer data type 28
2.5.2 Floating point data type 28
2.5.3 Character data type 29
2.5.4 Void data type 29
2.5.5 Complex data type 29
2.5.6 Boolean data type 29
2.5.7 Pointer data type 30
2.6 Declaration of variables 30
2.7 Assigning values to the variables 30
2.8 Input function- scanf() 32
2.9 Output function - printf() 32
2.10 Operators and Expressions 35
2.10.1 Arithmetic Operators 36
2.10.2 Relational Operators 36
2.10.3 Logical Operators 37
2.10.4 Increment and Decrement Operator 38
2.10.5 Assignment Operator 40
2.10.6 Conditional Operator 41
2.10.7 Special Operators 42
2.11 Operator Precedence and Associativity 43
2.12 Type conversion 44
Summary 45
Multiple choice questions 45
Comprehensive questions 51
3 CONTROL STATEMENTS
3.1 Introduction 53
3.2 Simple & Compound Statements 54
3.2.1 Simple statements 54
3.2.2 Compound statements 54
3.3 Null & Expression Statements 55
3.3.1 Null statements 55
3.3.2 Expression statements 55
3.4 Decision making & Branching (Selection) 55
3.4.1 if-statement 55
3.4.1.1 The simple if-statement 55
3.4.1.2 The if-else statement 56
3.4.1.3 The nested if-else statement 58
3.4.1.4 The else-if ladder 59
3.4.2 The switch statement 60
3.5 Looping or Iteration Statements 62
3.5.1 The while loop 62
3.5.2 The for loop 63
3.5.3 The do-while loop 68
3.6 Nested Control Structures 68
3.7 Jump Statements 68
3.7.1 The goto statement 69
3.7.2 The break statement 70
3.7.3 The continue statement 70
Summary 71
Multiple choice questions 72
Comprehensive questions 84
4 ARRAYS
4.1 Introduction 89
4.2 Array declaration 90
4.2.1 Declaration of one dimensional arrays 90
4.3 Subscript 91
4.4 Storage of one-dimensional arrays in memory 91
4.5 Initialization of array 92
4.5.1 Compile time initialization 92
4.5.2 Run time initialization 93
4.6 Two-dimensional arrays 99
4.7 Initialization of two-dimensional array 100
Summary 107
Multiple choice questions 107
Comprehensive questions 111
5 FUNCTIONS
5.1 Introduction 112
5.2 Structure of a function 113
5.3 Calling a Function 115
5.3.1 Calling function with no return value 116
5.3.2 Calling function with a return value 117
5.3.3 Calling a function with arguments 117
5.4 Function Prototypes 120
5.5 Categories of Functions 122
5.5.1 Functions with arguments and return value 122
5.5.2 Functions with arguments and no return value 123
5.5.3 Functions with no arguments and return value 123
5.5.4 Functions with no arguments and no return value 124
5.6 Passing Arrays to functions 125
5.6.1 Functions with one dimensional arrays 125
5.6.2 Functions with two dimensional arrays 126
5.7 Built-In Functions 129
5.8 Recursion 131
5.9 Global & Local Variables 131
5.9.1 Global & Local Variables 132
5.10 Storage Classes 134
5.10.1 Automatic Variables 134
5.10.2 External variables 136
5.10.3 Static variables 137
5.9.2.3 Register variables 138
Summary 139
Multiple choice questions 141
Comprehensive questions 145
10 FILE PROCESSING
10.1 Introduction 241
10.2 File operations 243
10.2.1 Creating a new file / Opening an existing file 243
10.2.2 Closing a file 244
10.3 File Input/ Output functions 245
10.3.1 Character data oriented functions 246
10.3.2 String data oriented functions 249
10.3.3 Mixed data oriented functions 250
10.4 Programs using files 251
Summary 253
Review questions 254
Comprehensive questions 254
Chapter 1
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 ones 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 cant 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 step of instructions that perform a particular task and it must satisfy the
following features.
1.4.2 Features of Algorithm
Following features should be present in an algorithm:
Proper understanding of the problem
Problem solving 3
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: Algorithm must terminater after no.of steps.
V) Effectiveness: Every Instruction must be very basic.
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
Algorithm:
Step1: Read two numbers a and b
Problem solving 4
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.
Expected Output:
Factorial of the integer
Problem solving 5
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
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
READ P,T,R
SI=P*T*R/100
start
PRINT SI
Sum=0
STOP N=0
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
Accvept a,b
Sum=a+b
STOP
Problem solving 13
Example1.17: Design a flow chart on Addition of Two Numbers
START
Accvept a,b
Sum=a+b
STOP
START
READ a,b
Is a>b
PRINT a
PRINT a
STOP
Problem solving 14
Example1.19:Design a flowchart on Natural Numbers between 1 to N Reverse Order.
START
Example1.20: Draw a flowchart to display
the given number is prime or not
START
READ N
READ N
Is N>0
STOP
K=N
I=2; FLAG=1
PRINT N
R=remainder of(N/I)
N=N-1
IS
R=0
I=I+1 FLAG=0
IS I<=K
IS
FLAG=
0
PRINT PRIME
PRINT NOT PRIME
Problem solving 15
Example1.21: Draw a flowchart to generate first n elements of Fibonacci series.
START
READ N
FIB1=1
FIB2=1
COUNT=2
FIB3=FIB1=+FIB2 Yes
No
PRINT FIB3
COUNT=COUNT+1
IS COUNT<N
FIB1=FIB2 STOP
FIB2=FIB3
Problem solving 16
1.5.4 Advantages of using Flowcharts
As we discussed flow chart is used for representing algorithm in pictorial form. This pictorial
representation of a solution/system is having many advantages. These advantages are as follows:
1.6 LANGUAGE
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 users form to
computers form. Like other language, a computer language also follows a particular grammar known as
the syntax.
Problem solving 17
1.7.2 Assembly language
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
process by rectangle and input/ output by parallelograms . . Lines and arrows connect
these blocks. A program is sequence of instructions and the process of writing program is called
programming. Programming languages can be divided into three categories: machine language,
assembly language and high level language. High level languages are easy to use while machine and
assembly languages are complex. Therefore, writing programs in machine and assembly languages is
difficult and time consuming.
Problem solving 18
EXERCISES
a) machine language b) assembly language c) high level language d) fourth generation language
ANSWERS
Problem solving 19
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 languages. We will briefly outline these
issues in the following section.
2.1.1 History of C
C is a programming language developed at AT&Ts bell laboratories of USA in 1972. It was
designed and written by a man named DENNIS RITCHIE. In the late seventies c began to replace the
more familiar languages of that time like PL\I(Programming Language One", pronounced "pee-el-one"),
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 called BCPL(Basic Combined Programming Language). But
unfortunately it turned out to be much less powerful and too specific. Ken Thompson at AT & Ts 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(High
Level and Low level), C lies in between these two categories. Thats 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 20
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 c programs 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 () represent fun2()
user defined functions. {
------
}
Fig1.1.structure of a C program
2.2.1 A sample C program
From the above section you have become familiar with a programming language and structure of a
program .It is now time to write a simple C program .The program will illustrate how to print out the
message This is a C program.
Program 2.1: write a program to print to a message on the screen
Basics of C 21
main() declares the start of the function while the two curly{ } shows the start and finish of the
function. Curly brackets in C are used to group statements together as a function or in the body of a 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.
Basics of C 22
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:
A constant is the value to be stored in a memory location whereas the variable is a name given
to a memory location.
The value of a constant does not change whereas the value of a variable can change during the
execution of a program. For example in the statement X=17; as the value of 17 cannot change it is
a constant whereas the quantity X can vary or change. Hence it is called variable.
Basics of C 23
A constant cannot have a direct memory location whereas a variable can have.
C language supports several types of constants as illustrated below:
Constants
Numeric
Integer Real
Fractional
form
Decimal Octal Hexadecimal
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 24
Valid examples Invalid examples(with reasons)
0143 12244(0 should precede the number)
0175 03.43(dot is not allowed)
015 $143(special symbol is not allowed)
00 08943(invalid digits 8 and 9)
0154 01,43(comma is not allowed)
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
Basics of C 25
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 26
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
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 27
ii) Derived data types
iii) User defined 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
Basics of C 28
giving a precision of 15 significant digits .To extend the precision we may use long double which uses 80
bits.
Size and range values of floating data types on 16 bit machine.
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 29
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.
Basics of C 30
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 31
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 .
2.8 INPUT FUNCTION- scanf()
We can assign values to variable through assignment statements such as x = 5 a = 0 ; and so on.
Another method is to use scanf() function which can be used to read data from a key board. It is the
general input function available in C Language. The general format of scanf() is as follows:
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 names 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.9 OUTPUT 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.
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.
Basics of C 32
Program2.5
main() Output:
{ Hello!
The control string contains format of the data to be displayed and exp1,exp2,exp3are 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() a x ch
{ int a; 65.8
56 y
float x;
char ch; Output:
printf(Enter value of a);
Enter value of a
56
scanf(%d,&a); Enter value of x
printf(Enter value of x); 65.8
scanf(%f,&x); Enter any character
y
printf(Enter any character );
a is 56
scanf(%c,&ch); x is 65.800000
printf( \n a is %d,a); ch is y
printf(\n x is %f,x);
Basics of C 33
printf(\n ch is %c,ch);
}
Basics of C 34
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 35
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 36
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
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);
Basics of C 37
else
printf( The values of a,b,c dont 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 dont form an isosceles triangle);
Consider the expression exp1||exp2. If exp1 is true then exp2 is not evaluated.
Example2.31: int i=6,j=3,k;
k=(i>5)||(j=i+3);
printf(k=%d j=%d\,n,k,j);
output: k=1 j=3
Example2.32: i=6,j=3,k;
k=(i<5)||(j=5+10);
printf(k=%d,j=%d,k,j)
output : k=1,j=13
Basics of C 38
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
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;
Basics of C 39
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.
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.
Basics of C 40
x+=expression x=x+expression
x-=expression x=x-expression
x*=expression x=x*expression
x/=expression x=x/expression
x%=expression x=x%expression
Basics of C 41
2.10.7 Special operators
The special operators are
i) comma operator(,)
ii) sizeof operator
iii) address operator(&),
iv) indirection operator(*)
v) cast operator
i) Comma operator
The comma operator is used to combine two more expressions into a single expression.
The general form is
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.
Example2.56: sizeof(13.56)
sizeof(239462l)
sizeof(896254ll)
sizeof(*)
sizeof(a+b)
iii) address operator
General form is
&operand
Basics of C 42
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 43
7 && L to R
8 || L to R
9 ?: R to L
10 =, +=, *=, -=, /=, %= R to L
11 , (comma operator) L to R
Example2.61: 2+3*4 is evaluated as 2+(3*4) and the result of the expression is 14
Example2.62: 3*8/4%5*2
Here we have four operators of the same precedence (* / % *). As the associativity of arithmetic operators
is left to right. The expression 3*8/4%5*2 is evaluated as
(((3*8)/4)%5)*2 and the result of the expression is 2.
Example2.63: a+=b*=c - =5
As the associativity of assignment operators is right to left, the above expression is evaluated as
(a +=(b*=(c - =5)))
Which is expanded to (a=a+(b=b*(c=c-5))).
Example2.64: -b++
Here postfix increment has higher precedence than unary -. Thus the above expression is evaluated as
(-(b++)).
If b is 6, then the result of the expression is -6. After the expression is complete 6 becomes 7.
Example2.65: int a =5,b=6,c;
c=a!=b;
The expression contains the assignment operator (=) and the relational operator (!=).As the relational
operator has higher precedence over assignment operator the expression a!=b is evaluated first and the
result 1 is assigned to c.
2.12 TYPE CONVERSION
There are two types of type conversions in expressions.
i) Implicit type conversion.
ii) Explicit type conversion.
i) Implicit type conversion
C permits mixing of constants and variables of different types. A data type that occupies less
memory will be converted automatically to a data type that occupies more memory space without losing
any information.
Example2.66: If one operand is int and the other is float, int is converted to float.
If one operand is double and the other is long double, double is converted to long double.
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
Basics of C 44
ii) Explicit type conversion
For explicit type conversion type casting is used.
The general form of a cast is:
(data type name) expression
Where data type name is one of the basic data types.
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 forms 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.
Suggested Reading:
EXERCISES
Basics of C 45
{
int x=10,y=15,a,b;
a=x++;
b=++y;
printf(%d , %d ,a,b);
}
a)10,16 b)11,15 c)11,16 d)10,15
2.4. Expression (x<5||a>b) is true
a) if x<5 b) if a>b c) if x<5 or a>b d) all the above
2.5. What value is assigned to k when the following statements are executed?
int i=8,j=20,k;
k=(++i , j-- , i*j);
int a=5,b=6,c;
c=(a+b>a-b)?a*b;a%b;
#include<stdio.h>
main()
{
int i=1;
for( ; ; )
{
printf(\n %d,++i);
if( i>5)
break;
}
}
a) 2 3 4 5 b) 1 2 3 4 5 c)2 3 4 5 6 d)1 2 3 4 5 6
2.10. What is the C expression for the following mathematical expression.
1<x20 or 3y1
a) 1<x <=20 || 1<=y<=3 b) 1<x <=20 && 1<=y<=3
c) (1<x && x<=20) || (3>=y && y>=1) d) any one of the above
2.11. What is the value assigned to k when the following statements are executed?
int k,a=5,b=3,c=10;
k=(a + = b *= c - = 6);
Basics of C 46
2.12. What is true about the following: a compound statement is
a) A set of simple statements
b) Demarcated on either side by curly bracket
c) Can be used in place of simple statement
d) All the above.
2.13. Which of the following represents true statement either x is in the range of 10 and 50 or
y is 0?
a) x>=10&&x<=50||y==0 b)x<50 c)y!=10 d)None of these
Basics of C 47
a) 60 b)66 c)61 d) none of the above
int x=20,y=16,z;
z=(x<y)&&(y+=2);
printf(y=%d,z=%d,y,z);
int x=20,y=16,z;
z=(x>y)&&(y+=2);
printf(y=%d,z=%d,y,z);
int x=20,y=16,z;
z=(x>y)||(y+=2);
printf(y=%d,z=%d,y,z);
a) 0 b)1 c) 5 d) 50
Basics of C 48
a = x = y = =z;
a) 5 b)3 c)4 d)0
Basics of C 49
#include<stdio.h>
main()
{
int a = 5, b = 0, c ;
c = a && b ++;
printf ( b = %d, c = %d \n, b, c);
}
#include<stdio.h>
main()
{
int a = 5, b = 6, c ;
c = a < b ? a : a > b ? b : -1;
printf ( c = %d \n, c );
}
a) -1 b)1 c)5 d)6
2.42. 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 = % .2 f , d = % . 2f \n, c, d );
}
#include<stdio.h>
main()
{
int x = 10;
printf( %d , %d, %d , x < = 20, x= 25, x >= 5);
}
a)20 ,25,5 b)1,25,1 c)0,25,1 d)10,25,1
2.44. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a = 3, b = 0, c;
c = ++a && ++b;
printf ( a = %d, b = % d, c= %d \n , a, b, c);
}
a)a=3,b=0,c=0 b)a=3,b=0,c=1 c)a=4,b=1,c=1 d)a=4,b=1,c=0
Basics of C 50
2.45. What is the output when the following program is executed?
#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=-3,j=2,k=0,m=1 b)i=-2,j=3,k=1,m=1
c)i=-2,j=3,k=1,m=0 d) i=-2,j=3,k=0,m=1
#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=5,b=5,c=6 b)a=7,b=6,c=6 c)a=5,b=6,c=7 d)a=5,b=6,c=6
2.47. What is the wrong assignment expression in the following?
float a,b,x=8.2,y=6.3;
ANSWERS:
2.1)C 2.2) b2.3) a 2.4) d 2.5) a2.6)d 2.7) b 2.8).a 2.9)c 2.10)c 2.11)a 2.12)d
2.13)a 2.14)a 2.15)a 2.16)b2.17)a 2.18)a 2.19)b2.20)c 2.21)b2.22)d2.23)a 2.24)a
2.25)b2.26)d2.27)d2.28)c 2.29)a 2.30)b2.31)c 2.32)d2.33)a 2.34)a 2.35)a 2.36)d
2.37)c 2.38)b2.39)a 2.40)d2.41)c 2.42)b2.43)c 2.44)c 2.45)d2.46)b2.47)a
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 printf(), 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.
Basics of C 51
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.
2.21 For a certain electrical circuit with an inductance L and resistance R and the capacitance C the
damped natural frequency is given by f = 1/LC-R2/4c2. Write a program to calculate the
frequency for the given values of L, R and C.
2.22 A Particle moves with simple harmonic motion in a straight line. In the first second starting from
rest , it travels a distance a and in the next second it travels a distance b in the same direction.
The amplitude of motion is 2a2/(3 a b). Write a program to calculate the amplitude of motion, for
the given values of a and b.
Basics of C 52
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 53
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(Enter an integers);
scanf(%d,&a);
if(a>max)
max=a;
}
Example3.3: if(flag==1)
{
printf();
scanf(%d,&b);
}
Control Statements 54
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.
;
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.
i) if-statement
ii) switch-statement
3.4.1 if-statements
Control Statements 55
False
condition
if(condition)
True
statement;
statement
Next
instruction
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 56
False True
Test-
Expression
if ( test-expression)
statement 1;
else True
statement 2; Statement2 Statement1
statement x;
Statements1
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 bis 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);
Control Statements 57
Input-Output:
scanf (%d,&year);
r4=year % 4; Enter a year
r100=year % 100;
r400=year % 400; 4000
if (( r4 == 0) && (r100!=0) || (r400 == 0)) 4000 is a leap year
printf (%d is a leap year ,year);
else Enter a year
printf (%d is not a leap year ,year);
} 2011
2011 is not a leap year
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 58
if(a>=b)
{
if(a>b)
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) TE-1
Statement-1;
else if (test-expression2)
Statement-2; True False
else if(test-expression3) TE-2
Statement-3; Statement-1
. False
else if (test-expression n)
Statement -n; TE-3
else Statement-2
Statement-n+1;
statement x True
Statement-3
Statement-x
Control Statements 59
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
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 and so on. If the value of expression matches with none of the case values
then default option will get executed.
Control Statements 60
switch ( expression) Expression
{
case value1:statement-1;
break;
case value2:statement -2; Case Value 1 Statement-1
break;
.
Case Value 2 Statement-2
.
case value n:statement -n;
break; Case Value 3 Statement-3
default :default statement;
break;
}
Case Value n Statement-n
Points to Remember:
Control Statements 61
case 5 : printf( Five); break;
case 6 : printf( Six); break;
case 7 : printf( seven); break;
case 8 : printf( Eight); break;
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.
Intialization
Expression
False
True
Statement
Example3.16: i=1;
sum =0;
while (i<=10)
Control Statements 62
{
sum+=i;
i++;
}
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:
Control Statements 63
expr1;
while (expr2)
{
statement;
expr3;
}
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
Expression 2 False
True
Statement
Expression 3
printf(%d\n,j);
Control Statements 64
{
int n,i;
float x,large;
printf ( Enter the number of values );
scanf(%d,&n);
printf(Enter the first number); 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 ten lines of the 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:\n,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;
}
This segment will find the sum of digits of a given integer. The loop is written without expression3.
#include<stdio.h>
void main()
{
int a,b,rem,temp1,temp2;
Control Statements 65
Input-output:
printf(Enter two integers);
scanf(%d%d,&a,&b); Enter two integers 36 24
temp1=a; temp2=b;
for(;(r=a%b)>0;) gcd(36,24)=12
{
a=b;
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;
}
would cause the statement block to be executed indefinitely unless the block contains a statement to break
the loop
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.
Intialization
Statements
do {
statements;
True
Initially, 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.
Control Statements 66
Example3.21: i=1;
sum=0;
do
{
sum+=i;
i++;
}while ( i<= 10);
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.
Control Statements 67
3.6 Nested control structures
Like the nested 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 or same.
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 wether 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.The Jump statements are
i) goto identifier
ii) continue
iii) break
Control Statements 68
3.7.1 goto statement
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 where the use of goto might be desirable.
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;
Control Statements 69
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
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.11 given below to know the working of the continue statement.
Control Statements 70
Program3.11 Program to print first 20 natural numbers skipping the numbers divisible by 5.
#include<stdio.h>
void main ( )
{
int i ;
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.Hence all
integers from 1 to 20 not divisible by 5 are displayed.
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.
Control Statements 71
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 loops 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.
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.
Suggested Reading:
EXERCISES
Control Statements 72
}
3.2 What is the value of y in the following code?
x=7,y=0;
if(x = 6)
y=7;
else
y=1;
a)7b)0 c)1d)6
int x=2,y=2,z=1;
if(x=y%2)
z+=10;
else
z+=20;
main()
{
int a=300,b=100,c=50;
if(a>400)
b=300;
c=200;
printf(\n b=%d c=%d,b,c);
}
a) b=100 c=200 b)b=300 c=200 c)b=100 c=50 d) b=300 c=50
3.5. 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
main()
{
int a=500,b=100,c=50;
Control Statements 73
if(a>400)
{
b=300;
c=200;
}
c=100;
printf(\n b=%d , c=%d \n,b,c);
}
a) b=100 c=200 b)b=300 c=200 c)b=300 c=100 d) b=300 c=50
3.7 Which of the following is true?
int a=5,b=7;
if(a<b);
a++;
else
b++;
printf(a=%d,b=%d \n,a,b);
int a=5,b=7;
if(a<b);
{
a++;
++b;
}
printf(a=%d,b=%d \n,a,b);
#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 74
int a=0,b=1;
if(a<b || ++b)
a=5;
else
b=6;
printf(a=%d ,b=%d \n a,b);
}
3.11 Write the following expression using if statement.
x = ( y > 3 ) ? ( x < y ) ? y : x + 10 : ( y < 0 ) ? -y : y + 10;
3.12. 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.13 Consider the following program segment
int n sum=1;
switch(n)
{
case 2: sum=sum+2;
case 3: sum*=2;
break;
default : sum=0;
}
If n=2 ,What is the value of sum
3.15. Omitting the break statement from a particular case in switch case construct
Control Statements 75
{
case 5 : printf (%d\t, x * x) ;
case 6 : printf(%d\t, x + 1 * x+1);
default : break;
}
}
a)25 11 b)25 31 c)25 36 d)25
3.17 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i=1;
while(i<=10)
{
printf(%d,--i);
++i;
}
}
a)Integers from 0 to 10 are printed b) the sequence 0 1 01 01 printed indefinitely
c) 0 is printed indefinitely d) first 10 natural numbers are printed.
int i=0;
while(i<=5);
{
printf(KLU\n);
++i;
}
#include<stdio.h>
main()
{
int x=1;
while()
{
printf(%d,x);
++x;
}
a)syntax error b)1 2 c)2 3 4 5 d)1 2 3 4
3.21 What is the output when the following program is executed?
#include<stdio.h>
main()
{
Control Statements 76
int a=5;
while(a-- >0)
printf(%d\t,a);
}
a)5 4 3 2 1 b) 4 3 2 1 0 c) 5 4 3 2 1 0 d) 4 3 2 1
3.22 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.23. What will be the output when the following code is executed?
#include<stdio.h>
main()
{
int a = 6;
while (a)
{ printf(%d\t, a);
a -= 2;
}
}
a)6 4 2 0 b)6 4 2 c)6 5 4 2 1 d)6 5 4 3 2 1
#include<stdio.h>
main()
{
int a=10;
do
{
Control Statements 77
printf(%d,a);
--a;
}
while(a<=1);
}
a) 10 b)10 9 1 c) 1 2 310 d) syntax error
3.26 What is the output when the following program is executed?
void main( )
{
int i = 1;
do
{
printf(%d, i);
}while (i=i-1);
}
3.27 Which of the following is exit control loop?
a)for b)switch case c)while d)do-while
3.28 How many times KLU is printed?
for(i=0;i>5;++i)
printf(KLU\n);
#include<stdio.h>
main()
{
int i;
Control Statements 78
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.
#include<stdio.h>
main()
{
int a=5;
for(a=5;--a >0; )
printf(%d\t,a);
}
a)4 3 2 1 b)5 4 3 2 1 c) 4 3 2 1 0 d)5 4 3 2 1 0
3.35 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) 7 7 7 c) 3 7 7 7 7 d)3
#include<stdio.h>
main()
{
int a;
for(a=10;! i;-- i)
printf(%d,i);
}
a) First 10 natural numbers are printed in reverse order b)11
c) 10 d) no output.
Control Statements 79
3.37 What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i;
for(i=10;++i ; i-=12)
printf(%d,i);
}
a)11 b)0 c)12 d)11,-1,-13,
3.38 What would be the output when the following program is executed?
#include<stdio.h>
main()
{
int i=4;
for(--i ; --i ; --i)
printf(%d,i);
}
a)2 0 -2 -4 -6 b)4 3 1 -1 -3 c)2 1 0 d)2
3.39 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);
}
a)0 b)no output c) -1 ,-3,-5 d)-1
3.40 What would be the output when the following program is executed?
#include<stdio.h>
main()
{
int x=3456,sum=0;
for( ;x>0;d=x%10,sum+=d,d/=10);
printf(%d,sum);
}
a)0 b)18 c)6 d)output statement is not executed
3.41 What will be the output when the following code is executed?
void main()
{
int i=0;
for(;i++;)
printf(%d,i);
}
3.42 What will be the output when the following code is executed?
void main()
Control Statements 80
{
int i;
for(i=0; i<=10; i++, printf(%d \t, i));
}
3.43 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.44 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.45 What is the output when the following code is executed?
{
for(i=1;i<=5;++i)
{
if(i<=4)
break;
printf(%d,i);
}
}
a)1 2 3 b) 1 2 3 4 c) 1 2 3 4 5 d) no output
3.46 Which of the following statement is true?
a) break statement is used to terminate the execution of the program.
b) continue statement is used to terminate the execution of the loop.
c) exit() function is used to jump out of a loop.
d) break statement is used to exit from a loop or from a switch case structure
3.47. Which of the following statement is true?
a) break statement is used to terminate the execution of the program.
b) continue statement is used to terminate the execution of the loop.
c) exit() function is used to jump out of a loop.
Control Statements 81
d) continue statement is used inside a loop to bypass a section of the loop and
continue the execution with next iteration of the loop.
3.48. Which of the following statement is true?
a) break statement is used to terminate the execution of the program.
b) continue statement is used to terminate the execution of the loop.
c) exit() function is used to jump out of a loop.
d) exit() function is used to terminate the execution of a program.
3.49 Which of the following statement is used to exit from a switch case statement?
#include<stdio.h>
main()
{
int i=1;
for( ; ; )
{
printf(\n %d,++i);
if( i>5)
break;
}
}
a) 2 3 4 5 b) 1 2 3 4 5 c)2 3 4 5 6 d)1 2 3 4 5 6
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;++i)
{
if(i==3)
continue;
printf(%d\t,i);
}
}
a) 1 2 4 5 b) 1 2 3 4 5 c) 4 5 d) 1 2
3.53. What is the output of the following program?
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;++i)
{
Control Statements 82
if(i==3)
break;
printf(%d \n,i);
}
}
a) 1 2 4 5 b) 1 2 3 4 5 c) 4 5 d) 1 2
#include<stdio.h>
main ()
{
int x=1;
for( ; ; )
{
if(x==3)
break;
printf(%d\t,x);
break;
}
}
a) no output b) 1 2
c) 1 d) syntax error as all the three expressions are missing in for
#include<stdio.h>
main()
{
int x=1;
while(1)
{
printf(%d,x);
++x;
}
a) 1 b)1 2 c)2 3 4 5 d)1 2 3 4
Control Statements 83
3.57 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);
}
a)5 b)6 c)4d)0
ANSWERS
3.2)a 3.3)a 3.4)a 3.5)b 3.6)c 3.7)d 3.8)a 3.9)c 3.12)d 3.13)b 3.14)d 3.15)c
3.16)a 3.17)c 3.18)d 3.19)d 3.20) a 3.21)b 3.22)b 3.23)b 3.25)a 3.27)d 3.28)c 3.29)c
3.30)b 3.31)b 3.32)b 3.33)d 3.34)a 3.35)c 3.36)d 3.37)a 3.38)d 3.39)b 3.40)b 3.44)a
3.45)d 3.46)d 3.47)d 3.48)d 3.49)d 3.50)d 3.51)c 3.52)a 3.53)d 3.54)a 3.55)c 3.56)d
3.57)d
Comprehensive Questions:
provided the denominator ad-cb is not equal to zero. Write a program that will read the values of
x1 and x2. An appropriate message should be printed if ad-cb=0
3.6 A function is defined as follows:
Control Statements 84
f(x) =
Write a program to find the value of the function for a 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 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.12 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 software package provided
by the user at the prompt.
3.13 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 cone and
sphere respectively. The process must go on until the user enters q to terminate the program.
3.14 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.15 For a certain electrical circuit with an inductance L and resistance R, the damped natural frequency
is given by
Frequency=
It is desired to study the variation of this frequency with C(capacitance). Write a program to
calculate the frequency for different values of C starting from 0.01 to 0.1 in steps of 0.01
3.16 Write for loop to find the sum of squares of first N-natural numbers.
3.17 Write a program to find the factorial of a given integer.
3.18 Write a program to display the image of given number.
3.19 Write a program to check if a given number is Armstrong or not.
3.20 Write a program to enter integer number and find the largest and smallest digit of the number.
Control Statements 85
3.21 Write a program to check given number is prime or not.
3.22 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.23 Write a program that prompts the user to enter an integer n that represent the number of values in
a list and then prompt the user to list of floating point numbers. After the numbers are read the
program will calculate the average of the positive numbers.
3.24 Write a program to check if a given number is an element of Fibonacci sequence
3.25 The numbers in the sequence 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.26 Write a program to print the numbers that dont appear in the Fibonacci series. The number of
such terms to be printed should be given by the user
3.27 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.28 Write a program to print the values of the function
f(x) = 3ex+ 4 sinx + 0.6 for x=0,0.1,0.2,.1.0
3.29 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.30 Write a program that reads an integer and determines wehter 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 find the sum of the series
1+ x + x 2 + . xn.
3.32 Write a program to find the sum of series
1+ x + x2/2 + x3/3 + . x n-1/(n-1)
3.33 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.34 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.35 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.36 Eulers 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!
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.37 Write a do-while loop that will display the following sequence of numbers
7,9,11,13 67.
a) *
* *
* * *
* * * *
- - - upto nth line
Control Statements 86
b)
*
* *
* * *
* *
c) 1
1 2
1 2 3
1 2 3 4
th
- - - - upto n line
Control Statements 87
3.55 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
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.56 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.57 Create an indefinite for loop that each input value for even or odd.If the value is odd display it
otherwise continue with next iteration. Use break statement to terminate the loop when ever the list
inout values is exhausted .
Control Statements 88
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 1st, 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 89
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 90
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 91
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 92
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 ;
for (i=0; i < 10;++i)
scanf (%d, & ;
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; Output
printf(Enter the number of values: ); Enter the number of values: 5
scanf(%d,&n); Enter the values: 20 5 10 9 14
printf(Enter the values: ); Given values in reverse order is:
for(i=0; i<n; ++i) 14 9 10 5 20
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 93
#define SIZE 50
main( )
{
float a[SIZE], sum, mean;
int n,i;
clrscr( );
printf(Enter the number of values : );
scanf(%d, &n); Output
printf(Enter the values : ); Enter the number of values: 5
for (i=0; i < n; ++i) Enter the values: 10 20 30 40 50
scanf(%f, & ); Mean of the n values : =30
/* 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.
= temp;
}
}
This loop is to be repeated (n-1) times for the values of pass number p=1,2,3,..,(n-1).
Arrays 94
scanf("%d",&n);
printf("Enter the values: ");
for(i=0; i<n; ++i)
scanf("%d",&a[i]);
Output
/*sorting process*/
Enter the number of values in the list:5
for(p=1; p<n; ++p)
Enter the values: 50 31 41 23 11
{
The sorted list is:
for(j=0; j<n-p; ++j)
11 23 31 41 50
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
/*output the sorted list*/
printf("The sorted list is: \n");
for(i=0; i<n; ++i)
printf("%d\t",a[i]);
}
Program 4.4 Program to search for a specified number in a given list of numbers.
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( ); Output
printf(Enter the number of values in the list: ); Enter the number of values in the list:6
scanf(%d, & n); Enter the values:13 52 45 12 6 40
printf(Enter the values : ); Enter the number to be searched: 45
for(i=0; i < n; ++i) 45 is in the list at the position 3
scanf(%d, & );
printf(Enter the number to be searched:);
scanf(%d, &key);
for(i=0; i<n; ++i)
{
if(key = = )
{
flag = 1;
break ;
Arrays 95
}
}
if (flag = = 1)
printf(\n%d is in the list at the position %d , key, i+1);
else
printf (\n%d is not in the list , key);
}
The method employed in the above program is called linear search method.
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 b 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("\nEnter the elements of the first list in ascending order: ");
for(i=0; i<m; ++i)
scanf("%d",&a[i]);
printf("\nEnter the number of elements of the second list ascending order: ");
scanf("%d",&n);
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;
Arrays 96
}
else
{
c[k]=b[j];
++j; Output
} Enter the number of elements of the first list:5
++k; Enter the elements of the first list in ascending
} order:
while(i<m) 22 34 56 89 99
{ Enter the number of elements of the second list
c[k]=a[i]; ascending order:
++i; 25 43 52 85 90
++k; the merged list is:
} 22 25 34 43 52 56 85 89 90 99
while(j<n)
{
c[k]=b[j];
++j;
++k;
}
printf("the merged list is: \n);
for(i=0; i<m+n; ++i)
printf("%d\t",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> Output
void main( ) Enter the decimal number :23
{ The binary representation of the decimal
short int bdigit[16],digit; integer 23 is :
int nd,num,i=0,j; 10111
clrscr();
printf(Enter the decimal number :);
scanf(%d,&num);
printf(The binary representation of the decimal integer %d is :\n,num);
while(num>0)
{
digit=n%2;
bdigit[i]=digit;
++i;
num=num/2;
}
nd=i; // nd is the number of digits in binary representation
Arrays 97
for(j=nd-1;j>=0;--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-1]=key;
The program to implement this process is:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10],n,i,key,pos;
printf(Enter the number of values in the list:);
scanf(%d,&n);
printf(\nEnter the values);
for(i=0;i<n;++i)
scanf(%d,&a[i]);
printf(Enter the number to be inserted:);
scanf(%d,&key);
Output
printf(Enter the position:);
Enter the number of values in the list:5
scanf(%d,&pos);
Enter the values 21 45 65 78 9
++n;
Enter the number to be inserted:50
for(i=n-1;i>=pos;--i)
Enter the position:3
a[i]=a[i-1];
The new list after insertion is : 21 45 50 65 78 9
a[pos-1]=key;
printf(The new list after insertion is :\n);
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 by one position. If the list contains 7 elements and
the value of pos is 3, the following code can be used to implement this process
Arrays 98
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;
printf(Enter the number of values in the list:);
scanf(%d,&n);
printf(Enter the values:); Output
for(i=0;i<n;++i) Enter the number of values in the list:5
scanf(%d,&a[i]); Enter the values:12 45 41 8 62
printf(Enter the position:); Enter the position:4
scanf(%d,&pos); The new list after deletion is :
if(pos<1 || pos>n) 12 45 41 62
{
printf(Invalid position \n);
exit(0);
}
--n;
for(i=pos-1;i<n;++i)
a[i]=a[i+1];
printf(\nThe new list after deletion is :\n);
for(i=0;i<n;++i)
printf(%d\t,a[i]);
getch();
}
4.6 TWO-DIMENSIONAL ARRAYS
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.
Arrays 99
Column 0 Column 1 Column 2 Column (n-1)
a 0 0 a 0 1 a 0 2 a 0 n 1
Row 0
a 1 0 a 1 1 a 1 2 a 1 n 1
Row 1
a 2 0 a 2 1 a 2 2 a 2 n 1
Row 2
a m 1 0 a m 2 1 a m 3 2 a m 1 n 1
Row (m-1)
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
Arrays 100
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
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].
for(i=0; i<3;++i)
for(j=0; j<4; ++j)
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)
{
for(j=0; j<4; ++j)
printf("%8d",a[i][j]);
printf(\n);
}
Arrays 101
Program 4.9 Program to add two matrices
Given two matrices A of order r1c1 and B of order r2c2, we write a program to find
their sum with suitable validation.
To find the sum matrix we have to find each element of the sum matrix .In general (i,j)th
element of the sum matrix C is obtained as
C[i][j]= A[i][j] + B[i][j];
for all combinations of i=0,1,2,,r1-1 and j=0,1,2,c1-1.
/*Program to find sum of two matrices*/
#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
#define ROWSIZE 5
#define COLSIZE 5
void main ( )
{
int r1, c1, r2, c2, i,j;
int a[ROWSIZE] [COLSIZE], b[ROWSIZE] [COLSIZE],c[ROWSIZE] [COLSIZE];
printf (Enter the number of rows and columns of first matrix:);
scanf (%d %d, & r1, & c1);
printf (Enter the number of rows and columns of second matrix:);
scanf (%d %d, & r2, & c2);
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);
for (i=0 ; i < r1 ; ++i)
for (j=0 ; j < c1 ; ++j)
scanf (%d, & ;
printf (Enter the elements of the second matrix row wise:\n);
for (i=0; i < r2 ; + + i)
for (j=0; j < c2 ; + + j) Output
scanf (%d, & b ; Enter the number of rows and columns of first
/* add the two matrices*/ matrix:3 3
for (i=0 ; i < r1 ; ++i) Enter the number of rows and columns of second
for (j=0 ; j < c1 ; ++j) matrix:3 3
{ Enter the elements of the first matrix row wise :
4 5 6
} 1 2 0
/*output the sum matrix */ 3 5 2
printf The sum matrix is : \n); Enter the elements of the second matrix row wise:
for (i=0; i < r1 ; ++i) 1 4 6
{ 2 1 5
for (j=0; j< c1 ; ++j) 7 2 0
printf (%8d, ; The sum matrix is :
printf(\n); 5 9 12
} 3 3 5
}/*end of main*/ 10 7 2
Arrays 102
Program 4.10 Program to find the product of two matrices
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
b j
1
ciJ aio ai1 ai 2 .... aip 1 b2 j
bP 1 j
=[ai0b0j+ai1b1j+ai2b2j++aip-1bp-1j]
p 1
= a
k 0
ik bkj
Thus, the following loop can be used to find the (i, j)th element
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define ROWSIZE 5
#define COLSIZE 5
void main ( )
{
int i, j ,k, r1, c1, r2, c2 ;
int a[ROWSIZE] [COLSIZE], b[ROWSIZE] [COLSIZE],c[ROWSIZE] [COLSIZE];
printf (Enter the order of the first matrix :);
scanf (%d%d, &r1, &c1);
printf (Enter the order of the second matrix :);
scanf (%d%d, &r2, &c2);
if (c1 ! = r2)
{
printf (product of given matrices does not exist \n);
exit (0);
}
printf (Enter the elements of first matrix row wise : \n);
for (i=0; i < r1 ; ++i)
for (j=0; j < c1; ++j)
scanf(%d, &a
printf(Enter the elements of second matrix row wise:\n);
for(i=0; i<r2; ++i)
Arrays 103
for (j=0; j< c2; ++j
scanf(%d, & b
/*find the elements of product matrix*/ Output
for(i=0; i<r1; ++i) Enter the order of the first matrix :3 3
for (j=0; j < c2; ++j) Enter the order of the second matrix :3 3
{ Enter the elements of the first matrix row wise :
c[i][j] = 0; 4 5 6
for(k=0; k<c1; ++k) 1 2 0
c[i][j] + = ; 3 5 2
} Enter the elements of the second matrix row wise:
printf (The product matrix is : \n); 1 2 5
for (i=0; i< r1; ++i) 0 7 6
{ 4 4 1
for (j=0; j< c2; ++j) The product matrix is :
printf (%8d, c[i][j]); 28 67 56
printf(\n); 1 16 17
} 11 49 47
}/*end of main */
Arrays 104
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 display n lines of the Pascal triangle. When n=6, the triangle is as follows
1 1
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 1s. 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
i. Total marks obtained by each student
ii. The highest marks in each subject and the roll no, of the student who secured it.
iii. The student who obtained the highest total marks.
Store the roll numbers in a one dimensional integer array rno, marks in a two dimensional array m of
size 44, where the total marks are stored in 4th column. Find the sum of the marks in each row for total
marks of the each student, maximum marks in the first three columns for subject wise maximum marks
and maximum marks in the fourth column for highest total marks. Display the output in a tabular form
#include<stdio.h>
#include<conio.h>
void main ( )
{
int rno[4],i,s1_rno,s2_rno,s3_rno,total_rno;
float m[4][4], s1_max,s2_max,s3_max,total_max;
printf( Enter the Roll no. and marks in 3 subjects of 4 students: \n);
for(i=0;i<4;++i)
scanf(%d%f%f%f,&rno[i],&m[i][0],&m[i][1],&m[i][2]);
/* To find total marks of each student */
for(i=0;i<4;++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<4;++i)
{
if(s1_max<m[i][0]) Output
{ Roll no sub1 sub2 sub3 Total
s1_max=m[i][0]; 12007582 80 20 30 130
s1_rno=rno[i]; 12003546 35 55 65 155
} 12007652 40 10 70 120
if(s2_max<m[i][1]) 12003500 10 60 30 100
{ Maximum marks in subject 1 is 80 and the roll number of the student is
s2_max=m[i][1]; 12007582
s2_rno=rno[i]; Maximum marks in subject 2 is 60and the roll number of the student is
} 12003500
if(s3_max<m[i][2]) Maximum marks in subject 3 is 70and the roll number of the student is
{ 12007652
s3_max=m[i][2]; Highest total marks is 155 and the roll number of the student is
s3_rno=rno[i];
12003546
}
if(total_max<m[i][3])
{
total_max=m[i][3];
total_rno=rno[i];
Arrays 106
}
}
printf(\n\t Roll no \t Sub1 \t Sub2 \t Sub3 \t Total\n);
for(i=0;i<4;++i)
{
printf(\t %d \t %6.2f \t %6.2f \t %6.2f \t %6.2f \n,rno[i],m[i][0],m[i][1],m[i][2],m[i][3]);
}
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();
}
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 dont 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.
Suggested Reading:
EXERCISES
Arrays 107
void main()
{
int arr[6]={12,13};
printf(\n %d , %d,a[1],a[3]);
}
a)13,garbage b)12,13 c)12,garbage d)13,0
4.3.Array name is
a)is always an integer type b)a key word
c)a common name shared by all elements d)not used in a program
4.4. Array elements occupy
a)adjacent memory locations
b)random location for each element
c)varying length of memory locations for each element.
d) no space in memory.
4.5. Array is used to represent
a) a list of data items of integer data type.
b) a list of data items of real data type.
c) a list of data items of different data type.
d) a list of data items of same data type.
4.6. Array subscripts in C always starts at
a)-1 b)0 c)1 d)any value
4.7.If the size of the array is less than the number of initializes, then
a) extra values are neglected
b) it is an error
c) the size is automatically increased
d) the size is neglected.
4.8. What is the output when the following program is executed?
#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);
}
a) 10 b) 1 c) 15 d)21
4.9. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a[5] = { 1,3,4 } , i ;
for ( i = 4; i> = 0; --i )
printf ( %d \t, a[i]);
}
a)0 0 4 3 1 b) 0 4 3 1
c)1 3 4 0 d) syntax error will occur during execution of the program
4.10. What is the output when the following program is executed?
#include<stdio.h>
Arrays 108
main()
{
int a[5], i;
for( i=0; i < 5; ++i)
a[i] = i * i ;
for( i=0; i< 5 ; ++i)
printf(%d , a[i]);
}
a)1 4 9 16 b) 1 2 3 4 5 c) 1 4 9 16 25 d)0 1 4 9 16
Arrays 109
4.15.What is the output generated by the following program segment?
int i ;
int a[5]={0};
for(i = 1; i < 5 ; ++i)
=i+
for(i = 0 ; i < 5 ; ++i)
printf (%d \t, );
a)2 6 8 10 12 b)2 4 6 8 10 c)0 1 3 6 10 d) unpredictable output
4.16. What is the output generated by the following program segment?
int a, b, c ;
int x [3] [4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
for(a=0; a < 3 ; ++a)
{ c = 999 ;
for (b=0 ; b < 4 ; ++b)
if (
c =x ;
printf (%3d, c);
}
a) 1 2 3 b)999 999 999 c) 999 5 999 d)1 5 9
4.17. What will be the output of the flowing program ?
#include<stdio.h>
int main()
{
int arr[5], i=0;
while(i<5)
arr[i]=++i;
for(i=0; i<5; i++)
printf("%d\t ", arr[i]);
return 0;
}
a)0 1 2 3 4 b)garbage c)1 2 3 4 5 d)0 0 0 0 0
4.18. What is the output if the flowing program is executed?
#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) 18 c) 65 d)unpredictable output
ANSWERS
4.1)a 4.2)d 4.3)c 4.4)a 4.5)d 4.6)b 4.7)b 4.8)c 4.9)a 4.10)d4.11)a 4.12)c
4.13)a 4.14)b4.15)c 4.16)d4.17)c 4.18)b
Arrays 110
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.3 Write a program to compare two one dimensional arrays containing two sets of numbers
4.4 Write a program to find the median height of students in a section
4.5 Write a program to implement the binary search alorigthm
4.6 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.7 Write a program for fitting a straight line passing through a set of points (xi, yi), i =1,2, . . . n.
The straight line equation is
y = mx + c
and the values of m and c are given by
Arrays 111
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 112
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
return_type function_name (data type arg1, data type
arg2)
{
Local_variable declaration;
Executable statement 1;
Executable statement 2;
.
return(expression);(or) return expression;
}
return_type indicates the data type of a value returned by the function and it may be of any data type like
int, float, double, void, array, structure, pointer etc
function_name is the name of the function given by the user and should follow the rules of an identifier.
arg1, arg2, arg3, are the list of arguments used to pass data from the calling function to the called
function. These arguments are called formal parameters.
Local_variables declaration is the declaration of local variables if required inside the function body.
Executable statements 1,2.:indicates any executable statements that are written to perform the task of
the function.
return(expression); is the statement that returns the value of expression to the calling portion of the
program. Only one expression can be included in return statement. Thus a function can return only one
value to the calling portion of the program. When a user defined function is written in the above form it is
called the definition of the function
Functions 113
Example5.2 Function to return the sum of two integers
Function_nam e
Return type
List of arguments
Local variable
int sum(int a, int b)
declaration
{
int s; Executable statement
s=a+b;
return(s); Return statement
}
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 Function to return biggest of two integers
int big( int x, int y)
{
if( x > y)
return(x);
else
return(y);
}
Functions 114
Advantages of writing functions
Every C program must have a function with the name main() and any number of other functions. Writing
all statements of a small task in main only is fine but if the main contains large number of statements say
100,1000,10000 lines for a big task, then it leads to a number of problems like
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( );
}
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.
Functions 115
Example5.7
main()
{ ..
fun3( );
..
}
void fun1( )
{ .
.
}
void fun2( )
{ .
fun1( );
.
}
void fun3( )
{
fun2( );
}
Here fun3( ) is called by main( ) and fun3( ) calls fun2( ) which calls inturn 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()
{
h_line();
}
void h_line()
{
int i;
for(i=0;i<10;i++)
printf(-);
}
Exampple5.9
void main() Wrong
{
int x;
x=h_line(); x=h_line();
}
void h_line(void)
{
int i;
for(i=0;i<10;i++)
printf(-);
}
Functions 116
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;
printf(\n enter any four integers:);
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);
printf(\n GCD=%d and LCM=%d,gc,lc);
}
Functions 117
Example5.12 Program to find sum of two integers using function
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
Example5.15
Functions 118
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
Output
Values of x and y before swap
x=20 y=30
values of x and y after swap
x=30 y=20
Functions 119
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)
Functions 120
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
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 that will 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;
}
Functions 121
return;
}
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(float 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 122
p = 1.0/power(x,y);
printf(\n value of %f to the power of %d is %lf,x,y,p);
}
double power(float 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(%5da[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)
{ ..
..
..
Functions 123
return(expression);
}
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;
Functions 124
int i;
for(i=1; i<=n; i++)
f = f * i;
return(f);
}
5.6 PASSING ARRAYS TO FUNCTIONS
Functions 125
for(i=0;i<n;i++)
printf(\t %d\t \t%d, tmarks [i],i+1);
}
sort(int x[50], int n)
{
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.
Functions 126
The prototype declaration should be similar to the function definition
The function must be called simply by passing the array name only.
Program 5.11 Write functions to read and display a matrix .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 first matrix:);
scanf(%d%d, &m1, &n1);
printf(\n Enter the no rows and columns of second matrix :);
scanf(%d%d, &m2, &n2)
if(m1!=m2 ||n1!=n2)
{
Functions 127
printf(Addition not possible \n);
exit(0);
}
printf(\n Enter the elements of first matrix row wise :\n);
read_mat(a,m1,n1);
printf(\n Enter the elements of secondmatrix row wise :\n);
read_mat(b,m2,n2);
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 to read, multiply and
display 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 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 first matrix:);
scanf(%d%d, &m1, &n1);
printf(\n Enter the no rows and columns of second matrix :);
scanf(%d%d, &m2, &n2)
if(n1!=m2)
{
Functions 128
printf(multiplication not possible \n);
exit(0);
}
printf(\n Enter the elements of first matrix row wise :\n);
read_mat(a,m1,n1);
printf(\n Enter the elements of second matrix row wise :\n);
read_mat(b,m2,n2);
mult_mat(a,b,c,m1,n1,m2,n2);
printf(\n Product matrix is:\n);
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 129
2. stdio.h contains the headers of standard input and output functions and macros
3. string.h contains the functions for string manipulation and processing
4. conio.h contains the headers of console input/output functions
5. ctype.h contains the headers of character type and manipulation functions
Some important built-in functions stored in the header files are
Functions 130
Example5.27
a1=sin(3.14159*angle/180);
a2=cos(3.14159*angle/180);
a3=tan(3.14159*angle/180);
exp( ) its prototype is double exp(double x);
pow( ) its prototype isdouble pow(double x, double y);
log( ) its prototype is double log(double x);
log10( ) its prototype is double log10(double x);
Example5.28
Since recursion process simulates repetitive process, it is required to check a condition for stopping the
repetitions.
Example5.31 Recursive function to find factorial of an integer
Factorial of an integer is a recursive function in Mathematics and is defined as follows
n!= 1 , if n=0 or 1
n(n-1)! , if n>1
Using this mathematical function we can write the corresponding C code.
long int factorial ( int n)
{
if (n==0 )
return(1)
else
return(n*factorial(n-1));
Functions 131
}
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
main() Output
{ value of i inside the block = 100
int i=4; value of i outside the block=5
int j=10;
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:
Functions 132
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 */ Output
func(); Value of local variable in the function func
printf( "Value of global variable\ n i = %d\n", i ); i = 11
}
Value of global variable
func()
{ int i=10; /* Local declaration of i */ i=5
i++;
printf( "Value of local variable in the function func \n i = %d\n", i );
}
Note: differences between local and global variables
Local variables Global variables
Functions 133
5.10 Storage Classes
Each Variable in C is characterized by its
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 longivity(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 longivity 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,
extern - external variables,
static - static variables and
register - register variables.
The general form of variable declaration with storage class is
Storage_class data_type variable_name1, variable_name2,..;
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
Functions 134
void main( )
{ int i;
Output
for(i=1; i<=5; i++) x=11
printf(%d\n, fun1( )); x=11
} x=11
int fun1( ) x=11
{ x=10; x=11
return(++x);
}
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.
Default initial value: The default initial value of automatic variable is garbage
void main( )
{
Output
int y;
printf(\n y=%d, y+=5); y= garbage
}
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 135
5.10.2 External variables
Variables that are declared outside the scope of any function are external variables. All global variables
are external variables.
int s; // s is global variable
void main()
{ s=96;
..
}
float r; // r is global variable
void fun1()
{
r=5.4; .
}
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;
void main( )
{
printf(\n x=%dx)
fun1();
Functions 136
Output
fun2(); x=96
printf(\n x=%d,x); x=200
} x=200
void fun1( )
x=500
{
x=200;
printf(\n x=%d, x);
}
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
fun1(); not allocated)
}
int x; External
void fun1() variable Output
{ definition x=200
x=200; (memory x=200
printf(\n x=%d, x );
is
}
allocated)
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 137
..
}
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 )
{ static int x=10;
return(++x);
}
The internal static variable x is 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.
Default initial value: The default initial value of internal or external static variable is zero
static int x;
void main( )
Output
{
x=1
static int y; y=5
printf(\n x=%d, ++x);
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.10.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.
Functions 138
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( )
{
register int i; // i is register variable.
for(i=0; i<=10000; i++) { }
..
...
}
Scope: The scope is local to the function in which a register variable is defined.
Life time: The life time of register variables is temporary
Default initial value: The default initial value is garbage
Memory location: These variables are located in registers of CPU
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 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( )
{ int total = 20;
printf("Hello World");
total = total + l;
}
Paranthises after the function's name are required. One or more parameters to a function can be passed
as follows :
demo( int a, int b)
{ 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:
Functions 139
int demo( int a, int b)
{
int total;
printf("Hello World");
total = a + b;
return (total);
}
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
{
printf( %d, x);
x++;
f( );
}
}
Functions 140
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.
Suggested Reading:
EXERCISES
Functions 141
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
Functions 142
printf("%d,", n);
fun(--n);
}}
5.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
5.7. Point out the error in the program
#include<stdio.h>
int main()
{
int a=10;
void f();
a = f();
printf("%d\n", a);
return 0;
}
void f()
{
printf("Hi");
}
5. 8. Find the output of the following program segement.
#include <stdio.h>
main()
{
int j,ans;
j = 4;
ans = count(j);
printf("%d\n",ans);
}
int count(int i)
{
if ( i < 0)
return(i);
else
return( count(i-2) + count(i-1));
}
a) -18 b) -10 c)-4 d) 4
Functions 143
5.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
5.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
5.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)
{
return(x*y);
}
a) 10,0 b)11,0 c)10,1 d)11,1
ANSWERS:
5.1)b 5.2)c 5.3)b 5.4)b 5.6)c 5.8)a 5.9)d 5.10)a 5.11)a
Functions 144
12. What is the need for functions?
13. Explain the general form of defining a function.
14. What do you mean by function call?
15. What are formal arguments?
16. What are actual arguments?
17. Define function prototype.
18. Mention the categories of functions.
19. What is calling function?
20. What is a called function?
21. The number of actual arguments and the number of formal arguments should be same
when a function is called. True / False
22. One function can be defined within another function. True / false
23. How many values can a function return?
24. What is meant by the scope of a variable?
25. What is meant by lifetime of a variable?
26. Mention different storage classes.
27. Define recursion and a recursive function
28. A function can returns float value by default. True / False
29. Variables declared within functions are by default of static storage class. True / False
30. The name of global variable and that of a local variable can be same. True / False
31. Only local variables can be of register storage class. True / False
32. Static variables retain their values between function calls. True / False
33. Write about storage classes in C along with their location, scope and life span.
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) , given the values of n and r.
C(n,r) = n!/ (n-r)!r!
5.8 Write a program that determines a students grade. It reads three tests scores (between 0 to 100) and
calls a function that calculate and returns a students 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.
5.9 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.
Functions 145
5.10 Write a function to find gcd of two numbers and use this function to find their lcm .
5.11 Write a recursive function for binary search with function prototype.
int binsearch(int data[], int key,int ll,int ul); and call this function in main() to test this function.
5.12 Write a function which imitates the behavior of strlen() function. Use this function to check if a
given string is a palendrome or not.
5.13 Write a recursive function power that computes ax , where a is a real constants and x is an integer.
5.14 Write a function that will scan a character string passed as an argument and convert all lower case
characters into their uppercase equivalents.
5.15 Write a function that can be called to find the largest element of an m X n matrix
5.16 Write a function that converts miles to kilometers. Note that 1 mile equals 1.6093440 km.
5.17 Write a function that will round a floating-point number to the specified decimal place. For example
the number 17.457 would yield the value 17.46 when it is rounded off to two decimal places.
5.18 Write a recursive function to find the binary code of a decimal integer.
5.19 Write a function isprime that returns 1 if its argument is a prime number and returns zero otherwise.
5.20 Calculate factorials of n from 1 to 20 using a factorial function with return type of unsigned long
long.
5.21 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.22 Write a program to reverse an integer using a recursive function
5.23 The Fibonacci numbers are defined recursively as follows
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 if n>2
Write a function with local static variables to find n th element of Fibonacci sequence
5.24 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
Functions 146
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 of operator( &):The address of 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 element.
&150, &(x+y) are not allowed.
*2000 =>10.23
*ptr
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 it is called as indirect reference operator.
The variable name sum refer the data item stored in the memory location allocated to sum.That data iem
can also be refered through the pointer variable ptr. 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;
Pointer Variable
A variable that is a pointer to a pointer must be declared as given 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
Program 6.4 Program to illustrate the contents of the variable their address using pointer
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);
Pointer Arithmetic
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.
2. A pointer can be incremented or decremented.
The expressions such as ++p1,--p1,p1-- etc. are allowed.
3. Two pointers can be compared, if they are pointers to same datatype.
int *p1,*p2;
the expressions such as p1==p2,p1!=p2,p1<p2 are allowed.
4. One pointer can be subtracted from another pointer if both point to the same array.
int a[10],*p1,*p2;
p1=&a[0];
p2=&a[4];
k=p2-p1; is allowed
the value assigned to k is 4.
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 the function definition will
be reflected on 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 integer values by passing pointers to the function swap
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
clrscr();
int a,b;
printf("\n\n\t\t Enter the integer values to be swapped :");
scanf("%d%d",&a,&b);
printf("\n\n\t\t The values before swapping are %d & %d",a,b);
swap(&a,&b);
printf("\n\n\t\t The values after swapping are %d & %d".a,b);
}
void swap(int *aptr,int *bptr)
{
temp=*aptr;
*aptr=*bptr;
*bptr=temp;
return;
}
*bptr=temp
temp=*aptr *aptr=*bptr
10 b
a
10 20 20 10
8000
2000 4000
a
a
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 function that 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
#include<stdio.h>
#include<conio.h>
void find_ area_in(float a, float b, float c, float *pa, float *pc );
void main()
{
float a,b,c,area,circumference,*pa,*pc;
pa=&area;
pc=&circumference;
printf("\n\n\t\t Enter the three sides of the triangle :");
scanf("%f%f%f",&a,&b,&c);
find_area_in(a,b,c,pa,pc);
printf(" area of the triangle=%.2f\n,*pa);
printf(" circumference of the triangle=%.2f\n,*pc);
}
void find_area_in(float a, float b, float c, float *pa, float *pc )
{
float s;
s=(a+b+c)/2.0;
*pa=sqrt(s*(s-a)*(s-b)*(s-c));
*pc=a+b+c;
return;
}
In the above program addresses of area and circumference and the sides are passed. The calculated values
of area and circumference are stored in the memory locations allotted for the variables area and
circumference in the function main through the de referencing *pa and *pc.
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 name represent the base address of the array or address of first element of the array.Hence array
name is a pointer to the array
10 20 30 40 50
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 );
` PRINTARRAY(n,a);
}
void READARRAY(int n,int *aptr)
{
register int i;
for(i=0;i<n;i++)
scanf(%d,aptr+i);
}
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);
}
void SORTARRAY(int n, int *aptr)
{
register int i,p;
for(p=1;p<n;++p)
for(i=0;i<n-p;++i)
if(*(aptr+i)> *(aptr+i+1))
{ temp=*(aptr+i);
*(aptr+i)= *(aptr+i+1);
*(aptr+i+1)=temp;
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 i 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 function and 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]
1 th one Dim. array 2002
a+1
2006 2008 2010
so on 2002
Since a two dimensional array name is a pointer to a group of contiguous one-dimensional arrays,the
declaration int a[3][4] is also can be written as int (*a)[4];
In general data-type(*ptr_variable)[size];
For three dimensional array the declaration is
data-type (*ptr_variable)[size][size]; and this can be generalized for higher-dimensional array;
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] : [,] have higher priority than *, so, it is array of pointers.
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 & jare to
select rows and columns respectively.
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 The given 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++)
{
for(j=0;j<c;j++)
printf("%6d",*(*(aptr+i)+j));
printf("\n");
}
}
Here a[4][6] is an array of 4 one dimensional arrays each of size 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; printmatrixdisplayselements of the matrix in natural form.
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",(*(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[4][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
printf("\n\n\t\t Matrix multiplication is not possible");
}
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;
*(*(rptr+i)+j)=*(*(rptr+i)+j)+((*(*(fptr+i)+k)) * (*(*(sptr+k)+j)));
}
}
}
}
The program contains two functions; readmatrixs which reads and stores the elements of matrix in a
given array; printmatrix display elements of the matrix in natural form. i, j ,k are register variables
whose values are used for identifying different elements of the array through pointers.
The function matmultiplication multiplies the matrices using the following code
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++)
{
*(*(rptr+i)+j)=0;
*(*(rptr+i)+j)=*(*(rptr+i)+j)+((*(*(fptr+i)+k)) * (*(*(sptr+k)+j)));
}
}
}
In the above code (*(rptr+i)+j)) points/to the(i,j)th element of the product matrix R.
Similarly ,*(sptr+i)+k and *(str+k)+j points to the (i,k)th and (k,j)th elements of the matrices F and S
repectively
#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. Static memory 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];
allocates 12 bytes of memory space at compilation time. In such a declaration there are few
shortcomings.
i) If we want to deal with more memory than the allocated memory during runtime of the program,
it is not possible to increase the size of array at runtime.
ii) Many a times all the memory allocated during compile time is not used; it is not possible to
decrease the allocated memory at runtime.
To overcome the above problems we have the concept of Dynamic Memory Allocation.
Dynamic Memory Allocation is the phenomenon of allocation of memory during run time. Allocated
memory can be released during runtime.
1. malloc()
2. calloc()
3. realloc()
4. free()
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.
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 0s .
calloc has two parameters first is the no. of blocks to be allocated and the second is the sizeof block.
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.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *pa,*pb ,*pc m,n,i,j,p,q;
printf(Enter the number of rows and columns of first matrix : \n);
scanf( %d%d , &m,&n);
printf(Enter the number of rows and columns 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));
pb=(int *)calloc(p , q*sizeof(int));
pc=(int *)calloc(m , q*sizeof(int));
if(pa==NULL)
{
printf(Memory not allocated);
exit(0);
}
printf(Enter the elements of the first matrix row wise\n);
for(i=0;i<m;++i)
for(j=0;j<n;++j)
scanf(%d , (pa+i*n)+j ) ;
printf(Enter the elements of the second matrix row wise\n);
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:\n);
In this program calloc() function is used to allocate the memory space to store the two input matrices and
the output matrix.
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).
On successful reallocation the function returns a pointer to the first byte of the reallocated block. If the
function is unable to allocate the additional size a NULL pointer is returned and the original block is
freed.
new size of block may be smaller or larger than the original block size. The location of old block and
new block may be same or different. If different data of old block will be copied to the new block,the
function will guarantee that the old data is intact.
ptr1=(char *)realloc(ptr1,sizeof("K.L.University"));
Above statement reallocates the memory block represented by the pointer ptr1 to the new size 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 is extensively used with their operators & and *. Arithmetic operations on
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.
Suggested Reading:
EXCERCISES
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)2 4 6 8 b)0 4 9 16
c)1 4 9 16 d)compilation error because i[a] is not allowed.
6.11. What is the output?
main()
{
int a[]={0,1,2,3};
int *ptr;
for(ptr=&a[0];ptr<=&a[3];ptr++)
printf(%d,*ptr+5);
}
a)compilation error because ,the test expression in for is invalid.
b) compilation error because ,the expression *ptr+5 is invalid.
C) 5 6 7 8 d) Garbage
6.12. Pointer variable may be assigned
a) An address value represented in hexadecimal
b) An address value represented in octal
c) The address of another variable.
d) All the above.
6.13. Identify the invalid expression.
a)&35 b)&(x+y) c)&(x-y) d)all the above
6.14. Identify the correct declaration statements.
a)float a=5;int *p=&a; b)float *p=&a;float a;
c)int a=5,p=&a; d)all the above .
6.15. Identify the invalid expression given
int num=15,*p=#
a)*(&num) b)**&num c)p++ d)*num
6.16. Identify the invalid expression for given
float x=2.14,*y=&x;
a) &y b)*(&x) c)**&y d)(*&)x
6.17.The operand of the address of operator is
a)a constant b)an expression c)a register variable d)a variable
6.18. How does the compiler differentiate address of operator from bitwise AND operator?
a) by using the number of operands and position of operands
b) by using the declaration
c)both options a and b d)by using the value of operand.
6.19. The operand of indirection operator is
a)pointer variable b)pointer expression
c)both options a and b d)ordinary Variable
Answers:
6.1)a 6.2)c 6.3)a 6.4)b 6.5)a 6.6)a 6.7)a 6.8)d 6.9)d 6.10)c 6.11)c
6.12)c 6.13)d 6.14)c 6.15)d 6.16)d 6.17)d 6.18)a 6.19)c 6.20)d 6.21)b 6.22)b
6.23)b 6.24)c 6.25)d 6.27)d 6.28)d 6.29)d 6.30)d 6.31)a 6.32)c 6.33)d 6.34)d
6.35)a 6.36)b 6.37)d 6.38)c 6.39)b 6.40)d 6.41)d 6.42)a 6.43)a 6.44)b 6.45)b
6.46)b 6.47)b 6.48)c 6.49)c 6.50)d 6.51)d 6.52)b 6.53)b 6.54)a 6.55)c 6.56)d
6.57)c 6.58)c 6.59)b 6.60)b 6.61)b 6.62)b 6.63)d 6.64)b 6.65)b 6.66)c 6.67)a
6.68)d 6.69)c 6.70)c 6.71)d 6.72)d 6.73)a 6.74)b 6.75)c 6.76)a 6.77)c 6.78)d
6.79)a 6.80)d 6.81)a 6.82)d 6.83)b
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>
main()
{
Output:
char ch;
Press any key
printf(Press any key \n);
H
ch=getchar();
The character is a letter.
if (isalpha(ch)>0)
Press any key
printf(The character is a letter.);
5
else if (isdigit(ch)>0)
The character is a digit
printf(The character is a digit.);
Press any key
else
&
printf(The character is not alphanumeric.);
The character is not alphanumeric
}
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
{ characters
char s[80]; the string typed is
printf (Type a string less than 80 characters); K L UNIVERSITY
gets(s);
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 names 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.
%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 to be read integer mode.
Example7.4
scanf (%3d %4d, &sum1, &sum2);
If the input is
175 1342 sum1
175 sum2
1342
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
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);
}
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)
Read characters form keyboard and the specification %s terminates reading at the encounter of a
white space.
If the user input is abc def ,the string variable str holds abc
3. scanf(%[a-z],str);
Read characters form keyboard and terminates reading at the encounter of non alphabet.
If the user input is abc123 , the string variable str holds abc
4. scanf(%[^z],str);
Read characters form keyboard and terminates reading at the encounter of character z.
If the user input is abc123 z , the string variable str holds abc123.
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,,expn);
The control string contains format of the data to be displayed and exp1,exp2,exp3,expn 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
For example,
Format Output
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
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
printf(%f,x) 9 8 . 7 6 5 4 0 0
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
7.5.3 Printing of single Character
A single character can be displayed in a desired position using following format specification
%wc
The character will be displayed right justified in the filed of w columns
We can make display left justified by placing - sign before the field width w
Default value of w is one
Output
Enter any character:
K
K
%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
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 0s 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 0s in g-type
Example 7.7
Output
#include<stdio.h> Enter three integers
main() 12 34 45
{ Enter three floating numbers
int a,b,c,d; 23.456 89.1234 12.456
float x,y,z; 12 34 45
printf (\n Enter three integers\n); 00012 00034 00045
scanf(%d%d%d,&a,&b,&c); 23.46 89.12 12.46
printf (\n Enter three floating numbers:\n);
scanf(%f %f %f,&x,&y,&z);
printf( \n%5d\t %5d \t%5d,a,b,c);
printf( \n%05d\t %05d\t%05d,a,b,c);
printf( \n%-5.2f\t %-5.2f \t%-5.2f,a,b,c);
Suggested Reading:
EXERCISES
Review Questions
7.1.What will the values of each variable be after the input
command:
data input: Tom 34678.2AA4231
scanf("%s %3d %f %c %*c %1d %x",name,&m,&x,&ch,&i,&j);
name:Tom m :346 x :78.2
ch :A i :4 j :231
7.2. What output does each of these produce?
a) putchar('a');
b)putchar('\007');
c) putchar('\n');
d) putchar('\t');
e) n = 32; putchar(n);
f) putchar('\"');
7.3. For the different values of n, what is the output?
printf("%x %c %o %d",n,n,n,n);
a) n = 67 b) n = 20
c) n = 128 d) n = 255
7.4. What is wrong with each of the following statements?
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
7.3. Write a program that uses scanf() and printf() statements to prompt for your first name, last name,
street, city, state and zip code. After input of the values, then print the values out with the following
format:
Name:
Street:
City:
State:
Zip:
7.4. Write a program that converts and prints a user supplied measurement in inches into
a.foot(12 inches) b. yard (36 inches)
c.centimeter (2.54/inch) d. meter (39.37 inches)
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 197
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 198
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 199
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 200
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 201
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 202
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 203
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 204
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 205
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 206
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 207
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 0th, 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 208
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 209
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 210
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 211
++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 212
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.
Suggested Reading:
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)
Strings 213
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
#include<stdio.h>
main()
int i=0;
while(str[i]!=\0)
if(i%2==0)
printf(%c,str[i]);++i;
Strings 214
char str[][10]={BLUE,RED,ORANGE,GREEN,YELLOW}
puts(str[2]);
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
Strings 215
Comprehensive Questions:
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.
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
Strings 216
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.
8.20 Write a program to copy its input to its output,replacing each string of one or more blanks by a
single blank
8.21 Write a program to copy its input to its output,replacing each tab by \t and each backslash by \\ .
8.22 Write a program to print all input lines that are longer than 80 characters.
8.23 Write a program to remove trailing blanks and tabs from each line of input and to delete entairly
blank lines.
8.24 Write a function reverse(s) that reverses the character string s,use it to write a program that reverse
input a line at a time.
8.25 Write a program detab that replaces tabs in the input with the proper number of blanks to space to
the next tab stop. Assume a fixed set of tab stops , say every n columns.
8.26 Write a program to fold long input lines in to two or more shorter lines after the last non-blank
character that occurs before the nth column of input .
8.27 Write a function htoi(s) which converts a string of hexadecimal digits(including an optional 0x or
0X) into its equivalent integer value.The allowable digits 0 through 9 ,a through f,and A through
F.
8.28 Write a function that deletes each character in string s1 that matches any character in the string s2.
Strings 217
Chapter - 9
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 .
The declarations of the variables with the new data type names would be as follows:
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
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
typedef struct
{
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;
Note that in the second form of variable declaration, the keyword struct is not required because
STUDENT is the name of the structure data type.
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.
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
If the number of initializers is less than the number of fields, like in arrays, the structure members will be
assigned null values, zero for integers and floating point numbers, and null(\0) for characters and
strings.
Example 9.7
Since there are no initial values for gender and cgpa, they are initialized with null and zero respectively.
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
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 members 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 members 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 ++;
Program 9.1 program to read and display the data of a student consisting of id_number, name,age and
cgpa.
typedef struct
{
long int id_no;
char name[20];
int age;
float cgpa;
}STUDENT;
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
Before
y=x
After
char
Structures Unions and Enumerated Datatypes
nam 223
e[20
x==y, x!=y, x&&y
Program 9.2 Define a structure COMPLEX whose fields are the real and imaginary parts of a complex
number. Write a program to read two complex numbers through keyboard and find their sum.
#include<stdio.h>
typedef struct
{
float real;
float imaginary;
}COMPLEX;
void main()
{
COMPLEX z1,z2,z3;
printf(Enter the real and imaginary part of first complex number:);
scanf(%f%f,&z1.real,&z1.imaginary);
prinf(Enter the real and imaginary parts of second complex number:);
scanf(%f%f,&z2.real,&z2.imaginary);
z3.real=z1.real+z2.real;
z3.imaginary=z1.imaginary+ z2.imaginary;
printf(Sum of given complex numbers=(%.2f,%.2f)\n,z3.real,z3.imaginary);
}
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 is an array of structures of the type struct STINFO .To access the data for one student, we refer to
the array name with the subscript.
stary[0].rno, stary[1].rno, stary[2].rno etc will refer the roll numbers of first, second and third students.
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];
stary[i]=stary[i+1];
stary[i+1]=temp;
}
printf(ROLL NO \t \t NAME \t \t MARKS1 \t MARKS2 \t MARKS3 \t TOTAL \n\n);
for(i=0;i<n;++i)
printf(%d\t%s\t\t%6.2f\t%6.2f\t%6.2f\t%6.2f\n,stary[i].rno,stary[i].name,
stary[i].marks1,stary[i].marks2,stary[i].marks3,stray[i].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.
Write a program to read the Id.Number and marks in six subjects of a list of students, find the total marks
of each student, and display all the above student details in tabular form.
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;
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.
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:
baby .dob
baby .dob.day
baby .dob.year
baby .tob
baby .tob.hour
baby .tob.min
baby .tob.sec
Nested structure Initialization
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.
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)
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.
Program 9.7 Program to find the modulus of a complex number.
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);
}
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>
COMPLEX product(COMPLEX z1 , COMPLEX z2);
void main()
{
COMPLEX z1,z2,z3;
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;
return(z3);
}
In the above program the structure variables z1 and z2 are passed to the function by value. Within the
function product(), the product of the complex numbers is obtained and is stored in local variable z3of
the function product(). The value of z3 is returned to the called function and is assigned to the local
variable z3of main().
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
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.
4. The function print_num() is written to display a complex number.
5. To accesses the members of the structure through the pointer the indirection operator() is used,
which has the highest precedence along with . , ( ) and [ ] operators.
6. The expressions pz real and pz imaginary are used to access the values of the structure members.
7. In the expressions &pz real and &pz imaginary the operator & apply on the members real and
imaginary but not on the pointer pz.
Size of structure
The operator sizeof can be used to find the size of a defined structure data type . The expression
sizeof(struct ex)
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 store at the same memory address
rno/id_number
student_id
rno/id_number
The rules for referencing a union are identical to those for structures. To reference individual fields
within the union we use the dot operator. When a union is being referenced through a pointer, the
arrow operator can be used.
x.rno and x.id_number canbe used to refer the union members rno and 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 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)
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.
enum day holiday, birthday;
scanf(%d%d,&holiday,&birthday);
printf(%d\t%d, holiday, birthday);
if the input is
12
The output is
1 2
Note that SUNDAY is a string, where as SUNDAY is an enumerated type identifier.
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 and 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.
Both the dot(.) and arrow() operators will have highest precedence along with () and [ ].
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.
Suggested Reading:
#include<stdio.h>
main()
{
struct ex
{
int a;
float b;
char ch;
};
printf(No of bytes allotted for the structure=%d, sizeof(struct ex));
}
a) No of bytes allotted for the structure = 3
b) No of bytes allotted for the structure = 7
c) No of bytes allotted for the structure = 8
d) No of bytes allotted for the structure = 12
3. Consider the following declaration
struct ex
{
int rno;
char name[20], gender;
float height;
};
struct ex p;
How many bytes of space is allotted for the structure variable p if the program is run on a 16 bit
machine.
a) 4 b) 24 c) 27 d) 28
ANSWERS:
Comprehensive Questions
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
To send data (input)into the program and
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 14 #include<stdio.h> x=5
void main( )
{ FILE *fp1, *fp2;
int x;
fp1=fopen(INPUT.DAT, r);
Input fp2=fopen(RESULT.DAT, w); Output
(from the file) f scanf(fp1, %d, &x ); (To the file)
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 49 16.33
11 Gopi 20 18 15 53 17.67
where
fp is a file pointer which is of structure data type FILE defind 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 reading and writing data
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( ) fp STUDENT.IN
{
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>
void main( )
{ fp STUDENT.IN
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.
INPUT.DAT RESULT.DAT
5 7 10 11 13 14 Example1.c x=5
#include<stdio.h>
void main( ) Output
Input { (To the file)
(Through file) . fputc(), fputs(), fprintf()
fgetc(), fgets(), fscanf() .
.
.
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
High level file I/O functions are basically C standard library functions and are easy to use. Most of the C
programs handling files use these because of their simple nature. Low level file I/O functions are file
related system calls of the underlying operating system. These are relatively more complex in nature
when compared to high level file I/O functions but efficient in nature. The following are the high level
file I/O functions
Character data oriented functions
String data oriented functions
Mixed data oriented 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. Write a 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 .Write a 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 characters i.e. by a space, a tab or a new line.
#include<stdio.h>
void main()
{
FILe *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( )
{ STUDENT.IN
FILE *fp; 25 RAMU 450
char name[30] = RAMU;
int rollno = 25;
float total_marks = 450;
fp = fopen(STUDENT.IN , w );
fprintf( fp, \n%d\t%s\t%f, rollno, name, total_marks);
fclose(fp);
}
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
The function reads data values in a given format from the file pointed by fp and returns the data values,
which are collected by the variable list.
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.
Program10.12: Define a structure emp with members as empno, name and salary. Write a program to
read information for n number of employees and write this data to the file EMP.DAT. Later read the
data from the file and display on standard output
#include<stdio.h>
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.
Suggested Reading: