You are on page 1of 121

C and Data Structures – Unit I

ALGORITHMS
composed of a finite set of steps, each of which may
require one or more operations.
Each operation must be definite meaning that it must
be perfectly clear what should be done.
Each operation should be effective, in the sense that
it can at least in principle be done by a person in a
finite amount of time.
It produces one or more outputs and may have zero
or more inputs which are internally supplied.
Algorithm should terminate after a finite number of
operations.
Algorithms are also called as computational
procedure.

A program is the expression of an algorithm in a


programming language.

Examples:
(1) Write an algorithm for determining the largest of
three numbers:
Step 1: Start
Step 2: Read A, B.
Step 3: if(A>B) then if(A>C) then print ‘A’;
stop
else print ‘C’; stop
else if(B>C) then print ‘B’; stop
else
print ‘C’; stop;

1
C and Data Structures – Unit I

(2) Write an algorithm for verifying


sin3A = 3SinA - 4sinA
Step 1: start
Step 2: Read A
Step 3: X < - 3*A
Step 4: T < - sinX
Step 5: M < - 3*sinA
Step 6: N < - 4*sinA*sinA*sinA
Step 7: W<-M-N
Step 8: if(W=T) then print ‘valid’
else
print ‘invalid’
Step 9: stop;

(3) Write an algorithm to compute the sum of first


hundred natural numbers:
Step 1: start
Step 2: sum <-0; N<-1
Step 3: sum<-sum+N
Step 4: N<-N+1
Step 5: if(N>100) then print sum
else
go to step 3
step 6: stop

2
C and Data Structures – Unit I

(4) Write an algorithm to print the sum of all even


numbers between 100 and 200
Step 1: start
Step 2: I<-100 ; sum<--0
Step 3: sum <--sum + I
Step 4: I<--I+2
Step 5: if(I>200) then print sum
else
go to step 3
Step 6: stop

(5) Write an algorithm for finding the maximum of


‘N’ numbers
Step 1: start
Step 2: Read N
Step 3: Read X(1), X(2),.......................X(N)
Step 4: Max <---X(1)
Step 5: J<----2
Step 6: if X(I) > Max then
Max <--X(I)
Step 7: I<--I+1;
Step 8: if (I>N) then print ‘Max’
else
go to step 6
Step 9: stop

3
C and Data Structures – Unit I

(6) Write an algorithm to count non - zero numbers in


a set of ‘N’ numbers
Step 1: I<- 1, count <-0
Step 2: Read Number
Step 3: if (Number! = 0) then count <-- count +
1
Step 4: I <-- I+1
Step 5: if(I > N) then print ‘count’
else
goto step 2
Step 6: stop

(7) Write an algorithm for determining whether the


given number has exact square root or not
Step 1: Read Number
Step 2: I <-- 1
Step 3: K<-- Number / 2
Step 4: if (I*I = Number) then
Print ‘ Has exact square root ‘
goto step 7
Step 5: I <-- I+1
Step 6: if (I>K) then print ‘ Does not have exact
square root’
Step 7: stop

4
C and Data Structures – Unit I

FLOW CHARTS
When a problem is programmed for a computer, it is
essential to work out in detail all the decisions to be
taken by the machine and the actions to be performed
and the sequence in which these are to be performed.
Flow charts and decision tables aid this planning.
A flow chart depicts in a pictorial form the sequence
in which conditions are to be tested and calculations
performed for solving a problem.

FLOW CHART SYMBOLS:


Parallelograms are used to represent input and output
operations.
Rectangles are used to indicate any processing
operations such as storage and arithmetic.
Diamond shaped boxes is used to indicate questions
asked or conditions tested based on whose answers
appropriate exits are taken by a procedure. The exits
from the diamond shaped box are labeled with the
answers to the questions
Rectangles with rounded sides are used to indicate
the beginning or the end of a procedure.
A circle called connector is used to join the different
parts of a flow chart.
Arrows indicate the direction to be followed in a
flowchart.

5
C and Data Structures – Unit I

SYMBOL NAME
Oval

Parallelogram

Rectangle

Diamond

Circle

Polygon

Polygon is used for a group of instructions or steps


detailed in some other flow chart.

6
C and Data Structures – Unit I

(1) Draw a flow chart for determining the largest of


three numbers:
Start

Read A,B,C

is
Yes A>B No

Yes is No Yes is No
A>C B>C

Print Print Print Print


A C B C

Stop

7
C and Data Structures – Unit I

(2) Draw a flow chart for verifying Sin 3A = 3SinA -


3Sin3A
Start

Read A

X=3*A

T = Sin X

M = 3 * Sin A

N = 4 * Sin A * Sin A * Sin A

W=M-N

No is
T=W

Print in valid Print valid

Stop

8
C and Data Structures – Unit I

(3) Draw a flow chart for printing the sum of first 100
natural numbers.
Start

Sum ←0

N ←0

N ←N+1

Sum ← Sum + N

is
N≥ 100

Print Sum

Stop

9
C and Data Structures – Unit I

(4) Draw a flowchart to complete the Compute the


scalar product of
n
∑ xiyi
i = 1.

Start

Read x1, x2, x3....xn


y1, y2, y3....yn

Sum ←0
I ←1

Term ← XI * YI

Sum ← Sum + Term

I ←I+1

is
I>N

Print
Sum

Stop

10
C and Data Structures – Unit I

Program Development Tools


Feasibility study
Concerned with evaluating and comparing costs and
benefits of a computer system.
The output of this phase is called a feasibility
document, and is simply a recommendation to the
user to proceed or not to proceed with the
development of such a document is an extremely
computer process and involves subject matter well
beyond computer science alone, including business,
management economics and accounting.
Problem specification phase
Sometimes known as requirements specification
involves developing a clear, concise and
unambiguous statement of the exact problem to be
solved.
Problem design phase
Any large, computer project must first be divided into
a set of smaller and less complex subtasks in order to
be managed and completed effectively. Otherwise the
job would be too large to comprehend and follow.
It basically involves decomposing the problem
statement into a set of simpler modules and data
structures, which, if they existed, would correctly
solve the problem.

11
C and Data Structures – Unit I

The result of this decomposition will be a program


design document that lists:
1. Every module used in the solution.
2. The structural relationship of that module to other
modules.
3. The interface specifications of that module (i.e. the
face it shows to the rest of the program).
4. The operations and functions carried out by these
modules.
5. The abstract data types that will be used.
6. The operations that will be performed on these
abstract data types.
Module design
Once we know, exactly what pieces are needed to
solve the problem, we can begin to implement the
modules one by one.
The first step is to select the method for solving the
problem and the internal representation of the
abstract data types that we have specified.
We can use algorithm or a flowchart to design our
module, which are introduced later on in this lesson.
Coding
This is the step that most people immediately think of
when they think of program. However a great deal of
preparatory work precedes this step.
If this preparatory work has been done well, then
coding simply becomes the mechanical translation of
algorithmic statements with in a module into the
syntax of some programming language.

12
C and Data Structures – Unit I

Debugging
Concerned with the location and correction of all
errors that cause the program to produce incorrect
results or perform improper actions.
This is the most frustrating, agonizing and time-
consuming step in the overall programming process.
The reason for this could be the lack of time spent on
careful planning, organising and structuring the
solution.
One thing to remember about debugging is the very
best technique is to avoid making mistakes in the first
place.
Testing and verification
Involves demonstrating that the program is
theoretically correct and will work properly on all
data, even those that have not been explicitly tested.
With testing, we select a large number of test cases
and run the program using these data. If the program
produces correct results for this collection of test
data, we can say that it will work properly on all test
data.
With verification techniques, we argue in a more
formal, mathematical or logical sense to prove that
the program P will produce the correct output O, for
all input data I. Verification is much more complex
than simple testing, but it allows us to make much
stronger claims about the correctness of the program.

13
C and Data Structures – Unit I

Documentation phase
Involves developing and writing the supporting
manuals and on-line assistance, which the user will
need to understand and use the finished program
effectively.
Program maintenance
Operation of adapting a program to keep it correct
and current with changing specifications and near
equipment.
If the program has been well organised and well
planned, has been carefully designed as a set of
independent modules, has been well coded, and is
clearly documented, then program maintenance will
be a less difficult task.
TOP DOWN DESIGN METHODOLOGY
Top down programming (design) is a program design
technique that describes a high level problem in
technique that describes a high level problem in
terms of more elementary subtasks.
Through the technique of stepwise refinement we
then expand and define each of these separate
subtasks until the problem is solved.
Each subtask is tested, verified before it is expanded
further.
The principles of top-down modular programming
are based on decomposing a problem into a hierarchy
of tasks, and then developing the solution from the
highest level down to the lowest.

14
C and Data Structures – Unit I

The higher levels are concerned with the broad


problems to be solved, while the lower levels become
more and more concerned with the details of how we
can actually achieve it.
The solution develops in a download “developing
tree” as shown below:
P1
o

P11o oP12 oP13

P111 o o o o o o P121o o
P112 P113 P121 P122 P131 P132
In top down programming, the original problem is
described in terms of a reasonable small number of
subtasks, which if they existed and were performed in
the correct order, would solve the original problem.
This operation of tasking a problem step and defining
it in terms of more elementary sub problems is called
stepwise refinement.
The stepwise refinement process terminates when a
subtask is so simple it need not be expressed in terms
of any new subtasks but can be coded directly in the
primitives of the language.
The problem solution is developing from the highest
levels downward, so that we are always “on top” of
the problem.
We always know, where we are heading and what
needs to be done.

15
C and Data Structures – Unit I

The advantages of top-down technique are:


1. Increased intellectual manageability and
comprehension
2. Abstraction of unnecessary lower-level details.
3. Delayed decisions on algorithms and data
structures until they are actually needed.
4. Reduced debugging time.
EXERCISES
1. Write an algorithm and draw a flowchart to
determine the number of points in each quadrant
from a set of 50 co-ordinates.
2. Given 100 pairs of length and breadth of
rectangles obtain an algorithm to find all the
rectangles whose area is greater than their perimeters.
3. Write an algorithm to determine whether a given
number is prime or not.
4. Write an algorithm to determine the sum and
product of the digits.

16
C and Data Structures – Unit I

The character set


The characters are used to form words, numbers and
expressions.
The characters in C-are grouped into four categories:
1. Letters.
2. Digits.
3. Special Characters.
4. White Spaces.
Letters
Uppercase A.....Z.
Lowercase a......z.
Digits
All decimal digits 0.....9.
Special characters
, Comma
! exclamation mark
. Period
/ Slash
; Semicolon
~ Tilde
: Colon
$ Dollar sign
? Question mark
% Percent sign
“ Quotation mark
# Number sign
& Ampersand

17
C and Data Structures – Unit I

White spaces
Blank space
Horizontal Tab
Carriage return
Newline
Form feed.
In C-language uppercase and lowercase letters are
distinct.
C-Forms
Individual words of the text are called as forms.
There are six types of tokens.
The programs are written using these tokens and the
system of the language.
Forms
(i) Keywords (ii) Identifiers
(iii) Constants (iv) Strings
(v) Operators (vi) Special symbols.
Identifiers and keywords
Every word of ‘C’ is known as a keyword or an
Identifier.
Every keyword has fixed meaning and these
meanings cannot be changed.
Keywords act as basic building blocks of program
statements.
The rule for writing a keyword is that it should be
written in lowercase.

18
C and Data Structures – Unit I

ANSI C - Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers are defined as the manes of the variables
and other program elements like function names,
arrays etc., basically user defined names using the
combination of sequence of letters, and digits with a
letter as first character.
Both uppercase and lowercase letters can be used for
identifiers.
The underscore character “_” is also permitted in
identifiers.
Usually it is used to form a link between two words.
Note: Keywords are reserved words and hence
they should not be used as identifiers.
Data Types
C-language has a quite a few data types.
The variety of data types available allows the
programmer to select the type appropriate to the
needs of the application.

19
C and Data Structures – Unit I

ANSI C supports four classes of data types:


1. Primary or fundamental data types.
2. User defined data types.
3. Derived data types.
4. Empty data types.
All the C-Compilers support the following
fundamental data types.
integer (int)
character (char)
floating point (float)
double precision floating point (double).
In addition there are number of qualifiers that can be
applied to these basic types, like short, long, signed,
unsigned.
Integer types
These are whole numbers, which support both
positive and negative values, within a range.
The range is dependent on the word size of the
machine generally 16-bits or 32-bits.
If we use 16-bit word size the range will be -215 to
215-1 i.e. -32768 to +32767 (one bit is reserved to
represent the sign).
In addition to this, we may have, short int, long int, in
both signed and unsigned forms.
Generally short int requires half the storage space, as
that is required for regular int.
Unsigned integers are only positive numbers.
Therefore there range be greater compared to that of
signed integers.

20
C and Data Structures – Unit I

In short, the keywords used to defined integer values


are: int, short int, long int, unsigned int, unsigned
short int, unsigned long int.
Floating Point types
These are numbers, which contain fractional parts
either positive or negative.
The keyword used to define float variable is float.
They are usually stored in 32-bits with 6 digits of
precision.
When the accuracy provided by the float number is
not sufficient the type double is used to define the
number.
A double data type number stores the data in 64-bits
with a precision of 14 digits.
The data type of the number is same as that of the
float.
To further extent the scope of double we may use
long double.
An example of float value is 34.12
Character types
A character can be defined as a character (char) typed
data.
They are usually stores in 8-bits of storage.
With signed char the range is from -128 to +127.
However with unsigned char the range will be 0 to
255.

21
C and Data Structures – Unit I

The sign and ranges of various data types are shown


for a 16-bit machine.
Type Size Range
Char or signed char 8 -128 -- +127
Unsigned char 8 0 -- 255
Int or signed int 16 -32768 -- + 32767
Unsigned int 16 0 -- 65535
Short int or
Signed short int 8 - 128 -- + 127
Unsigned short int 8 0 -- 255
Long int or -2,147,483,648 --
Signed long int 32 2,147,483,647
Unsigned long int 32 0 -- 4,294,967,295
Float 32 3.4E-38 -- 3.4E+38
Double 64 1.7E-308 -- 1.7E+308
Long double 80 3.4E-4932-1.1E+493.

Constants
Constants in ‘C’ are fixed values that do not get
change during the execution of a program.
Numeric constants are again divided into integer
constants and floating-point constants.
Integer constants
Do not contain decimal points.
Consists of sequence of digits.
Integer constants can be decimal, octal, or
hexadecimal.
Decimal integer constants consist of digits 0 through
9.

22
C and Data Structures – Unit I

Embedded spaces, commas, and non-digit characters


are not permitted between digits.
Examples: 456, 784, 0, + 789.
Octal constants
integer numbers of base 8 i.e. digits 0 -- 7.
In C, it is preceded by the character 0 (zero).
Examples: 037, 0435.
Hexadecimal constants
numbers of base 16 and their digits are from 0 to 9
and A to F or (a to f).
Normally it is preceded by ox.
Examples: ox 3
ox 9F
Note: it is possible to store large integer constants by
appending qualifiers such as 4.
Example: 567894, 9876543214.
Real constants
They usually have a decimal point and the fractional
point. It is possible to omit digits before and after the
decimal point.
Example: 0.0054, 276.0, -0.75, 217.0, 095, 215.
A real constant may also be expressed in exponent
from:
Example: 217.87e2 means 217.87x102.

23
C and Data Structures – Unit I

The general form is mantissa e exponent

Mantissa can be decimal number or an integer, but


exponent is an integer number with an optional plus
or minus sign.
Note: No white space is permitted after the symbol e,
i.e., 7.1e 5 is not a valid Real constant.
Character constants
divided into two categories
(a) single character constants
(b) String constants.
Single character constants
Contains a single character enclosed within a pair of
single quote marks ‘’.
Examples: ‘5’, ‘a’
Every character constants associated with a single
ASCII value.
String constants
sequence of characters enclosed in double quotes.
The character letters, digits or other special
characters.
Examples: “Hello”, “1998”, “?..!”, “8”.

24
C and Data Structures – Unit I

Escape sequence constants


There are special backslash character constants.
They are preceded with ‘\’(backslash).
These sequences look like two characters, but
represent only one.
Examples:
‘\a’ bell character ‘\v\ vertical
‘\b’ backspace ‘\\’ backslash
‘\f’ formfeed ‘\?’ question mark
‘\n’ newline ‘\’’ Single quote
‘\r’ carriage return ‘\”’ double quotes
‘\t’ horizontal tab ‘\o’ null
In addition to these, an arbitrary byte-s pattern can be
specified by ‘\000’, where 000 is one to octal digits.
‘\xhh’ where hh is one or more hexadecimal digits.
Variables and Declarations
A variable is a value holder.
It is used to store a data value.
The values of the constants remain unchanged during
the execution of the program.
But a variable (may) take different values during the
execution of the program.
Note: Since the programmer selects every variable
name, it is advisable that meaningful names
should be selected for the variable names to
improve the clarity of the program and it also
helps in easy maintenance.

25
C and Data Structures – Unit I

Rules to be followed for naming a variable:


• May consists of letters, digits and the underscore
character.
• Must begin with a letter or under score character.
Should not begin with digits.
• ANSI standard permits the length up to 31
characters. Normally one should not exceed the
length to more than 8 characters.
• Uppercase and lower cases are distinct. I.e. Sum
is not the same as sum.
• It should never be a keyword.
• White spaces are not allowed. It should be a
continuous stream of characters.
Examples:
ravi, kapil, x1, y1, distance are all valid variables.
Some of the invalid ones are: 12Hello, (Khan, % etc.
Note: Programmers should be careful, when the
length of the variable names is restricted to 8
characters. In such cases, averageheight and
averageweight would be treated as same.

26
C and Data Structures – Unit I

Declaration of variables
All variable s must be declared before use, although
certain declarations can be made implicitly by
content.
A declaration specifies a data type and contains one
or more variables of the type.
The general form is
data-type V1, V2, V3....Vn;

Variables are separated by Commas.


Every declaration statement must end with a
semicolon.
Examples: int lower, upper;
int right, left;
char c, b, d;
float sum, average;
float total;
The declaration of variables is usually done at the
beginning of the program.
Note: When an adjective or qualifier like short, long
or unsigned used without a basic data type
specifier, it will be treated as int by default.

27
C and Data Structures – Unit I

User-Defined Type Declaration


This facility allows the user to define an identifier
that would represent an existing data type.
This feature is known as type definition.
The keyword used to achieve this is typedef.
Remember this will not create a new data type.
It just gives another name to the existing data types.
General syntax is
typedef type identifier;

where ‘type’ refers to an existing data type and


‘identifier’ refers to the new name given to the data
type.
Example: typedef int newint;
typedef char newchar;

Here newint and newchar represents int and char.


They can be further used to declare variables of the
basic data type.
They represent in typedef like
newint b1, b2;
newchar c, d;
then b1 & b2 represents integer (int) and C & C
represent character variables (char).

28
C and Data Structures – Unit I

Another user-defined data type is ‘enum’


Syntax:
enum identifier {value1, value2,.....value n}
Identifier is a user-defined enumerated data type
which can be used to declare variables that can have
one of the values enclosed within the braces.
After this we can declare variables of type identifier
as
enum identifier V1, V2,....Vn;
The variables V1, V2....Vn can have only the values
Value1, Value2,....Value n;
Example: enum colour {red, green, blue, yellow};
enum colour my-colour, your-colour;
my-colour = blue;
your- colour = yellow;
The compiler assign integer digits beginning with
zero to all the enumeration constants, i.e. Value 1 is
assigned 0, Value2 is assigned 1 and so on.
However the default assignments can be overridden
by assigning values explicitly to the enumeration
constants.
Examples: enum colour{blue=1, yellow, green};

29
C and Data Structures – Unit I

Arithmetic Operators & Expressions


An operator is a symbol that tells the computer to
perform certain mathematical or logical
manipulation.
They are used to manipulate data and variables.
The various categories of operators are:
• Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Increment and decrement operators
• Conditional operators
• Bit wise operators
• Special operators.
Arithmetic operators
The arithmetic operators +, -, /, *, does work in the
same way as they do in other languages.
+ Addition
- Subtraction or unary minus
* Multiplication
/ Division
% modulo division (gives the remainder)
The operators can be applied to the variables and
constants as operands.

30
C and Data Structures – Unit I

Expressions
An expression is a combination of variables,
constants and operands following the syntactic rules
of the language.
The impressions can be again classified according to
the operators present in them as arithmetic
expressions or logical expressions etc.
Every valid expression yields a value, which can be
assigned to a variable.
Precedence of arithmetic operators
An arithmetic expression without parenthesis will be
evaluated from left to right using the precedence
rules of operators.
The priority of arithmetic operators is high priority is
given to *, /, % and then low priority is given to +, -.
High priority operators are evaluated first followed
by low priority operators.
Mixed-Mode Arithmetic
Generally in an expression, same type of operands
like integer or real (float) is used and hence type of
the expression will be accordingly real or integer.
But sometimes, we can have one operand as real and
the other as integer in an expression. Such an
expression is called a mixed-mode expression.

31
C and Data Structures – Unit I

Assignment Statement (operator)


Assignment operators are used to assign the result of
an expression to a variable.
The assignment operator is “=”.
In addition to this “C” has a set of shorthand
assignment operators of the form.
Variable op=exp;
op is a binary arithmetic operator; exp is an
expression.
This is equivalent to variable = variable op
expression;
Various Assignment operators
operation meaning
= Assign right hand value to the left hand
side
+= Value of left-hand side variable is
added to the value of right hand and
assign back to the variable of the left.
-= Value of right hand variable will be
subtracted from the value of left-hand
and assign back to he variable of left
hand side.
*= Same as above except that it is
multiplied.
/= Same as above except that it is divided.
%= The remainder will be stored back in the
LHS.

32
C and Data Structures – Unit I

Examples of arithmetic statements:


a = b + c * d -2;
c = 2 + 5 * 5 + d;
d = d/5 is known as d /=5;
n + 3; is same as n = x+i’
Symbolic constants
It is a well-known fact that some constants appear in
the program at various places like Pi, e, etc. If by
chance we need to change the value of such
constants, then we have to change at each and every
place in the program where it is defined.
Therefore we face the problem of Modifiability and
understandability (∴ it is not always clear when the
same value means different things at different
places).
We can use symbolic constants to get rid of this
program, by assigning the constant value to the
symbolic constant identifier.
The syntax is
#define symbolic-name values of constant

Valid examples are


#define PI 3.14159
#define STRENGTH 50
#define PASS-MARKS 40
where #define is called the pre-processor statement.

33
C and Data Structures – Unit I

Rules of symbolic constants


• Same rules are to be followed as those of
variable names.
• No blank space between define and # is
permitted
• A blank space is required between #define and
symbolic name.
• #define statement should not end with
semicolon.
• After definition the symbolic name should not be
redefined in the program.
• They may appear anywhere in the program.
Structure of a C program
C programs are essentially constructed in the
following manner, as a number of well defined
sections:
/* Header section */
/* Contains name, author, revision number */
/* Include Section */
/* Contains #include statements */
/* Constants and types section */
/* Contains and types and #defines */
/* Global variables section */
/* any global variable declared here */
/* Functions section */
/* Any user defined functions declared here */
/* main () section */

34
C and Data Structures – Unit I

First C Program
main ()
{
printf (“Welcome to C programming”);
}
Every program should have only main () function.
This is the place where the program execution begins.
The opening brace ‘{‘ indicated the beginning of
main program and the closing brace indicates the end
of the program. All the statements between these two
braces from the body of the function, which contains
a set of instructions to perform the given task.
This program contains only one statement printf ()
with a message to be printed.
The lines beginning with /* and ending with */ are
comment lines, which are non-executable.
When you run this program, the message “Welcome
to C programming” will be displayed on the screen.
Example 2
main ()
{
int a;
float b;
a = 10;
b = 5.5;
printf(“%d %d”, a, b);
}

35
C and Data Structures – Unit I

This program has a declaration section, where we


have declared two variables ‘a’ and ‘b’ of type int
and float.
Then we have an initialisation section, where we
have initialised a & b to 10 & 5.5. Followed by
printing the values of a & b, using printf () statement.
Note: It is possible to assign the initial values to the
variable in the declaration as
int a = 10;
float b = 5.5;
Declaration variable as a constant
If you want the value of the variable to remain
constants during the execution of a program, qualify
it with a qualifier const at the time of initialisation as
const int rank = 40, which tells the compiler that the
value of the int variable rank must not be modified by
the program.
Volatile variables
Used to tell explicitly to the compiler that a variables
value may be changed at any time by some external
sources (from outside the program).
Example:
volatile int date;
The value of date may be changed by external
environment even if it does not appear on the left
hand side of an assignment statement.

36
C and Data Structures – Unit I

Exercises
(1) An identifier in ‘C’
(a) is a name of an entity such as variable and
function.
(b) is made up of letters, numerals and the
underscore character.
(c) an contain both uppercase and lowercase
letters.
(d) all of the above.
(2) Which are the following are the valid character
constants.
(a) ‘\n’ (b) ‘\\’ (c) ‘\0’ (d) all the above
(3) An expression
(a) is a collection of data objects and operators that
can be evaluated to a single value.
(b) is a name that substitutes for a sequence of a
characters.
(c) causes the computer to carry out some action
(d) all the above.
(4) The statement I*3; is equivalent to
(a) I=3*; (b) I=3; (c) I=*3; (d) i=i*3;
(5) A character variable can at a time store
(a) 1 character (b) 8 characters
(c) 254 characters (d) none of the above
(6) A ‘C’ variable cannot start with
(a) An alphabet (b) A number
(c) A special symbol (d) both (b) & (c)

37
C and Data Structures – Unit I

(7) Which of the following is incorrect.


(a) m = 125.56; (b) ch = ‘T’ * ‘A’;
(c) t = ‘T’ * 20; (d) 5 + t = b;
(8) Which of the following is incorrect.
(a) Each new statement has to be written on a
separate line
(b) usually all C statements ate entered in small
case.
(c) Blank spaces may be inserted between two
words in a C statement.
(d) Blank spaces cannot be inserted within an
integer variable.
(9) The expression x = 4+2%8 evaluates to
(a) +6 (b) 6 (c) 4 (d) 0.
(10) Precedence (Hierarchy) decides which operator
(a) is important
(b) is fastest
(c) is to be used first
(d) operates on largest numbers.
(11) Which of the following are the invalid variable
names
Minimum My Name a+b
&hello doubles sum
$n Rows float
int Sum Total

38
C and Data Structures – Unit I

(12) Find errors if any, in the following declarations


int x;
double = p, x;
m, t : int;
int m; count;
(13) What would be value of x after the execution of
the following block of statements?
int x, y = 10;
char t = ‘b’;
x = y + t;
(14) Define a constant TRUE which a value of 1.
(15) Declare two integer variable x, y and initialise
the variable y to 1000, in the declaration itself,
also declare a double variable money and a
character variable ch and initialise t to null
character.
(16) Divide the variable total by 100 and leave the
result in the variables dividend.
(17) Assign the sum of two variables even-count and
odd-count to total-count.

39
C and Data Structures – Unit I

Data - Input & Output


I/O functions: printf, scanf, getchar, putchar, gets,
puts.
Formatted and Buffered output: printf()
We have seen the use of printf () function to perform
the printing of messages and the values of the
variables on the output device like monitor, in a
given format.
The string gives this format, which is the first
argument of printf.
This string is known as the control string, specifies
what to print and also how to print (i.e. the format).
The printf () statement provides certain features that
can be effectively exploited to control the alignment
and spacing of printouts on the terminal.
The general form of printf () function is
printf(“control string”, arg1, arg2, arg3,....argn);
control string may contain:
• characters that may be printed as it is on the
screen
• Format specifications that define the output
format for display of each item. The format
specifications like %d, %c, %f, etc.
• Escape sequence characters like \n, \t, \b.

40
C and Data Structures – Unit I

Note: The arguments and the format specifications


should match in number, type and order. i.e.
for each argument you should have one format
specification.
The general form of format specification is
% m n type specifier
where ‘m’ is an integer specifying the total number of
columns for the argument value, and ‘n’ is another
integer specifying the number of digits to the right of
the decimal point or the number of characters to be
printed from a string. Both m and n are optional.
Printing integers
The format specification is %wd, where w specifies
the minimum field width.
If the number is greater than the width, it will be
printed in full ignoring the width.
The number is printed right justified.
Example:
printf(“%d”, 6543); would print as
6 5 4 3
printf(“%6d; 6543); would print as
6 5 4 3
with minus sign, you can force it to print left
justified, as
printf (“%-6d”, 6543);

6 5 4 3

41
C and Data Structures – Unit I

Note: long integers may be printed with ‘ld’


specified. As printf(“%ld”, x);
where x is declared as long int type.
Printing float values
The format is %m, n f
Examples
y = 45.6789;
printf (“%7.4f”, y)
4 5 . 6 7 8 9
printf (“%7.2f”, y)
4 5 . 6 8
Note that if the no. of digits after the decimal point
are more than if is specified in the specifier then it is
rounded and printed left justified.
Printing a character
The format specifier is %wc, which will display the
character right justified in the field of ‘w’ columns.
However with minus sign it will be displayed left
justified.
The default value for w is 1.
Example:
char xyz = ‘c’;
printf(“%c”, xyz);
would point character ‘c’ on the screen.

42
C and Data Structures – Unit I

Printing strings
The format specification for printing strings is similar
to that of real numbers.
%m, n, s
Mixing all the specifications
It is allowed to mix the data in one printf statement.
Example: printf (“%d %f %c %s”, x, y, z, t);
printf uses its control string to decide how many
variables to be printed and what their types are.
In summary, the format specifications used in printf()
function for the various data variables are:
Code Format
%c a single character
%d decimal numbers (integers)
%f floating values
%e floating with e-notation
%o Octal
%x hexadecimal
%s string
%u unsigned decimal
%ld long integer
%p print memory address value.

43
C and Data Structures – Unit I

Example 1:
main ()
{
int x = 100, z = 200;
float y = 205.75;
char c= ‘d’;
printf(“x=%d y = %f c=%c”, x, y, c);
printf(“%d + %d = %d”, x, z, x+z);
}
The first printf would print the values of x, y & c.
The second printf would print the sum of x & z.
The first %d will be for x, the second will be for and
the this will be for x+z.
Note that the format specifies could be used as
arguments to the binary operators.
Example 2:
main( )
{
int x = 78;
printf (“\n x in decimal is %d”, x)’
printf (“\n x in Octal is %o”, x);
printf (“\n x in Hen is %x”, x);
}
The first printf() would print he value 78.
The second one would print on the newline because
we have a ‘\n’ the value of x is octal.
The third statement would print the value of x in
hexadecimal form on the newline.

44
C and Data Structures – Unit I

Formatted and Buffered Input


Scanf formatted input means reading the data, which
is arranged in a particular format.
The syntax is same as that of printf statement.
scanf(“control string”, arg1, arg2,....argn);
The control string specifies the field format in which
the data is to be entered and the arguments arg1,
arg2,...argn specify the address of locations where the
data is to be stored.
The control string as usual contains the format
specifications, consisting of conversion character %
and a data type character.
Reading integers
Field specification is %wd, where ‘w’ is the width of
the number to read, ‘d’ denotes integer type.
Examples: scanf (“%2d %5d”, &a, &b);
Data to be read: 40 31233
Then the value 40 will be assigned to variable a &
31233 to b.
If the length of the number is greater than the width
specified, then only those many digits will be taken
from the number as specified in the width.
Suppose in the previous example, instead of 40, if we
give it as 31245 then 31 would be assigned to and
245 to b.
Therefore it is advisable that width should not be
specified in the scanf to avoid such errors.

45
C and Data Structures – Unit I

Tabs, spaces or newline characters must separate


input data.
Note: Every integer, character and float variable in
the argument of scanf should be preceded with
&(ampersand) which denotes the address of
that variable).
Since scanf function reads the values in the
variables location.
If it is not preceded with &, then the value will
not be read into the variable and you may get
erroneous results.
However for reading strings with %s, the ‘&’
symbol or address operator is not needed.
Remember this point very carefully.
Sample program illustrating use of scanf () to read
integers, characters, and float.
main( )
{
int sum;
char letter;
float money;
printf (“enter the integer value”);
scanf (“%d”, & sum);
printf (“enter a character”);
scanf (“%c”, & letter);
printf (“enter a float value”);
scanf (“%f”, & money);
printf (“the values you entered were \n”);
printf (“value of sum = %d \n”, sum);

46
C and Data Structures – Unit I

printf (“value of letter = %c \n”, letter);


printf (“value of money = %f\n”, money);
}
Sample output:
enter an integer value
42
enter a character
K
enter a float value
48.5
The values you entered were
value of sum = 42
value of letter = K
value of money = 48.500000
The program illustrates several points.
• The ‘C’ language provides no error checking for
user input. The user is expected to enter the correct
data type. For instance, if a user entered a character
when an integer value was expected, the program
may enter an infinite loop or abort abnormally.
• Its up to the programmer to validate data for
correct type and range the values.
getchar ( ), putchar ( );
Even though all input/output operations are carried
out through function calls such as printf, scanf.
There exist several functions that have become
standard for input and output operations in C. These
functions are known as standard I/O library.

47
C and Data Structures – Unit I

Note: Each program that uses a standard input/output


function must contain the statement
#include <stdio.h>
usually at the beginning of the program, stdio.h is an
acronym for standard input-output header file.
Reading a character with a getchar
getchar ( ) reads a character from the standard input
unit usually keyboard.
The general form is
variable-name = getchar ( );
variable-name must be of char type.
Sample program:
#include <stdio.h>
main ( )
{
char ans;
printf (“enter Y or n:”);
ans = getchar ( );
if (ans = ‘Y’)
printf (“you have typed Y”);
else printf (“you have typed N”);
}
sample output
Enter Y or N = Y
you have typed Y

48
C and Data Structures – Unit I

Writing a character with putchar( );


putchar( ) put a character supplied as an argument on
the monitor screen.
Syntax:
putchar (variable-name);
where variable-name is of type char.
Sample program to read a character and prints it on to
the screen (echoing);
#include <stdio.h>
main( )
{
char alpha;
printf(“enter a character”);
alpha = getchar( );
putchar(alpha);
}
Output:
Enter a character: K
gets ( ) and puts ( )
The gets () and puts () are used to read a string of
characters and print a string of characters called
arrays.
Preprocessor statements
The preprocessing is done before complication of the
program by the C preprocessor.
The ‘C’ preprocessor provides the tools that enable
the programmer to develop programs that are easier

49
C and Data Structures – Unit I

to develop, easier to read, easier to modify, and easily


portable.
It can also serve as customising the language.
Preprocessor statements are identified by the pound
sign “#” which must be the first character on the line.
#define statement:
#define TRUE 1
defines the name TRUE and makes it equipment to
the value 1.
TRUE could be used anywhere in the program where
the constant 1 could be used.
Whenever this name appears, its value i.e. 1 will be
automatically substituted into the program by the
preprocessor.
Uses of #define
Program extendibility: If the constant value ends to
be changed or modified then only define symbolic
constant needs to be changed. We need not change
the value at each and every place in the program.
Program portability: Helps to make programs more
portable from one computer to another. Sometimes it
may be necessary to use constant values that are
related to the particular computer that the program is
running on. It may need to access a particular
memory address or the number of bits contained in a
computer word. Then this can be done by using
#define statement.

50
C and Data Structures – Unit I

Advanced type definitions


A definition for an identifier can include more than a
simple constant value.
It can include an expression.
Example: #define TWO-PI 3.14159
In ‘C’ definitions are also known as macros.
Macros often take one or more arguments.
Example: #define square (x) x * x
enables us to write statements of the form
y = square(v);which will assign the value of v2 to y.
The #include statement
The preprocessor enables one to collect all of our
definitions into a separate file and then include them
in your program.
Suppose if we have some common declarations then
we can forma header file with /h extension and
include it in our program.
Any program that subsequently needed to use any of
the definitions contained in the header file say
values.h could do so by writing the pre-processor
directive
#include “values.h”.
The double quote sign instruct the pre-processor to
look for the specified file in the same file directory
that contains the source file.

51
C and Data Structures – Unit I

If the file is not found there, then the pre-processor


will automatically search other directories as set up
by the system manager like /usr/include on UNIX.
Excluding the file name within < > as in #include
<stdio.h> has the same effect, except that the file
directory that contains the source file is not searched.
Note: Whenever we use any standard system supplied
function like getchar( ), putchar( ), getch ( ), and
mathematical functions like sqrt ( ), floor( ), ceil( )
their declarations are given their standard header
files and to use them, we should include the
corresponding header file in the program like
#include <stdio.h>, #include <math.h> etc.
It is permitted to have more than one file included in
a program.
In such cases, separate #include statements must be
used.
If a statement contained in one include file references
a value defined in another include file, then the latter
file must be included in the program first.
include files can be nested, i.e. include file can itself
include another file, and so on.
Conditional compilation
#ifdef, #endif, #else, #ifndef.
Conditional compilation is often used to have one
problem that can run on different computer systems.
It is also to switch on or off various statements in the
program, such as debugging statements that print out

52
C and Data Structures – Unit I

the values of various variables are trace the flow of


program execution.

53
C and Data Structures – Unit I

If we have the definition in a program


#define INT-SIZE 16
So this program meant to sum on 16-bit machine if
we want to run the program on a 32-bit machine, then
this would have to be changed to 32, as
#define INT-SIZE 32
If we have a large program that had many such
dependencies on the particular hardware of the
computer system, then we might have many defines
whose values would have to be changed when the
program was moved to another computer system.
We can reduce this program of having to change
these defines when the program is moved by using
conditional compilation as shown below:
#ifdef IBMPC
#define INT-SIZE 16
#else
#define INT-SIZE 32
#endif
will have the effect of defining INT-SIZE to 16 if the
symbol IBMPC has been previously defined and to
32 otherwise.
If the symbol on the #ifdef line has been already
defined either through a #define statement or through
the command line then the lines up to #else or #elif or
#endif are processed. Otherwise they are ignored.

54
C and Data Structures – Unit I

We can define the symbol IBMPC to the pre-


processor as
#define IBMPC 1
or even
#define IBMPC
is enough.
In UNIX, the name IBMPC can also be defined when
the program is compiled by using -D option shown
below:
$cc-D IBMPC fl.c.
Similarly we can use the statement #ifndef to mean if
not defines, the syntax of it is same as that of #ifdef.
We can even have nested if else using #elif.
#if MACHINE = 1
#elif MACHINE = 2
#elif MACHINE = 3
#else
#endif
The #undef statement means undefined.
In order to remove the definition of a particular
name, the statement.
#undef sum
can be used, which will remove the definition of sum,
from the system.
In such cases, all subsequent #ifdef or #if defined
statements would be evaluated to false.

55
C and Data Structures – Unit I

Preparing, running and compiling a C program


There are series of steps involved in executing a ‘C’
program.
1. Editing the program with an editor.
2. compiling the program
3. linking the program with the libraries.
4. Executing or Running the program.

Start

to edit the program

compile the source


program

Yes errors
any

No

link file.o

libraries and Execute


object modules

No Correct
output

Yes
stop

The flowchart given depicts these processes in detail,


even though these steps are operating system
dependent, but the functionality remains the same.
However we shall discuss the procedures to be

56
C and Data Structures – Unit I

followed in executing C programs under UNIX and


MS-DOS operating systems.
UNIX System
The first step is creating the program.
This can be done with a standard editor like ed or vi.
The filename can be valid characters, like letters
digits and special characters followed by a dot and a
small letter c.
Examples of file name
sum.c
average.c
my-program.c
The file an be opened and created with vi editor as
$ vi my-program.c
Then we type the source code.
After which we save the file and come out of the
editor.
After editing the phase, we compile the program by
using the command cc as
$cc my-program.c.
If there are any errors, they will be displayed
otherwise the object code will be created in
my-program.o.
The linking in UNIX is automatically done with cc
command.
The executable code is placed in a out file.

57
C and Data Structures – Unit I

The program can now be run as


$a.out
Note: If we use any mathematical functions in the
program, then we may have to link them as
$ cc f.c -im.
We can even create our own executable code file
rather than a.out by using the following cc option.
$ cc .-o filename source-file
Example: $ cc -o my-result my-program.c
the executable code would be placed in the file my-
result.
We can even just compile the file without linking by
using
$ cc - c mod.c
This would create object file mod.o, which have to be
linked again by using cc command as
$cc mod.o
It is also possible to compile multiple source files by
using
$ cc f1.c f2.c f3.c
This would create an executable file a.out.

58
C and Data Structures – Unit I

The various options of cc and their meaning:


Option meaning
-c compilation and no linking only .o (object code
file) is created.
-f If the machine does not have floating point
hardware then this option is used.
-o file Executable object code is placed in file
rather than a.out.
-lx The string x is an abbreviation for a library that
is to be searched. If we want to use a
function from a library other than lib then
this option is included.
-D name defines the indicated name to the pre-
processor, with the indicated definition.
DOS Operating System
Microsoft and Borland provide many IDE
environments.
The standard compiler in DOS environment is tc or
Turbo C and bc or Borland C.
From the prompt by typing tc, we enter into an
integrated development environment with possible
mouse interface.
It has user-friendly options to edit, compile and link.
Editing, compiling and linking the programs are
much more easier in IDE environment of DOS
compared to command line features of UNIX
operating systems.

59
C and Data Structures – Unit I

Exercises
(1) Which function would you use if a single key
were to be received
(a) scanf (b) gets (c) getchar (d) none
(2) If an integer were to be entered through a
keyword, which input function would you use?
(a) scanf (b) gets (c) getchar (d) printf( )
(3) A field width specifier in a printf() function
(a) controls the margins of the program listing.
(b) specifies the maximum value of a number.
(c) controls the size of types used to print numbers.
(d) specifies how many columns will be used to
print the number.
(4) If a character string s to be received through the
keyboard which function would you use.
(a) scanf( ) (b) gets( )
(c) getchar( ) (d) all the above can be used
(5) #directives may be present (recommended)
(a) before the main function
(b) after the main function
(c) at the end of the program
(d) anywhere in the program.
(6) The single character I/O functions are
(a) scanf( ) & printf( )
(b) getchar & putchar( )
(c) scanf( ) & putchar( )
(d) getchar( ) & printf( )

60
C and Data Structures – Unit I

(7) Which of the following is correct.


(a) scanf (“%f”, float-variable);
(b) scanf (“%d & sum”);
(c) scanf (“%d”, & sum);
(d) scanf (“%d”, & n);
(8) Use printf statement to print out the float variable
sum using two decimal places.
(9) Use a single scanf statement to read an integer
variable code, float variable salary and a character
variable sex.
(10) Write a program to read the values of a, b, c &
print the results of the following expressions.
(a) a+b+c (b) a+b+c (c) (a+b+c)*(a-b-c)
a+b-c 2
(11) What is a pre-processor directive?
(a) A message from compiler to the programmer.
(b) A message from compiler to the linker.
(c) A message from programmer to the pre-
processor.
(d) A message from programmer to the
microprocessor.
(12) Which of the following is/are correct.
#define INCH PER FEET 15
#define sqr(x) (x * x)
#define SQR(x) * n * x

61
C and Data Structures – Unit I

(13) How many #include & #define can be there in a


program file.
(14) Give the output of the following program
#define product(n) (n * x)
main( )
{
int i = 10, j, k;
j = product (i++);
k = product (++i);
printf (“%d %d”, j, k);
}
(15) A header file is
(a) A file containing the declarations of standard
library function.
(b) A file containing the definitions of standard
library function.
(c) A file containing user defined functions.
(d) A file present in the current directory.

62
C and Data Structures – Unit I

OPERATORS AND EXPRESSIONS


Unary, Logical, Bit wise and conditional operators
Unary operators
The + and - are the two unary operators.
They take only one operand and they are preceded to
the number.
Example: -14, +8, etc.
Relational operators
The various relational operators are
<  is less than
<=  is less than or equal to
>  is greater than
>=  is grater than or equal to
==  is equal to
!=  is not equal to
The relational operators are used to compare two
quantities and then depending on their relation certain
decisions are made.
An expression containing relational operators is a
relational expression.
Example: a< b
1<2
The value of a relational expression is always either
one or zero.
It is one if the relation is true and zero if it is false.
Example: 100 < 300 is true

63
C and Data Structures – Unit I

200 < 50 is false

The general form of a relational expression is:


arith-expr rel-op arith-expr
When arithmetic expressions are used on either side
of a relational operator, then the expressions will be
evaluated first and then the comparison takes place.
Arithmetic operators have higher priority over
relational operators.
Relational expressions are used in decision making
constructs like if - else, while , for , etc. .
Logical operators
C has the following logical operators
&& → logical AND
| | | → logical OR
! → logical NOT
The operators && and | | are used to test more than
one condition.
A compound expression is true when two conditions
(expressions) are true.
Syntax
expr1 && expr2
where expr1 and expr2 are expressions .
The result of logical operator && is
true && true → true
true && false → false
false && true → false
false && false → false
64
C and Data Structures – Unit I

Example: (a > b && x == 100)


The result of this compound relational expression is
true if a > b is true and x == 100 is also true other
wise it is always false.
Similarly the results of logical OR operator are
true | | true → true
true | | false → true
false | | true → true
false | | false → false
Example: a = 10 ; b = 5; c = 8;
(a < b | | b > c )
10 < 5 | | 5 > 8
false | | false
false
In the logical OR operator, if one of the expression is
true, then it yields true.
NOTE: In a compound relational expression with a
first logical OR operator, if the first expression is
evaluated to true, then we need not evaluate the
remaining expressions, as irrespective of their
values being true or false, the final value of the
expression will be true. This technique is called
short-circuiting.

65
C and Data Structures – Unit I

Logical NOT operator


It is used to change the value from true to false and
from false to true.
The results of logical NOT (negation) operator is:
!(true) → false
!(false) → true
Example: a =4 ;b = 5; c = 6;
!(a > b) | | ( b > c)
!(4 >5 ) | | (5 > 6)
!(false) | | (false)
true
Precedence rules
The NOT operator has a higher precedence over
logical AND and logical OR.
Parenthesis are usually used to reduce unexpected or
ambiguous results.
The logical AND has higher precedence over logical
OR operator.
The expression
exp1 | | exp2 && exp3 | | exp4
will be evaluated as
exp1 | | ( exp2 && exp3 ) | | exp4
Example: a = 4, b = 5, c = 7
(a < b) | | (b > c) && (a > b) | | (a > c)
(true) | | (false) && (false) | | (false)
(true) | | (false && false) | | (false)
true | | (false) | | (false)
true | | false
true
66
C and Data Structures – Unit I

See that this expression is evaluated to


((a < b) | | (b > c)) && (( a >b) | | (a > c))
Bit wise operators
There are the low-level operators, which are applied
to the binary bits.
C supports the following bit wise operators:
Bit wise AND
Denoted by & (ampersand) carried out between the
two bit patterns of the variable.
Example: Let us say we have two variables with
values x = 5 and y = 3.
Their binary values will be 0101 & 0011
respectively.
Then the bit wise and of x and y denoted as x & y is
(0101 & 0011) the result is 0001 = 1.
To generate a 1 bit in the result, bit wise AND needs
a 1 in both numbers.
This is usually done for masking hits.
Bit wise OR
Denoted by |.
It is similar to bit wise AND and the result is 1, if any
one of the bit value in the number is 1.
Example: x = 5, y = 3
x | y =(0101) | (0011) = (0001) = 7

67
C and Data Structures – Unit I

Bit wise Exclusive –OR ---


Denoted by ∧ performs the operation X Y + X Y.
Example: x = 5, y = 2
x ^ y = (0101) ^ (0010) = (0111) = 7
Bit wise complement
Denoted by ∼ .
Complements or switches all the bits in a binary
pattern, i.e., all the binary zeroes become ones and
ones becomes zeros.
Example: x = 33 → 0011 0011
∼ x = cc → 1100 1100
Shift operators
The shift operators take binary patterns and shift the
bits to the left or to the right, keeping the same
number of bits by dropping shifted bits off the end
and filling in with zeroes from the other end.
C provides the two types of shift operators: left shift
and right shift.
Left shift
Denoted by <<
The syntax is
variable1 << variable2
The bit pattern of variable1 is to be left shifted by the
value of variable2 times.

68
C and Data Structures – Unit I

Example: x = 10
x << 3 ( 1010 << 0011)
1010
1010
0100
1000
∴ The result will be 1000 (8).
Right shift
Denoted by >> and the contents will be shifted right.
Example: y = 6 ( 0110 )
y >> 2
0011
0001
∴ The result will be 0001 (1)
Conditional operator
Also known as ternary operator.
Denoted by ?.
The general format of this is
Expression1 ? Expression2 : Expression3
which results in expression 2 or expression 3 being
evaluated.
If expression 1 is true, then expression 2 is evaluated,
otherwise expression 3 is evaluated.

69
C and Data Structures – Unit I

Example: a = 100; b = 150;


t = ( a > b ) ? a : b;
means, if a > b then t will be assigned a , other wise b
will be assigned to t .
This is as good as writing
if( a > b) then
t = a;
else
t = b;
Increment and decrement operators
Increment operator
Denoted by ++ (double plus).
Used for incrementing by 1.
There are two types of increment operators: pre and
post increment.
++ i is pre-increment and i ++ is post-increment.
If written alone as a distinct statement, both gets
evaluated to i = i + 1
i.e., ++ i & i ++ ⇒ i = i + 1
The meaning of pre increment is that, first the value
is incremented and then the required operation is
performed, where as in post increment, first the
operation is performed with the present value and
then the value is incremented.

70
C and Data Structures – Unit I

Example:
suppose i = 7, then if we have a statement x = ++i;
first the value of i is incremented to 8 and then it is
assigned to x.
∴ After execution, the value of x & i will be 8.
Where as if we have x = i++; with the present value
of i = 7, then the present value of i is assigned to x
and then the value of i is incremented to 8.
∴ After execution x =7 and i = 8.
Decrement operator
Denoted by -- (double minus).
The functionality of it is same as that of increment
operator, except that it subtracts the value by 1.
--i, and i-- is same as i = i - 1;
Like increment operator, we have pre decrement and
post decrement operators.
Example:
say x = 8;
z = -- x;
After execution i = 7 and x = 7
say y = 10;
z = y --;
After execution z = 10 and y = 9;

71
C and Data Structures – Unit I

Special operators
The comma operator
The first use of a comma is as a separator in the
variable declaration like int a, b, c;
Another use of comma operator is to link the related
expressions together.
A comma list of expressions is evaluated left to right
and the value of the combined expression.
Example: value = (t=10, b=18, t+b+5);
First assigns the value 10 to t, then 18 to b and finally
t+b+5 i.e. 33 to value.
Comma operator has the lowest precedence, of all
operators, therefore parentheses are necessary.
The sizeof operator
It is compile time operator, it results the number of
bytes the operand of it requires. The operand can be a
variable, a constant or a data type qualifier.
Example: m = sizeof (number);
n = sizeof (longint);
k = sizeof (FF);
Uses of size of
• An determining the lengths of arrays, structures
etc., when their sizes are not known.
• To allocate memory space dynamically to
variables during execution of a program.

72
C and Data Structures – Unit I

Type conversions in expressions


Automatic conversion
C allows mixing of constants and variables of
different types in an expression.
During evaluation it converts them to a particular
type.
The general rule is that, if the operands are of
different types, the lower type is converted to the
higher type before the operation proceeds. The result
is of higher type.
Some of the rules are
• All short and char are automatically converted to
int.
• If one is long double then the other will be
converted to long double and the result will be long
double.
• Same rule applied for double and float.
• If one of the operands is unsigned long int, the
other will be converted to unsigned long int and the
result will be unsigned long int.
NOTE: The final result of an expression is converted
to the type of the variable on the left of the
assignment sign before assigning value to it.
• Float to int causes truncation of the
fractional part.
• Double to float causes rounding of digits
• Long int to int causes dropping of the excess
higher order bits.

73
C and Data Structures – Unit I

Type casting
The cast operator is used to convert from one type to
another.
The cast operator syntax is
(cast-type) expression;
Example: result = (int) (29.2/4);
The (int) operator casts only (29.2) & the result will
be 7.
char ch;
int x, y, z;
x = (int) ch;
forces to convert the character to integer type.
SUMMARY OF C OPERATORS
Operator Meaning Associativity
() Function call Left to Right
[] Array element reference Left to Right
→ Pointer to structure Left to Right
Member reference Left to Right
Structure member reference Left to Right
− Unary minus Right to Left
++ Increment Right to Left
−− Decrement Right to Left
! Not Right to Left
∼ One’s complement Right to Left
* Pointer reference Right to Left
& Address Right to Left
sizeof Size of object Right to Left
type Type conversion Right to Left
* Multiplication Left to right

74
C and Data Structures – Unit I

/ Division Left to Right


% Modulus Left to Right
+ Addition Left to right
− Subtraction Left to Right
<< Left shift Left to right
>> Right shift Left to Right
< Less than Left to right
<= Less than or equal to Left to Right
> Greater than Left to Right
>= Greater than or equal to Left to Right
== Equality Left to right
!= Not equal to Left to Right
& Bitwise AND Left to right
∧ Bitwise EXOR Left to Right
| Bitwise OR Left to Right
&& Logical AND Left to right
 Logical OR Left to Right
?: Ternary (conditional) Right to Left
= += −= Assignment Left to right
∗= /= %=

75
C and Data Structures – Unit I

LIBRARY FUNCTIONS
The standard libraries are used to perform some
predefined operations on characters and strings etc.
There are many library functions for performing
different functions.
Most of the C compilers support the following
standard library facilities.
• Operations on characters
• Operations on strings
• Mathematical functions
• Input / Output functions
• Storage allocation functions
The declarations (prototypes) are placed in the header
files.
math.h
abs(x) Gets the absolute value of its argument
acos(x) Determines the Arc cos of x.
asin(x) Determines the Arc sin of x
atan(x) Determines the Arc tan of x.
ceil(x) Rounds its argument up to an integer.
cos(x) cos value of x , x in radians.
cosh(x) Hyperbolic cosine.
exp(x) Calculates ex
floor(x) Truncates x to an integer.
log (x) Determines Natural logarithm of x.
log10x Log to base 10 of x.
pow (x, y) calculates x raised to y.
sqrt (x) Calculates the square root of x.

76
C and Data Structures – Unit I

Functions of string.h
strcat(dest, source) Appends the contents of the
source string to the
destination string.
strcpy(dest, source) Copy the contents of the
source string to the
destination string
strcmp(dest, source) Compares source and
destination strings.
If dest < source returns -1
if dest = source returns 0
if dest > source returns 1
strncpy(dest, source, n) Copy exactly ‘n’ characters
from source to destination.
Functions of ctype.h
isalnum(ch) Checks whether ‘ch’ is an alphanumeric
character.
isalpha(ch) Checks whether ‘ch’ is an alphabet
iscntrl(ch) Checks whether ‘ch’ is a control
character.
isdigit(ch) Checks whether ‘ch’ is a digit
islower(ch) Checks whether a given character
belongs to a lower case alphabetic
character
isprint(ch) Checks whether a given character is a
printable (visible) character.
isspace(ch) Checks for white space character.
isupper(ch) Checks whether ‘ch’ is upper case
character.

77
C and Data Structures – Unit I

In all the above functions, if it matches then a


nonzero value is returned, incase of failure zero is
returned.
tolower(ch) Converts ‘ch’ to lowercase.
toupper(ch) Converts ‘ch’ to uppercase.
Other header files
assert.h
conio.h
dir.h
fcntl.h
float.h
limits.h
signal.h
stdlib.h
time.h
process.h
io.h
sysstat.h
stdio.h
mem.h

78
C and Data Structures – Unit I

EXERCISES
(1) Evaluate the following expressions:
a. g = b/2 + b * 4/b - b + a/3 ( a=1.5, b=3)
b. s = q*a/4-6/2+2/3*6/g; (q=2 , a =4 , g = 3 )
(2) Convert the following equations to C statements
z=9.8(a+b+c)z/t - 1.5+4b/(q + t)/(a+b)*(b-c)
t = -b + √b2-4ac / 2a
R = 2v + 1.6 g / (2a) / g + v.
(3) Give the output of the following program
segment:
int i = 2, j = 3,k,l;
float a, b;
k = i / j * j;
l = j / j *i;
a = i / j * j;
b = j / i * I;
printf (“ %d %d %f %f “ ,k, l, a, b);
(4) Which of the following shows the correct
hierarchy of arithmetic operations in C.
a. ( ) , ** ,* , / ,+ or - b. ( ) , * or | , + or -
c. ( ) , ** , | , * ,+ , - d. NONE

79
C and Data Structures – Unit I

(5) Give the output of the following programs:


a. main ()
{
int i = 10, j = 15;
if( i == 5 || j > 50 )
printf (“ I AM IN YES BLOCK “);
else
printf (“ I AM IN NO BLOCK “);
}
b. main()
{
int I = 4, j= -1, k = 0, w, x, y;
w = i || j || k;
x = i && j && k;
y = i || j && k;
printf(“%d %d %d”, w, x, y);
}
(6) Give the output of the following programs:
a. main()
{
int i = - 4 , j , num;
j = ( num < 0 ? 0 : num * num);
printf(“%d” , j);
}
b. main()
{
int k, number;
number = 50;
k = (number>5 ? (number<10 ? 100 : 200) : 500);
printf( “ %d %d “ , k ,number);
}

80
C and Data Structures – Unit I

(7) What does the following program print?


main()
{
int x = 1, y = 1, z = 1;
x+=y+=z;
printf(“%d”, x < y ? y : x );
printf(“%d”, x < y ? x++ : y++);
printf(“%d %d “,x ,y );
}
(8) Give the output of the following program.
main()
{
int x , y , z;
x = y = z = 1;
++x || ++y && ++z;
printf(“%d %d %d”, x , y, z);
x = y = z = 1;
++x && ++y || ++z;
printf(“%d %d %d”,x, y, z);
x = y = z = -1;
++x && ++y || ++ z;
printf(“ %d %d %d”, x, y, z);
x = y = z = -1;
++x || ++y && ++ z;
printf(“ %d %d %d”, x, y, z);
}

81
C and Data Structures – Unit I

CONTROL STATEMENTS
Decision making and Branching: If-else, switch,
break & continue
Normally the set of statements are executed
sequentially in a C program. But in practice, we
come across situations; where we may have to
change the order of execution of statements based
on certain conditions, i.e. break the normal flow of
sequential control.
This involves a kind of decision making to see
whether a particular condition has occurred or not
and then direct the control to execute certain
statements accordingly.
C supports such decision-making by providing the
following decision-making control statements:
• If statement
• Switch statement
These two are conditional branching statements.
There are some unconditional branching constructs
like goto, break and continue.
If statement
It is used to control the flow of execution of
statements.
It is a two-way decision statement, which is used in
conjunction with an expression.

82
C and Data Structures – Unit I

The general format is


if (expression)
{
Statement block;
}
Next statement;
If the expression is true, the statement block will be
executed, otherwise the statement block will be
skipped and the execution continues with next-
statement.
When the condition is true both the statement-block
and next-statement are executed as shown below:

True
Expression

False Statement block

Next-statement

Example 1: Program to print the square root of a


positive number.
#include<math.h>
main()
{
int numb;
printf (“ Enter a Number”);
scanf (“%d”, &numb);
if (numb > 0)
printf(“%d\n”, sqrt(numb));
}

83
C and Data Structures – Unit I

Note: If there is only one statement present in the


statement block of the if statement, then the
block delimiters namely { and } may be ignored
as illustrated in the previous example.
Example 2:
main()
{
int n1, n2, n3;
float f1;
printf ( "Enter three integers" );
scanf ("%d%d%d", &n1, &n2, &n3);
if (n3 > 0)
{
f = (n1 + n2 ) / n3;
printf (“The ratio of n1 & n2 to n3 is %f”,
f);
}
}
We can even have a compound relation in the test
condition of if statement like
if (age > 25 && weight >= 60)
count = count + 1;
This can be equivalently written with two nested if
statements as
if(age > 25)
if (weight >= 60)
count = count +1;

84
C and Data Structures – Unit I

The if-else statement


This is an extension (Enhancement) of simple if
statement.
The general form of it is
if (expression)
{
true-statements
}
else
{
false-statements
}
next-statement;
The flow chart is

False true
Expression
?

False statements True statements

Next Statement

If the expression is evaluated to true, then the true-


statements are (is) executed.
Otherwise, the control comes to else block of
statements.

85
C and Data Structures – Unit I

Example: To print the largest of two numbers


main ()
{
int x,y;
printf ( "Enter two integers" );
scanf ("%d%d", &x, &y);
if (x > y)
printf ("x is the largest");
else
printf ("y is the largest");
}
Nesting of if-else statements
When a series of decisions are involved, we may have to
use more than one if-else construct in nested form:
if (condition1)
{
if (condition2)
{
s1;
}
else
{
s2;
}
}
else
{
s3;
}
s4;

If condition1 is false then s3 will be executed


followed by s4; If it is true, then condition2 is tested

86
C and Data Structures – Unit I

if it is true then s1 is executed followed by s4;


otherwise s2 is evaluated followed by s4.
When nesting of if-else is involved, care should be
taken to match every if with an else or vice-versa.
Otherwise, ambiguities may result.
Example:
if (code == 1)
{
if (rate > 0.2)
cost = 0.5 * balance;
else
cost = 0.2 * balance;
}
else
{
cost = 0.2 * balance;
}
balance = balance + cost;

87
C and Data Structures – Unit I

Instead of writing the program that way, if we


mistakenly write it like this,
if (code == 1)
if(rate > 0.2)
cost = 0.5 * balance;
else
cost = 0.2 * balance;
balance = balance + cost;
There is a clear ambiguity as to which if the else
belongs, whether to if (code==1) or to if (rate>0.2).
In C, we link the else to the innermost and hence it
is associated with the second if statement.
In order to associate the else with the outer if we
may have to write the block as
if (code == 1)
{
if(rate > 0.2)
cost = 0.5 * balance;
}
else
cost = 0.2 * balance;
balance = balance + cost;

88
C and Data Structures – Unit I

Example: This program selects the largest of three


numbers.
main()
{
int x, y, z;
printf ( "Enter any three numbers");
scanf ("%d%d%d", &x, &y, &z);
if (x > y)
{
if (x > z)
printf ( "%d is largest", x);
else
printf ( "%d is largest", y);
}
else
if (y > z)
printf ("%d is largest", y);
else
printf ("%d is largest", z);
}

89
C and Data Structures – Unit I

The Else-if ladder


The else-if ladder is a multipath decision chain of ifs
in which the statement associated with each else is
another if statement.
The general form is:
if (cond1)
s1;
else
if (cond2)
s2;
else
if (cond3)
s3;
else
if (cond4)
s4;
……
……
else
if (cond n)
sn;
else
default;
next-statement;
In the above ladder, the next-statement after the first
if statement is next-statement.
Therefore, after executing each of si, i.e., either s1
or s2 … or sn the control comes to the next-
statement.

90
C and Data Structures – Unit I

You might well realize that using the else-if ladder


is cumbersome and not organized way of
programming.
You should always try to eliminate the usage of
else-if ladder since even if one is mismatched and to
make the problem more complex if you have pair of
parenthesis, then it will be very difficult to match
them and ultimately we may even get wrong results.
One-way of avoiding such nesting is by using
switch statement.
Example: To print the months based on the month
number.
main ( )
{
int month;
printf ( "enter a number between 1 & 6");
scanf ("%d", &month);
if (month == 1)
printf ("January");
else if (month == 2)
printf ("February");
else if (month == 3)
printf ("March");
else if (month == 4)
printf ("April");
else if (month == 5)
printf ("May");
else if (month == 6)
printf ("June");
else

91
C and Data Structures – Unit I

printf ( "I know only six


months");
}
Some of the sample if-else constructs are:
1. if (expr) 2. if (expr)
{ {
if (expr)
{
} ___
else ___
{ }
else
{
}
}
}

92
C and Data Structures – Unit I

3. if (expr) {
if (expr) {
….
….
}
else {
……
____
}
}
else {
if (expr) {
_____
_____
}
else {
____
____
}
}

93
C and Data Structures – Unit I

Example: Simple calculator program


#include <stdio.h>
main ( ) {
int invalid-operator=0;
char operator;
float number1, number2, number3, result;
printf("enter two numbers and an operator in the format
\n");
printf ("number1 operator number2 \n");
scanf("%f % c %f", &number1, &operator,
&number2);
if (operator == '*')
result = number1 * number2;
else if (operator == '+')
result = number 1 + number2;
else if (operator == '-')
result = number1 - number2;
else
invalid-operator = 1;
if (invalid-operator !=1)
printf("%f%c%f=%f", number1, operator, number2,
result);
else
printf ("invalid operator \n");
}
Sample program output:
enter two numbers and an operator in the format
number1 operator number2
23.2 + 12
23.2 + 12 = 35.2

94
C and Data Structures – Unit I

The switch-case statement


We have seen that when more than one alternatives are
available to make a selection, we have to use multipath if-
else of else if ladder, which increases the complexity of
the program.
It becomes difficult to read and understand. Sometimes it
may confuse even the programmer who has designed it.
To get rid of this problem, we use what is called as a
switch-case statement, which is a built in multi way
decision statement.
The switch statement tests the value of a given variable or
expression against a list of case values and when a match
is found, a block of statement associated with that case is
executed.

The general form of switch statement:


switch (expression) {
case value 1:
block-1;
break;
case value 2:
block-2;
break;
…….
case value n:
block-n;
break;
default :
default-block;
break;
}
next-statement.

95
C and Data Structures – Unit I

The 'expression' is an integer expression or can be a


character value1, value2, ……. are constants or
constant expressions known as case labels.
The types of case labels and expression should
match block1, block2 are zero or more statements.
When the switch is executed, the value of the
expression is compared against the values value1,
value2, ……..
If a case is found whose value matches with the
value of the expression then the corresponding
block of statements is executed.
The break-statement at the end of each block
denotes the end of a particular case and causes an
exit from the switch statement, transferring the
control to the next-statement after the switch
statement.
The default statement is optional case, if the value
of the expression doesn't match with of the case
labels, then the statements within the default case
will be executed.

96
C and Data Structures – Unit I

Example: To print the month based on its number now


with switch statement.
main( ) {
int month;
printf("Enter a number between 1 and 6");
scanf ("%d", &month);
switch(month)
{
case 1:
printf ("January");
break;
case 2:
printf ("February");
break;
case 3:
printf ("March");
break;
case 4:
printf("April");
break;
case 5:
printf ("May");
break;
case 6:
printf ("June");
break;
default:
printf("I know only the names of six
months");
}
}

97
C and Data Structures – Unit I

Example 2: The calculator program with the case-


switch statement.
#include <stdio.h>
main ( )
{
char operator;
float number1, number2, result;
printf("enter two numbers and an operator in this
format\n");
printf ("number1 operator number2");
scanf("%f%c%f", &number1, &operator,
&number2);
switch (operator)
{
case '*' :
result = number1 * number2;
break;
case '+' :
result = number1 + number2;
break;
case '-' ;
result = number1 - number2;
break;
default ;
printf ("invalid operator");
}
}

98
C and Data Structures – Unit I

Exercises:
1. Write a program to determine whether a number
is odd or even.
2. Write a program to find the largest of four
numbers.
3. Write a program to solve the quadratic equation to
check all possibilities of their coefficients
ax2+bx+c=0
Note: In the case labels of the switch statements if
the break statement is missing, then the
subsequent statements present in the next case-
label if any will be executed.
Goto Statement
So far we have seen the branching using if-else or
switch statements based on some conditions, hence
these statements are also called as conditional
statements.
Another way of branching to break the sequential
flow of control is unconditional branching i.e.
without testing any condition we branch to a
statement.
This is achieved by using the goto statement of C.
Although it may not be essential to use the goto
statement in a highly structured language like C,
there may be occasions when the use of goto might
be desirable.
The syntax of goto is
goto label;

99
C and Data Structures – Unit I

The Goto requires a label to indicate the place of


branch in the program.
The label can be anywhere in the program either
before the goto statement or after the goto
statement:
goto label; label;
…… statement;
….. …..
….. …..
label: …..
statement goto label;
forward branch backward jump

When we come across the goto statement during the


execution of the program, the flow of control will
jump to the statement immediately following the
label.
Note: When the label is before the goto statement a
loop will be formed, and some statements will
be executed repeatedly.
If the label is after goto then some statements
will be skipped as with break statement.
Loop creation with goto statement
We can create a loop of statements that gets executed
repeatedly with goto statement.
Example:
#include<math.h>
main ( ) {
float a, b;
read: scanf ("%f", &a);
if (a < 0) goto read;
b = sqrt(a);
printf ("%f", b);
goto read;

100
C and Data Structures – Unit I

}
The program used two goto statements, one at the
end, after printing the results to transfer the control
back to the input statement and the other to skip any
computation if the number is negative.
This program puts the computer in a permanent loop
known as an infinite loop i.e., it continuously
executes the statements until we take some special
steps to terminate the loop.
While programming, care should be taken to avoid
such loops.
Examples: 1. Program to calculate the sum of
squares of all integers between 1 and 100.
main ( ) {
int sum, n;
sum=0, n=1;
loop: sum = sum + n * n;
if (n == 10)
goto print;
else
{
n++;
goto loop;
}
print: printf ("sum = %d", sum);
}

101
C and Data Structures – Unit I

2. Program to print all the numbers less then 200 that are
divisible by 10.
main ( ) {
int number;
number =1;
loop: if ((number %10) == 0))
printf ("%d\t", number);
number ++;
if (number != 200)
goto loop;
}
Decision making and looping: While, do-while, for
statements and continue statement
We have seen that sometimes it becomes essential to
repeatedly execute a segment of a program. This was
done with a goto statement, by initializing a counter and
later testing it, using the if statement.
Consider the program to calculate the sum of squares of
100 integers.
sum = 0;
n = 1;
loop: sum + = n * n;
if (n == 100) goto print;
else
{
n++;
goto loop;
}
print: printf ("%d", sum);

102
C and Data Structures – Unit I

In brief, we can say that this program does the


following:
• Initializes the variable n.
• Computes the square of n and adds it to sum.
• Tests the value of n, whether it has reached 100
or not. If so, we print the sum otherwise we repeat
the loop i by incrementing the value of n.
We can say that, in looping a sequence of statements
are executed until some conditions for termination
of the loop are satisfied.
A program loop consists of two parts, body of the
loop and the control statement.
The control statement is responsible for testing &
then terminating the loop.
Depending on the position of the testing statement
the loops can be entry-controlled loop or the exit-
controlled loop.
In the entry-controlled loop, the testing conditions
are tested before the start of the loop execution. If
the conditions are not satisfied, then the body of the
loop will not be executed.
In the case of an exit-controlled loop, the test is
performed at the end of the body of the loop
performed at the end of the body of the loop and
therefore the body is executed unconditionally for
the first time.

103
C and Data Structures – Unit I

Therefore the looping process, in general would


have the following steps.
• Initialization of counter.
• Execution of the body of the loop.
• Testing for a specified condition for execution
of the loop.
• Incrementing the counter.
In C language, there are three looping constructs, for
performing looping operations.
1. while statement
2. do-while statement
3. for statement.

While statement
The basic format of the while loop is
while (testing condition)
{
body of the loop;
}
While loop is an entry-controlled loop statement.
The test condition is evaluated and if the condition
is true, then the body of the loop is executed. After
execution of the body, the test condition is once
again evaluated and if it is true, the body is executed
once again.
This process of execution of the body is continued
until the test condition is false. Then the control is
transferred out of the loop.

104
C and Data Structures – Unit I

Note: The braces are needed only if the body


contains two or more statements. However, it
is a good practice to use braces even if the
body has only one statement.
We can rewrite the previous program using while loop as:
sum = 0;
n = 1;
while(n <= 100)
{
sum + = n * n;
++n;
}
printf ("%d", sum);
Example 1: Program to read characters from the keyboard
and print them in uppercase, until you read the character
newline.
#include<stdio.h>
main ( )
{
char ch;
ch = ' ';
while (ch ! = '\n')
{
ch = getchar ( );
if (islower (ch))
ch = toupper (ch);
putchar (ch);
}
}

105
C and Data Structures – Unit I

Example 2: Program to find the sum and average of


the given 'n' numbers using the while loop.
main( )
{
int n, number i, sum;
float average;
printf ("enter how many numbers");
scanf ("%d", &n);
i = 1;
sum = 0;
while (i <= n)
{
printf ("enter the number \n');
scanf ("%d", &number);
sum + = number;
}
average = (float) sum / n;
printf ("sum of %d numbers = %d", n, sum);
printf ("\n Their average is %f", average)
}
Do-While Statement:
This is an exit controlled looping construct, i.e., the
testing condition is placed at the end of the loop.
So, here the body of the loop is executed at least
once.
In while loop however the body of the loop is
executed atmost once.

106
C and Data Structures – Unit I

The general form of the do-while is


do {
body of the loop;
} while (test condition);
On reaching, the do statement, the program
proceeds to evaluate the body of the loop first.
At the end of the loop, the test-condition in the
while statement is evaluated.
If the condition is true, the program continues to
evaluate the body of the loop once again.
When the condition becomes false, the loop is
terminated.
Note: The test condition may have compound
relations as well, like while (number > 0 &&
number < 1000)
Example 1: Program to reverse a number.
# include<stdio.h>
main ( ) {
int number, digit;
printf ("%d", &number);
do {
digit = number %10;
printf ("%d", digit);
number = number/10;
} while (number != 0);
}

107
C and Data Structures – Unit I

Example 2: Program to print the numbers in step of


3 between 1 and 100.
main( ) {
int x;
x = 1;
do {
printf ("%d\n", x);
x += 3;
} while (x <= 100);
}
for statement
It is another entry-controlled loop, which provides a
more structured looping construct.
The general from of the for loop is:
for (initialization; test-condition; increment)
{
body of the loop;
}
First the initialization of the control variables is
done, using assignment statements such as i =1 etc.
These variables are called loop-control variables.
The value of the variable is tested using the test-
condition. The test condition is a relational
expression like i < 100 etc, which determines when
to come out of the loop. If the condition, is true the
body of the loop is executed, otherwise the loop is
terminated.
After each iteration the control is transferred back to
for statement. Then the value of the control variable
is incremented and the new value of the loop control

108
C and Data Structures – Unit I

variable is tested to see whether it satisfies the test


condition. If the condition is satisfied the body of
the loop is again executed, otherwise the loop is
terminated.
Example:
for (i = 1; i <= 10; ++i)
{
printf ("%d", i);
}
This loop is executed 10 times.
The three sections are separated by semicolon; and
there is no semicolon after the increment section.
We can even have negative increments (decrements)
like:
for (i = 10; i <= 1; --i)
{
printf ("%d", i);
}
The output is printing of 10 numbers in backward
fashion, i.e., from 10 to 1.

109
C and Data Structures – Unit I

Examples of for loops


1. Program to calculate the factorial of a given
number (n!).
main ( ) {
int number, fact, i;
printf ("enter the number for which you want to
calculate the factorial");
scanf ("%d", &number);
fact : = 1;
for (i = 1; i <= n; ++i) {
fact: = fact * i;
}
printf (" factorial of %d", number, fact);
}
2. Program to find the sum of the squares of the first
'n' natural numbers.
main () {
int i, n, sum;
printf ("enter the value of n");
for (i = 1; i <= n; ++i) {
sum + = i * i;
}
printf ("the sum is %d", sum);
}

110
C and Data Structures – Unit I

Additional features of the loop:


Comma operator
More than one variable can be initialized in the
initialization section of for loop.
If that is the case, then comma operator should separate
the variables.
for (p = 1, i = 1; i <= 20; ++i, ++p)
Note: Initialization section has two parts p=1 and I=1
separated by comma operator, also note that, there
are two increment parts ++i and ++p.
Similarly, we can have multiple test condition in the test
condition section of the for loop.
for (i = 1; i <= 20 && sum < 100; ++i);
Note: It is also possible to initialize the for loop control
variables by expressions.

Nested for loop


One for statement can be enclosed within another for
statement
Example 1:
for (i = 1; i <= 10; ++i) {
…..
for (j = 1; j <= 10; ++j) {
…..
}
…..
}
The statements with the inner for loop will be repeated for
10 * 10 = 100 times.

Example 2: Use a nested for loop to print the following


output.

111
C and Data Structures – Unit I

1
2 2
3 3 3
: : : :
n n n n n
main ( ) {
int n, i, j;
printf ("Enter the value of n");
scanf ("%d", &n);
for (i=1; i<=n; ++i) {
for (j=1; j<=i; ++i) {
printf ("%d", i)
}
printf ("\n");
}
}
The three sections of the for loop are optional. We
can ignore some of the sections depending on the
requirement.
We can ignore the initialization section and have a
for loop like this for( ; j <= 100; ++j). Similarly we
can have a for loop without increment section,
which case we assume that we increment the loop
control variable within the body of the for loop.
We can even have a for loop like for (; ;) without
any sections, which will create an infinite loop.
Note: you should not have a semicolon immediately
after the for-loop (unless you desire to create
a delay within the program), otherwise the
following statements will not be repeated.

112
C and Data Structures – Unit I

Example: for (i = 1; i <= 100; ++i);


sum = sum + i;
Then this would just repeat for 100 times and
execute the statement sum = sum + i only once.
(∴ we have terminated the for loop by the
semicolon).
continue statement
The continue statement is similar to the break
statement, except that it does not cause the loop to
terminate. Rather, this statement causes the loop in
which it is executed to be continued by skipping those
statements which are immediately after the continue
statement. Execution of the loop otherwise continues
as normal.
Usually we use continue statement to bypass a group
of statements inside a loop based upon some
condition, but to otherwise continue execution of the
loop.
The format of the continue statement
continue;

113
C and Data Structures – Unit I

Example: Program to print the sum of positive


numbers in a given set of 'n' numbers.
#include<stdio.h>
main ( ) {
int n; number, i, sum;
printf ("enter the value of n");
scanf ("%d", n);
sum : = 0;
for (i = 1; i <= n; ++i) {
printf ("enter the number");
scanf ("%d", &number);
if (number < 0)
continue;
sum + = number;
}
printf ("sum = %d", sum);
}
In a similar fashion, we can have continue statement
within the while and do-while statements.
while (test-condition) { do {
….. …
….. if (condition)
if (condition) continue;
continue; …..
….. } while (test-condition);
}

114
C and Data Structures – Unit I

Similarly we can have break statements within the


for loop, while loop and do-while loop.
while (condition1) { do {
s1; s1;
s2; s2;
: :
if (condition2)
if(condition2)
break; break;
sn; sn;
sn+1; sn+1;
} } while (condition1);
s n+2; s n+2;
for (initial-condition; test-condition; increment-
section) {
s1;
s2;
:
if (error-condition)
break;
sn;
sn+1;
}
sn+2;

115
C and Data Structures – Unit I

Jumping in loops with goto statement


We can jump within the loop and outside the loop
with the goto statement.
while (condition1) {
if (error)
goto stop;
s2;
:
if (condition2) exit from the loop
goto label;

jump within …
the loop label: si;
:
{
stop:
for (conditions)
{


for (conditions)
{

if (error)
Goto error;

}

}
error:

116
C and Data Structures – Unit I

Exercises:
1. Write a program to generate the sum and product
of the digits of the number.
2. Write a program to read a number and count the
occurance of a particular digit in it. (Ex: In the
number 1257653 the digit 5 is occurring 2 times)
3. Write a program to generate the following series:
(a) 1, 2, 3, 4, ….., n
(b) 0, 2, 4, 6, ….., n
(c) 1, 22, 32, 42, …., n2
(d) 1, 23, 33, 43, …., n3
4. Write a program to calculate ncr and npr
ncr = n! npr = n!
r!(n-r)! (n-r)!
5. The 'break' statement may be used to exit from
(a) a do-while loop (b) a for loop
(c) a switch statement (d) all of the above
6. In which statements, does a 'continue' statement
cause the control to go directly to the test
condition and then continue the loop process.
(a) do-while and while
(b) while and 'if-else'
(c) 'do-while' and 'if-else'
(d) none of the above

7. Give the outputs of the following programs:


(a) main( ) {

117
C and Data Structures – Unit I

int a = 20, b, c;
if (a >= 40)
b = 30;
c = 20;
printf("%d %d", b, c);
}
(b) main( ) {
int x=10, y=30;
if(x ! = y);
printf("%d%d%d", x, y);
}
(c) main() {
int x=3, y=10;
if(x==3)
printf ("%d", x);
else;
printf ("%d",y);
}

(d) main() {
int val = 35, k = 20;
printf("%d %d %d", k == 35, k = 50, k >
100);
}

118
C and Data Structures – Unit I

8. Given the output of the following:


(a) main() {
int j;
while (j <= 100)
printf ("%d \n", j);
j += 10;
}

(b) main() {
char x;
for(x = 0; x <= 255; ++x) {
printf ("%d %c", x, x)
}
}
(c) main( ) {
int i = 100;
while(I = 100);
printf("Infinite loop");
}
(d) main( ) {
int i;
for(i=1; i<=10);
printf("%d", i);
i++;
}

119
C and Data Structures – Unit I

(e) main( ) {
int i = 1, j = 1;
for ( ; ;) {
if (I > 5)
break;
else
j += i;
printf ("%d", j);
i + = j;
}
}
9. Give the output of the following:
(a) main( ) {
int i=0;
switch(i)
{
case 0: printf("zero");
case 1: printf("one");
case 2: printf("two");
}
}
(b) x = 1;
y = 1;
if (n > 0)
x += 2;
y -= 2;
printf ("%d %d", x, y);
10. Determine how many times the body of the
loop will be executed.

120
C and Data Structures – Unit I

(a) int m = 10;


for (i = 0; i<=5; i += 2/3)
while (m % i >= 0) {

m++;
n += 2;
}
(b) int i;
int n = 7;
{


}
11. What is the output of the following program?
main ( ) {
int x, y, z;
x = y = 0;
while (y < 10) ++y; x + = y;
printf ("%d %d", x, y);
for (y = 1; y < 10; y++) x = y;
printf ("%d %d", x, y);
}

121

You might also like