[go: up one dir, main page]

0% found this document useful (0 votes)
6 views34 pages

POP Using C - Module 2

Complete module 2 notes for C

Uploaded by

shriyasm7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views34 pages

POP Using C - Module 2

Complete module 2 notes for C

Uploaded by

shriyasm7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Principles of Programming using C – 23ESCS11

Module – 2
Operators and Expressions in C
Operators and expressions in C:
- Operators in C: arithmetic, relational, equality,
- logical, assignment,unary,
- conditional, bitwise operator, Increment and decrement operator,
- Conditional Operator, operator precedence,
- keywords and identifiers,
- Type conversion and typecasting.
Decision control and Looping statements:
- Introduction to decision control,
- Conditional branching statements,
- Iterative statements,
- Nested loops,
- break and continue statements,
- goto statement.

Prepared By –
Prof.DIVYA.H.N. B.E,M.Tech,(Ph.D )
Asst.Professor,
Department of CSE, DSATM

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Module 2
Operators and Expressions in C

Introduction

In the previous chapter we studied Alphabets of C ,how these alphabets are used to obtain
meaningful words called Tokens , and various types of Tokens .We also discussed about the
variables and how some of the keywords can be used to define the Type of the variables .Now ,
we will see how these variables and constants are joined together using operators to obtain the
expression and evaluate the expressions .

1.Operators

An Operator is a symbol/Token that specifies the Operation to be performed.


or
An operator is a symbol that specifies the mathematical, logical or relational operation to be
performed. An expression is any computation that yields a value . C supports a rich set of
operators. Operators are used in programs to manipulate data and variables

+ , - , * , / , are some of the Operators . + means Add ; - means Subtract ; * means Multiply
and so on .

Eg 1 : 10 + 20

// Here 10 and 20 are called Operands and + is an Operator . Since there are Two Operands ,
the Operator + is called Binary Operator //

Eg 2 : - 100

// Here 100 is an Operand and - is an Operator . Since the Operator ‘-‘ is associated with Only
Operand it is called Unary Operator //

C language includes large number of Operators . The Operators in C can be classified based on

• The Number of Operands an Operator has ;


• The Type of Operation being Performed .

1.1. The Number of Operands an Operator has

The Operators are classified into four major categories based on the number of Operands
shown below :
1.Unary Operators
2.Binary Operators
3.Ternary ( ?:) Operators
4.Special Operators : comma , size of etc.

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


1.1.1. Unary Operators

An Operator which acts on Only one Operand to Produce the result is called Unary Operator .
In this expressions involving Unary Operator , the operators precede the Operand .
Eg : -10 , -a , *b , &c , ~d etc .

1.1.2.Binary Operators

An Operator which acts on Two Operands to produce the result is called Binary Operator.

In an Expression involving a Binary Operator, the Operator is placed between Two Operands

Eg : a+b ; 10*20 ; 5/5 ; 10/a etc.

1.1.3. Ternary Operators

An Operator which acts on Three Operands to Produce the result is called Binary Operator. This
Operator is also called Conditional Operator .

Eg : a ? b : C

1.2. The Type of Operation being Performed

Here Classification is based on the type of the Operation being Performed

Types of Operators are :

1. Arithmetic Operators +,-,*,/.


2. Assignment Operators = , + = etc.
3. Increment / Decrement Operators ++ , --
4. Relational operators < , < = etc
5. Logical Operators && , || etc
6. Conditional Operators ?:
7. Bitwise Operators & , ^ etc
8. Special Operators , ; [ ] ; & ; size of

1.2.1. Arithmetic Operators

The Operations that are used to Perform Arithmetic Operations such as Addition
,subtraction ,Multiplication etc are Arithmetic Operators .

1.2.2.Assignment Operators Before Manipulating the data , the data as to be stored in memory
. Now the Question is “How to store the data in memory ?’ .This is where the Asssignment
Operator is used .

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


An Operator which is used to Copy the Data or Result of an Expression into a memory location (
which is identified by a variable name ) is called an Assignment Operator . The Assignment
Operator is denoted by ‘ = ‘ sign .

Syntax : variable = expression ;

Eg Statements Results
1 a=b; Store the Value into b
2 area = l*b ; Compute the Product and store the value into area
3 Pi = 3.1416 ; Store the number 3.1416 using the variable pi
4 a = =b ; Error = = is relational Operator (used for compare not to
copying)
5 a = b*10 ; Error No semicolon at the end
6 10 + b = c ; Error Expression not allowed on LHS Of assignment Operator

1.2.3.Increment / Decrement Operators

This is an Unary Operator.It increments the value of the Operand by One .

It is Classified into Two Categories as ;

Pre increment ( ++ a) : if the increment operator (++) is placed before the Operand
,then the Operator is called Pre increment Operator . As the name indicates pre increment
means increment before the Operand Value is used . So Operand value is incremented
by 1 .

Post increment (a++) . if the increment operator (++) is placed After the Operand ,then
the Operator is called Post increment Operator . As the name indicates pre increment
means increment After the Operand Value is used, the Operand value is incremented
by 1 .

Type Operator Example Result


Post Increment ++ a++ 21
Pre Increment ++ ++ a 21

In the above table ; If initial value of a is 20 , in both the cases after Executing , the value of a
will be 21

Decrement Operators

This is an Unary Operator.It decrements the value of the Operand by One .


Pre decrement ( - - a) : if the decrement operator (--) is placed before the Operand ,then the
Operator is called Pre decrement Operator . As the name indicates pre increment means
decrement before the Operand Value is used . So Operand value is decremented by 1 .

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Post decrement (a--) : if the decrement operator ( --) is placed After the Operand ,then the
Operator is called Post decrement Operator . As the name indicates pre decrement means
decrement After the Operand Value is used,the Operand value is decremented by 1
Type Operator Example Result
Post decrement -- a -- 19
Pre decrement -- --a 19

In the above table ; If initial value of a is 20 , in both the cases after Executing , the value of a
will be 21

*Note*

In pre-decrement, first the value of the variable is decremented after that the
assignment or other operations are carried. In post-decrement, first assignment or other
operations occur, after that the value of the variable is decremented.

Eg :
a- -;
--a;
a = a - 1;
a -= 1; are all same if used independently.

1.2.4.Relational operators

The Relational Operators also called Compare Operators are used to Compare Two Operands .
They are used to find the Relationship between Two operands hence are called Relational
Operators .
The Relationship between these two Operands results in either True (always 1 ) or False
(always 0).

C supports six relational operators

Operator Meaning
< Less Than
> Greater Than
= Equal To
!= Not Equal To
<= Less Than or Equal To
>= Greater Than or Equal To

1.2.5.Logical Operators
The Logical Operators are used to combine two or more Relational Expressions.
Eg : if a = = b && b= = c ,then the Triangle is Equilateral . Here Two Expressions are Combined
together by a Logical && Operator .

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Types of Logical Operator
Operator Description / Meaning
! not
&& And
|| Or

Since the Output of Relational Expressions is True or False , the Output of Logical Expressions
is also True or False .

1.2.6.Conditional Operator ( ?: )

An Operator that Operates on three Operands is called Ternary Operator (Conditional Operator).

Syntax :

The general form is:


exp1 ? exp2 : exp3;

where exp1, exp2 and exp3 are expressions.

Here, exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and
becomes the values of the expression.
If exp1 is false, exp3 is evaluated and its value becomes the values of the expression.

Note that only one of the expressions either exp2 or exp3 is evaluated.

For example,
a=10; b=34;
True

max=(a > b) ? a: b;

False

In this example, max will be assigned the value of b because the condition is false. So, exp3 (b)
is evaluated and its value is assigned to max .

1.2.7. Bitwise Operators

The Data is stored in the memory in terms of Binary Digits i.e, 0’s or 1’s . Sometimes , it may be
necessary to manipulate these bits . The Operators that are used to manipulate the bits are called
Bit Wise Operators .

Operator Description
~ Bit wise negative
<< Left shift

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


>> Right Shift
& Bit Wise and
^ Bitwise xor
| Bitwise or

1.2.8. Special Operators ( , ; sizeof )

The Comma Operator represented as a comma ( , ) accepts two Operands and it is used to
combine two or more statements into a single statement . Thus , Compact statements can be
written using comma operator .

The statements are executed one by one from left to right and hence it is left associative operator.
Eg : Consider the statements
temp=a;
a=b;
b=temp;

Above three statements can be written as single statement using ( , ) operator as ;


Temp=a, a=b, b=temp ;
The sizeof( ) Operator is used to find the number of bytes occupied by a variable or a constant
in the computer memory .

Syntax : sizeof
(Operand)

Eg ;
Sizeof(char) 1bytes
Sizeof(int) 2bytes
Sizeof(float) 4bytes

1.2.8. Equality operators : ( = = ) and ( ! = )

The Equal-to-Operator ( = = ) returns True if both Operands have the same value ; otherwise it
returns False .

The not-Equal-to Operator ( != ) returns True if the Operands don’t have the same value ;
otherwise it returns False

1.2.9.Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
destination data type may be smaller than the source data type when converting the data type to
another data type, that’s why it is also called narrowing conversion.

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Eg : float x;
byte y;
...
...
y=(byte)x;
we are converting float(source) data type into byte(target) data type.
1.2.1.Type conversion : In type conversion, a data type is automatically converted into
another data type by a compiler at the compiler time. In type conversion, the destination data
type cannot be smaller than the source data type, that’s why it is also called widening
conversion. One more important thing is that it can only be applied to compatible data types.

Keywords

The words which have predefined meaning in C language are called Keywords .Since they are
reserved for specific purpose in c language ,they are also called reserve words . The keywords
have some specific purpose in c language and hence cannot be used as variable names
,function names etc

*Note *
1.The meaning of the keywords cannot be changed by the user .
2.All keywords should be written in lower case letters .
3.If we use Capital letters they are treated as just identifiers

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Keywords : Different keywords available in C language

1.2.12.Identifiers

An Identifier is a word consisting of sequence of one or more letters or digits along with a
special character “_”(underscore).

Eg : The letters are the characters from ‘A’ to ‘Z’ and ‘a’ to ‘z’ .The Digits are the characters
from 0 to 9.

Normally an Identifier starts with a letter or an underscore and followed by any number of
letters or digits or underscore .

Eg : variables name: sum,i,x,my_marks &
Function names : main,printf etc

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


2.Operator Precedence ( Hierarchy of Operator )

In C Language , each Operator is associated with Priority Value . Based on the priority , the
Expressions are evaluated . The Priority of each Operator is Pre – defined in C language .

The Pre-defined priority or Precedence order given to each of the Operator is called
Precedence of Operator .

The Operations that are carried out based on the precedence of Operators are Called
Hierarchy of Operations .

Operator Category Operator in Precednce Associativity


( highest to lowest )
();[] Innermost Brackets / Function calls Left to Right (L - > R )
Array Element reference
Unary Operators ++ , --, ! , size of , ~ , +,-,&,* Right to Left ( R -> L )

Member Access * Or -> L→R

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Arithmetic Operators *,/,% L→R

Arithmetic Operators - ,+ L→R


Shift Operator <<,>> L→R
Relational Operator ==,!= L→R
Equality Operators & L→R
Bitwise and ^ L→R
Bitwise xor | L→R

Logical and && L→R


Logical or || L→R

Conditional Operator ?: R→L

Asssignment Operator = , + = , - = , /= , * = , % = , & = ,| = , < R → L


<=,>>=
Comma Operator , L→R

Associativity of Operators

If all the Operators in an Expresssion have equal priority , then the Direction order choosen ( left
to right evaluation or right to evaluation ) to evaluate an expression is called Associativity of
Operators .

They are Classified into Two Categories based on the Direction of Evaluation Chosen as shown
below :

1.Left to Right Associativity ( Left Associative) ; Eg : All Binary Arithmetic , Logical and
Relational Operators .

2.Right to Left Associativity ( Right Associative ) : Eg : Assignment Operator , Unary


Operator etc.

2.1. Left to Right Associativity ( Left Associative)

In the Expression ,if there are two or more Operators having the same priority and evaluated
from left to right , then the Operators are called Left To Right Associative Operators .

Eg : 8+4+3

12+3

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


2.2. Right to Left Associativity ( Right Associative )

In the Expression ,if there are two or more Operators having the same priority and evaluated
from right to left , then the Operators are called Left To Right Associative Operators.

Problems on Left Associative

1) 2* ( ( a % 5 ) * ( 4 + (b – 3) / ( c + 2 ) ) ); assuming a=8 ; b=15 & C = 4

Soln : 2* ( ( a % 5 ) * ( 4 + (b – 3) / ( c + 2 ) ))

=2* ( ( 8 % 5 ) * ( 4 + ( 15 – 3) / ( 4 + 2 ) ) )

=2* ( 3 * ( 4 + ( 15 – 3) / ( 4 + 2 ) ) )

=2* ( 3 * ( 4 + 12 / ( 4 + 2 ) )

=2* ( 3 * ( 4 + 12 / 6 ) )

=2* ( 3 * ( 4 + 2 ) )

=2* ( 3 * 6 )

=2 * 18

= 36
Hierarchy of Operator ( On Relational Expressions )

General rules to be followed :


1) Evaluate the Expression within parenthesis
2) Evaluate Unary Operators
3) Evaluate Arithmetic Expressions
4) Evaluate Relational Expressions
Evaluate the following Expression : 100 / 20 < = 10 – 5 + 100 % 10 – 20 = = 5 > = 1 ! = 20

Soln : 100 / 20 < = 10 – 5 + 100 % 10 – 20 = = 5 > = 1 ! = 20

5 < = 10 – 5 + 100 % 10 – 20 = = 5 > = 1 ! = 20

5 < = 10 – 5 + 0 - 20 = = 5 > = 1 ! = 20

5<=5 + 0 - 20 = = 5 > = 1 ! = 20

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


5<= 5 -20 = = 5 > = 1 ! = 20

5<= -15 = = 5 > = 1 ! = 20

0 ==5 > = 1 ! = 20

0 == 1 != 20

0 != 20

Hierarchy of Operator ( On Logical Operators )

General rules to be followed :


1) Parenthesis
2) Unary Expressions
3) Arithmetic Expressions
4) Relational Expressions
5) Logical Expressions

Evaluate the Expression : a + 2 > b && ! c || a ! = d & & a – 2 < = e ; where a=11;
b=6;c=0;d=7 & e = 5

Soln : a + 2 > b && ! c || a ! = d & & a – 2 < = e

11 + 2 > 6 && ! 0 || 11 ! = 7 & & 11 – 2 < = 5


11 + 2 > 6 && ! 0 || 11 ! = 7 & & 11 – 2 < = 5

11 + 2 > 6 && 1 || 11 ! = 7 & & 11 – 2 < = 5

13 > 6 && 1 || 11 ! = 7 & & 11– 2 < = 5

13 > 6 && 1 || 11 ! = 7 & & 9 < = 5

1 && 1 || 11 ! = 7 & & 9 < = 5

1 && 1 || 11 ! = 7 & & 0

1 && 1 || 1 & & 0

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


1 || 1 & & 0

1 || 0

Evaluate :
a) a+2 > b || ! c && a ==d || a-2 < = e ; where a = 11 , b= 6 , c= 0 , d = 7 ,e =5.
b) 10!=10||5<4&&8

Hierarchy of Operator ( On Assignment Operators )

1.Short-hand Assignment statement ( Compound assignment )

a) Evaluate : x*=y+3 ; x=10 and y=5

It can be written as

x* =(y+3)
can be interpreted as ; x = x * ( y +3)

x = 10 * ( 5+3)

x = 10 * 8

x=80

2.Short-hand Assignment statement ( Multiple assignment statement )

a + b * = c - = 5 ; where a = 1 ; b = 3 and C = 7.
a+b*=c-=5

c=c–5
c=7–5
c =2

a+b*=2

a+=b=b*2
b=3*2
b=6

a+ = 6

a=a+6
a=1 +6

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


a=7

3. Statements

• A statement is a Programming Construct that is used to inform the Computer to Perform


an action when a Program is executed.
• A statement can alter the value of variable , it can accept the input , it can manipulate
the data and display the data
✓ Eg : i++; /*increment value of I by 1*/
✓ Sum=0; /*initialize sum to zero*/
✓ Scanf(“%d”,&n); /*read an integer value to n*/
❑ Types of Statement
1. Expression Statement
2. Compound Statement
3. Control statement .

3.1.Expression Statement
An expression followed by a semicolon is called Expression statement
Eg : area=l*b;
Sum=sum+i;
J++;
Printf(“\n enter the number”);
Scanf(“%d”,&n);

3.2.Compound Statement
✓ A sequence of statement enclosed within a pair of braces { } is called compound
statement .
✓ Even if a single statement is present within the braces ,it is treated as a compound
statement .
✓ The Compound statement is also called block statement .
eg1 :
{
Printf(“\n area=%ld”,l*b);
}
3.3. Control statements in C are programming constructs that are used to control the flow of
execution in a program.
They allow a programmer to specify conditions that determine which statements are
executed and which are skipped, to loop through statements until a condition is met, or to jump
to a different part of the program.

Eg ;

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


4.Selection / Branching statements

In Sequential control , all the statements are executed in the order in which they are written .
However , a set of statements may have to be executed only when certain condition is met . A set
of statements may have to be skipped during execution when some other condition is met
.sometimes without any condition , the control may be transferred to some other place in the
program .These statements that transforms the control from one place to other place in the
Program with or without any condition are called Branch Statements .

The branching instructions are classified as ;

1.Conditional branch statements .


2.UnConditional branch statements.

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


4.1.Conditional branch statements

Normally , all the statements are executed one after the other .However sometimes,the user
wants to execute certain statements when some condition is met or the user may skip the
execution of some statements when some other condition is met . These statements that transfer
control from one place to other place so as to execute a set of instructions if some

condition is met or skip the execution of some statements if the condition is not met are
called conditional branch statements .they are also called selection statements or decision
statements . Simple if (single selection ) .

4.1.1.The if-statement ( One way selection / decision )

• An if statement is a single selection or Decision statement .

• When a set of statements have to be executed when an expression is evaluated to true


(non zero value ) or when a set of statements have to be skipped when an expression is
evaluated to false (zero),then if-statement is used .

• It is used when we have only one alternative .

Hence it is also called one-way decisions/selection statement

Syntax ;

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Example ;

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


4.2.2. The if-else statement

• If one set of activities have to be performed when an expression is evaluated to true and
another set of activities have to be performed when an expression is evaluated to false
,then if-else-statement is used .

The if-else statement is a simple selection /decision statement that is used when we must choose
between two alternatives .Hence it is also called Two-way Decisions /Selection statement.

❑ When we can use if-else ? when we cannot use ?


❖ The if-else is used only during Two-way selection / decision .
❖ It cannot be used if decision has to be made for one alternative .
❖ It cannot be used if decision has to be made for three or more alternatives .

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Example

4.1.3.Nested –if

• An if or if-else statement within another if or if-else statement is called “nested if


statement “
• When an action has to be performed based on many decisions involving various types of
expressions and variables ,then this statement is used .so it is called multi-way decision
statement .

Advantages
1. There are situations involving series of decisions where we are forced to use an if or if-
else in another if or if-else statement.In such situations , nested-if-statements are used .

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


2. When an action has to be performed based on many decisions involving various types of
expressions and variables ,then this statement is used
DisAdvantages
1. The nested if’s are difficult to understand and modify .
2. As depth of nesting increases ,the readability of the Program decreases .

Eg ;

4.1.3.Else-if ladder

• An else-if ladder is a special case of nested-if statement where nesting take place only in
the else part .
• When an action has to be selected based on range of values , then this statement is used
.so it is called multi-way decision/selection statement .
• The orderly nesting of if-else-statement only in the else part is called else-if-ladder .

Example :

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


4.1.4. The Switch statement

The Switch statement is a control statement used to make a selection between many
alternatives.

The switch statement is used in the following scenarios :


• When a decision has to be made between many alternatives .
• When the selection condition reduces to fix integer value .
• Switch statement cannot be used when a series of decision /condition involve a logical or
relational expressions .

❑ Advantages
• Improves readability of the program
• More structured way of writing the program .
❑ Disadvantages
• Used only if the expressions used for checking the conditions results in Integer
value(char is also allowed ).If the result of expression is not integer value,switch
statement cannot be used .
• Cannot be used when a selection is based on a range of values
*Note*
When break statement is executed ,the control comes out of the switch statement .

Eg;/*Prog to compute -
• Calculator function using switch
• To check an alphabet vowel or not

4.2.2. Unconditional branch statements

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


The sequential statements are executed one after the other .However we can give instructions to
transfer control from one statement to some other statement during execution of the Program
.These statements are called Unconditional Branching Statement or Unconditional control
statements.The statements that transfer the control from the one statement to other statement in
the Program without any condition are called unconditional statements

• Unconditional statements are classified as shown below :

4.2.1.The goto statement

• The sequential statements are executed one after the other .But , if the programmer wants
to transfer the control from one point to other in the Program ,the goto statement can be
used .
• Using this statement ,control can be transferred from one statement to the specified
statement without any condition(conditionally).

• Syntax:
goto label;

– Where , label is an identifier

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Example ;

❑ Disadvantages
• Using goto,the code is difficult to read and understand .
• The usage of goto results in unstructured programming.
• It is not good programming style .
*NOTE * As far as possible use of goto is avoided in all subsequent programs.

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


4.2.2. The break statement

The break statement is jump statement which can be used in switch statement and loops .
❑ The break statement works as shown below :
✓ The break statement in switch statement causes control to terminate switch statement and
the statement following switch statement will be executed .
✓ Usually in any case , the break statement will be the last statement.
✓ If break is executed in a loop(such as for/while/do-while),the control comes out of the
loop and the statement following the loop will be executed .

Syntax of break in switch case

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


4.2.3.The continue statement
The continue statement is used only in the loops to terminate the current iteration and continue
with remaining iterations .
• During execution of a loop,it may be necessary to skip a part of the loop based on some
condition.In such cases , we use continue statement .

Eg : During processing of student records , it may be necessary to exclude student names whose
marks are less than or equal 50.In such case , a test is made to see whether the marks scored is
less than or equal to 50.If so part of the program that processes the student details can be skipped
using Continue .But the execution continues with next iteration of the loop .

Syntax

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Differences between ;

4.2.4.return statement

• The function body consists of declaration ; executable part & return .


• Return is a keyword ,used to control the calling function with/without a value .

Eg :
• If a function is not returning any value ,use the return keyword as shown ;
return ;
• If a function is returning any value ,use the return keyword as shown;
return value ;

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


5.Repition (Looping) [ for ,while , do – while ]

A set of statements may have to be repeatedly executed for a specified number of times or till a
condition is satisified . The Statements that help us to execute a set of statements repeatedly are
called Looping Constructs or Loop Control statements .

These statements are also called Repititive or Iterative statements .

The Various loop Constructs in C language are ;

For loop ( pre-test / Top Testing loop )

Loop Constructs while loop ( pre-test / Top Testing loop )

Do-while loop ( post-test / Bottom-testing loop)

5.1.The for statement

A for loop is a control statement using which the programmer can give instructions to the
computer to execute a set of statements repeatedly for a specified number of times .Since it is
required to specify how many times a set of statements have to be executed ,it is also called
counter-controlled loop .

Syntax : for ( exp1 ; exp 2 ; exp 3 )

Where , for - > keyword


exp1 - > contains initialization statements followed by semicolon ,
exp2 - > contains limit-test expression followed by semicolon,
exp3 -> contains updating expression.

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Working of for loop

1.The first expression exp1 is evaluated.

2.Second expression exp2 is evaluated to True / False . If it is evaluated to False , the control
comes out of the loop without executing the body of the loop and the A-statements following the
for loop are executed .

3.If exp2 is evaluated to True , the body of the loop is executed . After executing the body of the
loop , control goes back and exp3 is executed .

*NOTE*

a) Exp2, the body of the loop and exp3 are repeatedly executed as long as exp2 is evaluated to
True. Once the exp2 is evaluated to FALSE ,the control comes out of the loop and the A-
statements that appear after the for loop are executed .

b) The for loop is always used when we know initial value , final value and Updating value . The
Updating value can be constantly incremented or decremented .

Eg 1 : /* C prog to display numbers from 1 to n * /

#include<stdio.h>

Void main()

int n,i ;

printf(“\n enter the value of n :”);

scanf(“%d”, &n);

printf(“\n The numbers displayed are : “);

for(i=0;i<n;i++)

Printf(“%d”,i);

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


Eg 2 : /* C prog to display numbers from n down to 1 * /

#include<stdio.h>

Void main()

int n,i ;

printf(“\n enter the value of n :”);

scanf(“%d”, &n);

printf(“\n The numbers displayed are : “);

for(i=0;i<n;i- -)

Printf(“%d”,i);

Eg 3 : /* C prog to Compute factorial of a number * /

#include<stdio.h>

Void main()

int n,fact,i ;

printf(“\n enter the value of n :”);

scanf(“%d”, &n);

fact = 1 ;

for(i=0;i< =n;i+ +)

fact* = i ;

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


}

Printf(“%d ! = %d \n ”, n , fact );

5.2.The While statement

A while loop is a control statement using which the programmer can give instructions to the
computer to execute a set of statements repeatedly as long as specified condition is satisfied .
Once the specified condition is false , control comes out of the loop .

Working of while loop ;

The following sequence of operations are carried out after executing B – Statements that are
present before the while-loop

a)The initialization for the while loop are done first . Theloop controlled variable is also
initialized .

b)Then the expression is evaluated to True / False . If it’s evaluated to False , the control comes
out of the loop without executing the body of the loop and A-statements that are present after the
while loop are executed .

c)If the expression is evaluated to TRUE,the statements inside the body of the loop are executed .

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


d)The loop variable is updated inside the body of the loop and then control goes back to
beginning of the while – statement and expression is again evaluated to True or False .

e)Thus the body of the loop is repeatedly executed as long as expression is evaluated to TRUE ,
Once the expression is evaluated to False ,the control comes out of the loop and A-statements
following while loop are executed .

f) Since a set of statements have to be repeatedly executed based on the conditions or till an
event has occurred,the while loop is also called condition-controlled loop or event – controlled
loop .

Eg1 :/*C program to compute sum of series 1+2+3+……..+n */

Void main()

int n,sum,i;

printf(“\n Enter the number of terms :”);

scanf(“%d”,&n);

sum = 0 ;

i= 1;

while ( i < =n)

sum = sum + i ;

i++ ;

Printf ( “ sum of series=%d “,sum );

5.3. do – while statement

do-while loop is similar to a while loop and used when a set of statements have to be
repeatedly executed at least once until a certain condition is reached .when we do not know
exactly how many times a set of statements have to be repeated ,do while can be used .

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


It is a post-test loop or bottom testing loop and hence the body of the loop is executed
first and then the expression is evaluated to True or False.

Since the expression is evaluated to True or False at the end of the do-while loop , the do-
while loop is also called exit-controlled loop .

Working ;

The following sequence of Operations are carried out after executing the B-statements that
appear just before the do-while loop.

a ) The statements inside the body of the do-while loop are executed one after the other .

b) Then , the expression is evaluated . If the expression is evaluated to True , the body of the
loop is executed again and the process is repeated . The moment expression is evaluated to False
, control comes out of the do-while and A-statements that appear the do-while loop are executed .

Eg 1 : / * C prog to find sum of natural numbers from 1 to n * /

#include<stdio.h>

Void main()

int sum , n ,i ;

printf(“\n Enter the number of terms : “);

scanf(“ %d”,&n);

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024


sum = 0 ;

i=1;

do

sum = sum + i ;

i++;

While ( i < = n) ;

printf(“\n sum of series = % d : “, sum);

******************************** END *************************************

By – Prof . DIVYA . H . N [ DSATM ] 2023-2024

You might also like