0% found this document useful (0 votes)
21 views42 pages

Iteration and Loops

The document discusses various control statements in C including relational operators, logical operators, if/else statements, switch statements, loops, and nested control structures. Relational operators compare values and return true or false. Logical operators combine relational expressions. Selection statements like if/else and switch allow conditional execution based on relational expressions. Loops allow repetitive execution of code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views42 pages

Iteration and Loops

The document discusses various control statements in C including relational operators, logical operators, if/else statements, switch statements, loops, and nested control structures. Relational operators compare values and return true or false. Logical operators combine relational expressions. Selection statements like if/else and switch allow conditional execution based on relational expressions. Loops allow repetitive execution of code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

CONTROL STATEMENTS

2. CONTROL STATEMENTS INCLUDE


PROGRAM CONTROL
STATEMENTS/CONSTRUCTS IN ‘C’
OPERATORS
RELATIONAL Equality and Logical
OPERATORS Operators

To Specify Symbol Used To Specify Symbol Used


less than <
Equal to ==
greater than >
Not equal to !=
less than or <=
equal to >= Logical AND &&
greater than or
equal to Logical OR ||

Negation !
POINTS TO NOTE
 If an expression, involving the relational operator, is true, it is given a value of 1. If
an expression is false, it is given a value of 0. Similarly, if a numeric expression is
used as a test expression, any non-zero value (including negative) will be
considered as true, while a zero value will be considered as false.

 Space can be given between operand and operator (relational or logical) but space
is not allowed between any compound operator like <=, >=, ==, !=. It is also
compiler error to reverse them.

 a == b and a = b are not similar, as == is a test for equality, a = b is an assignment


operator. Therefore, the equality operator has to be used carefully.

 The relational operators have lower precedence than all arithmetic operators.
A FEW EXAMPLES
The following declarations and initializations are
given:
int x=1, y=2, z=3;
Then,
The expression x>=y evaluates to 0 (false).
The expression x+y evaluates to 3 (true).
The expression x=y evaluates to 2 (true).
LOGICAL OPERATORS MAY BE MIXED WITHIN RELATIONAL EXPRESSIONS
BUT ONE MUST ABIDE BY THEIR PRECEDENCE RULES WHICH IS AS
FOLLOWS:
OPERATOR SEMANTICS

Operators Associativity
() ++ (postfix) -- (postfix) left to right
+ (unary) - (unary) right to left
++ (prefix) -- (prefix) * / % left to right
+- left to right
< <= > >= left to right
== != left to right
&& left to right
|| left to right
?: right to left
=+=-=*=/= right to left
, (comma operator) left to right
CONDITIONAL EXECUTION AND SELECTION

Selection Statements

The Conditional Operator

The switch Statement


SELECTION STATEMENTS

One-way decisions using if statement

Two-way decisions using if-else statement

Multi-way decisions

Dangling else Problem


ONE-WAY DECISIONS USING IF STATEMENT

Flowchart for if construct


if(TestExpr)
stmtT; T F
TestExpr

stmtT
WRITE A PROGRAM THAT PRINTS THE
LARGEST AMONG THREE NUMBERS.
Algorithm C Program
1. START #include <stdio.h>
2. PRINT “ENTER THREE int main()
NUMBERS” {
int a, b, c, max;
3. INPUT A, B, C printf(“\nEnter 3 numbers”);
4. MAX=A scanf(“%d %d %d”, &a, &b, &c);
5. IF B>MAX THEN MAX=B max=a;
if(b>max)
6. IF C>MAX THEN MAX=C
max=b;
7. PRINT “LARGEST if(c>max)
NUMBER IS”, MAX max=c;
8. STOP printf(“Largest No is %d”, max);
return 0;
}
TWO-WAY DECISIONS USING IF-ELSE STATEMENT

The form of a two-way decision Flowchart of if-else construct


is as follows:

if(TestExpr) TestExpr
stmtT;
else
stmtF;
stmtT stmtF
WRITE A PROGRAM THAT PRINTS THE LARGEST
AMONG THREE NUMBERS.

Algorithm C Program
1. START #include <stdio.h>
2. PRINT “ENTER THREE int main()
NUMBERS” {
int a, b, c, max;
3. INPUT A, B, C printf(“\nEnter 3 numbers”);
4. MAX=A scanf(“%d %d %d”, &a, &b, &c);
5. IF B>MAX THEN MAX=B max=a;
if(b>max)
6. IF C>MAX THEN MAX=C max=b;
7. PRINT “LARGEST if(c>max)
NUMBER IS”, MAX max=c;
printf(“Largest No is %d”, max);
8. STOP
return 0;
}
MULTI-WAY DECISIONS

if(TestExpr1)
switch(expr)
stmtT1; {
else if(TestExpr2) case constant1: stmtList1;
stmtT2; break;
else if(TestExpr3) case constant2: stmtList2;
break;
stmtT3;
case constant3: stmtList3;
.. . break;
else if(TestExprN) ………………………….
stmtTN; ………………………….
else default: stmtListn;
}
stmtF;

if-else-if ladder General format of switch


statements
FLOWCHART OF AN IF-ELSE-IF CONSTRUCT

TestExpr

TestExpr
2
TestExpr3
stmtT1
TestExpr
stmtT2 N

stmtT3
stmtTF
stmtTN
THE FOLLOWING PROGRAM CHECKS WHETHER A NUMBER
GIVEN BY THE USER IS ZERO, POSITIVE, OR NEGATIVE

#include <stdio.h>
int main()
{
int x;
printf(“\n ENTER THE NUMBER:”);
scanf(“%d”, &x);
if(x > 0)
printf(“x is positive \n”);
else if(x == 0)
printf(“x is zero \n”);
else
printf(“x is negative \n”);
return 0;
}
NESTED IF

When any if statement is Construct 1 Construct 2


written under another if if(TestExprA) if(TestExprA)
statement, this cluster is if(TestExprB)
called a nested if. if(TestExprB) stmtBT;
stmtBT; else
The syntax for the nested is else stmtBF;
given here: stmtBF; else
else
stmtAF; if(TestExprC)
stmtCT;
else
stmtCF;
A PROGRAM TO FIND THE LARGEST AMONG THREE
NUMBERS USING THE NESTED LOOP
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\nEnter the three numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
DANGLING ELSE PROBLEM
This classic problem occurs when
there is no matching else for each
if. To avoid this problem, the
simple C rule is that always pair
an else to the most recent
unpaired if in the current block.
Consider the illustration shown
here.
The else is automatically paired
with the closest if. But, it may be
needed to associate an else with
the outer if also.
SOLUTIONS TO DANGLING ELSE PROBLEM

With null With braces


Use of null else else
if(TestExprA if(TestExprA
Use of braces to ) )
{
enclose the true if(TestExprB
action of the second ) if(TestExprB
if stmtBT; )
else stmtBT;
; }
else else
6. THE CONDITIONAL OPERATOR

It has the following simple #include <stdio.h>


int main()
format: {
int a,b,c;
printf(“\n ENTER THE TWO
expr1 ? expr2 : expr3 NUMBERS:”);
scanf(“%d %d”, &a, &b);
c=a>b? a : b>a ? b :-1;
It executes by first if(c==-1)
printf(“\n BOTH NUMBERS ARE
evaluating expr1, which is EQUAL”);
normally a relational else
expression, and then printf(“\n LARGER NUMBER IS %d”,c);
return 0;
evaluates either expr2, if the }
first result was true, or
expr3, if the first result was
false. An Example
THE SWITCH STATEMENT

The general format of a switch


statement is
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}

The C switch construct


SWITCH VS NESTED IF
 The switch differs from the else-if in that switch can test
only for equality, whereas the if conditional expression
can be of a test expression involving any type of
relational operators and/or logical operators.

 A switch statement is usually more efficient than nested


ifs.

 The switch statement can always be replaced with a


series of else-if statements.
ITERATION AND REPETITIVE EXECUTION

 A loop allows one to execute a


statement or block of statements
repeatedly. There are mainly two
types of iterations or loops –
unbounded iteration or
unbounded loop and bounded
iteration or bounded loop.
 A loop can either be a pre-test
loop or be a post-test loop as
illustrated in the diagram.
“WHILE” CONSTRUCT

while statement is a pretest


Expanded
loop. TheSyntax of “while”
basic syntax and its
of the
Flowchart
while Representation
statement is shown below:
AN EXAMPLE

#include <stdio.h> This loop contains all the parts


int main() of a while loop. When executed
{ in a program, this loop will
int c; output
c=5; // Initialization
5
while(c>0)
4
{ // Test Expression
3
printf(“ \n %d”,c); 2
c=c-1; // Updating 1
}
return 0;
}
TESTING FOR FLOATING-POINT ‘EQUALITY’

float x;
x = 0.0;
while(x != 1.1)
{
x = x + 0.1;
printf(“1.1 minus %f equals %.20g\n”, x, 1.1 -x);
}
The above loop never terminates on many computers, because 0.1 cannot
be accurately represented using binary numbers.
Never test floating point numbers for exact equality, especially in loops.
The correct way to make the test is to see if the two numbers are
‘approximately equal’.
“FOR” CONSTRUCT
 The general form of the for statement is as follows:

for(initialization; TestExpr; updating)


stmT;
for construct
flow chart
EXAMPLE

#include <stdio.h>
int main()
{
int n, s=0, r;
printf(“\n Enter the Number”);
scanf(“%d”, &n);
for(;n>0;n/=10)
{
r=n%10;
s=s+r;
}
printf(“\n Sum of digits %d”, s);
return 0;
}
8.3 “DO-WHILE” CONSTRUCT

The C do-while loop


The form of this loop
construct is as follows:
do
{
stmT; /* body of
statements would be
placed here*/
}while(TestExpr);
POINT TO NOTE

With a do-while statement, the body of the loop is


executed first and the test expression is checked
after the loop body is executed. Thus, the do-while
statement always executes the loop body at least
once.
AN EXAMPLE

#include <stdio.h>
int main()
{
int x = 1;
int count = 0;
do {
scanf(“%d”, &x);
if(x >= 0) count += 1;
} while(x >= 0);
return 0;
}
WHICH LOOP SHOULD BE USED???
THERE ARE NO HARD-AND-FAST RULE
REGARDING WHICH TYPE OF LOOP SHOULD BE USED

Some methods of controlling repetition in a program are:

 Using Sentinel Values

 Using Prime Read

 Using Counter
GOTO STATEMENT

The following program is used to


The control is find the factorial of a number.
unconditionally transferred #include <stdio.h>
int main()
to the statement associated {
with the label specified in int n, c;
long int f=1;
the goto statement. The printf(“\n Enter the number:”);
form of a goto statement is scanf(“%d”,&n);
if(n<0)
goto end;
for(c=1; c<=n; c++)
goto label_name; f*=c;
printf(“\n FACTORIAL IS %ld”, f);
end:
return 0;
}
10. SPECIAL CONTROL STATEMENTS

“return” statements

“break” statements

“continue” statements
“BREAK” AND “CONTINUE” STATEMENTS
NESTED LOOPS
 A nested loop refers to a #include <stdio.h>
loop that is contained int main()
within another loop. {
 If the following output has int row, col;
to be obtained on the for(row=1;row<=4;++row)
screen {
1 for(col=1;col<=row;++col)
22 printf(“%d \t”, row);
333 printf(“\n”);
4444 }
then the corresponding return 0;
program will be }
COMMON PROGRAMMING ERRORS

 Writing expressions like a<b<c or a==b==c etc.

 Use of = instead of ==

 Forgetting to use braces for compound statement

 Dangling else

 Use of semicolon in loop

 Floating point equality

You might also like