[go: up one dir, main page]

0% found this document useful (0 votes)
11 views23 pages

Loops

The document covers key programming concepts in C, focusing on selection and looping structures. It details logical data and operators, two-way and multi-way selection statements, and various types of loops including pre-test and post-test loops. Additionally, it provides examples and flowcharts to illustrate the syntax and application of these concepts in programming.

Uploaded by

shravan18k
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)
11 views23 pages

Loops

The document covers key programming concepts in C, focusing on selection and looping structures. It details logical data and operators, two-way and multi-way selection statements, and various types of loops including pre-test and post-test loops. Additionally, it provides examples and flowcharts to illustrate the syntax and application of these concepts in programming.

Uploaded by

shravan18k
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/ 23

Unit-VI 7 Hours

Selection – Making Decisions, Repetition


Logical data and operators, Two-way selection, Multiway-selection, Concept of a loop, Pretest and
post-test loops, Initialization and updating, Event controlled and count controlled loops, Loops in
C, Other statements related to looping, looping applications, Recursion, Programming examples,
Software Engineering, Tips and common programming errors.

Logical data and operators:


Definition: Data variables/identifiers that evaluate to a TRUE (1) or FALSE (0) values
are called Logical data elements.
Following are the Logical operators used in C Language:
Logical Operators Name Example
&& Logical AND A && B
|| Logical OR (X +A) | | (Y+B)
! Logical NOT !A

(Note: Logical operators and their truth values are extensively covered in Unit-4 of this
book)

Logical expressions: ‘C’ expressions that comprises of logical operators (&&, | | and !)
are referred to as Logical expressions. Here is one example:
((A+B) = = (C-D)) && ((X-Y) != (P+Q))

Relational
Relational expression-2
expression-1
Logical AND used to
Combine two
relational expressions

The expression ((A+B) = =(C-D)) && ((X-Y) ! = (P+Q)) is an example for logical
expressions.

Where do we use logical operators and expressions?


Logical expressions are used to make decisions in C statements. Two way selection
statements and multi-way selection statements always use logical expressions.

Two-Way Selection Statements (Decision making):


In C programs we often face situations where the path of program execution changes
based on a condition being TRUE or FALSE. (Refer unit-4 C statements) in such
situation we make use of two way selection statements.
C language provides following two-way selection statements:
1. if statement
2. if – else statement
3. Nested if statement
4. if-else-if (also called else-if ladder)

Here we discuss each of these if statements by using general-syntax, flowcharts and


examples:
if statement:

if general syntax:
if ( test expression)

Statements-1;

}
Statements-2

Flowchart:

True
Test expression Statement-1

false

Statement-2

Example:
void main( )
{
int a=10, b=11;
if (a >b)
{
printf(“a is bigger and value is= %d”, a);
}
}
if—else general syntax

if (test expression)
{
(true-block;)
statement-1;
}
else
{
(false-block;)
statement-2;
}
Statement-3;

Here is a flowchart representation for if-else statement

false true
Test expression

Statement-2 Statement-1

Statement-3

Example:
void main( )
{
int a=10, b=11;
if (a >b)
{
printf(“a is bigger and value is= %d”, a);

}
else
{
printf(“b is bigger and value is= %d”, b);
}
}

Nested –if general syntax

if (test expression-1)
{
if( test expression-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}

Equivalent flowchart is as follows:

True
Test expression-1

False True
Test expression-2

Statement-1
Statement-3 False

Statement-2

Example for nested if:


if ( A>B)
{
if (A>C)
{
printf(“%d”, A);
}
else
{
printf(“%d”, C);
}
}
else
{
if(B>C)
{
printf(“%d”, B);
}
else
{
printf(“%d”, C);
}
}

if-else-if ladder general syntax:

if (test expression-1)
{
statement-1;
}
else if(test expression-2)
{
statement-2;
}
else if(test expression-3)
{
statement-3;
}
else
{
statement-4;
}

Here is example flowchart for if-else-if ladder:


false
Test expression-1

false
true
Test expression-2

Statement-1 true
Test expression-3

Statement-2
True
Statement-3

Example program for if-else-if ladder is a simple calculator program that carries out
addition, subtraction and multiplication.
void main()
{
int choice, a=100, b=5;
scanf(“%d”, &choice);

if(choice==1)
printf(“sum=%d”, a+b);

else if(choice==2)
printf(“difference=%d”, a-b);

else if(choice==3)
printf(“product=%d”, a*b);

else if (choice==4)
printf(“rem=%d”, a%b);

else
printf(“Invalid option”);
}

Multi-way Selection Statements:


C language provides a multi-way decision statement so that complex if-else-if statements
can be easily replaced by it. C language’s multi-way decision statement is called –switch.
General syntax of switch statement is as follows:
switch( test-expression)
{
case value-1:
block-1;
break;

case value-2:
block-2;
break;

case value-3:
block-3;
break;

default:
default-block;
}

Here switch, case, break and default are built-in C language words. If the test-expression
evaluates to value-1, block-1 will be executed else if it evaluates to value-2 block-2 will
be executed and so on. If test-expression does not evaluate none of the values default
block will be executed.

Here is a simple flowchart for switch statement:

switch (expression)

Test-exp=value-1
Block-1
Test-exp=value-2
Block-2

Block-3
Test-exp=value-3
Statement-x
Default-block
Expression given in switch statement determines which blocks of statements to be
executed. If expression does not match with any values default block will be chosen.
Here is a simple calculation program that uses multi-way switch statement to do addition,
subtraction and multiplication:

void main( )
{
int a=5, b=25, ch, sum, diff, product;
scanf(“%d”, &ch);
switch(ch)
{
case 1:
sum=a+b;
printf(“%d”,sum);
break;

case 2:
diff=a-b;
printf(“%d”,diff);
break;

case 3:
product =a*b;
printf(“%d”, product);
break;

default:
default-block;
}
}

In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so
on.

Concept of loops
Let us take two sample problems to be solved using computer programs.
1. Program to print ‘hello’10 times
2. Program to find sum of first 10 natural numbers.
First let us analyze the problem to print ‘hello’ 10 times. To print ‘hello’ once we require
one printf statement as shown below:
printf(“\nhello”);
But to print ‘hello’ 10 times we cannot write printf so many times. Instead we will use a
counter that keeps track of the number of times ‘hello’ is printed. It is in such situations
we require loops.
In second problem we have to add 10 natural numbers from 1 to 10. This can be achieved
by using a loop starting with a counter starting at 1 and terminating with 10.
Definition of Loop: It is a programming structure used to repeatedly carry out a particular
instruction/statement until a condition is true. Flowchart equivalent for a loop is given
here:

Explanation:
1. ctr contains 1
ctr=1 2. check whether
ctr value <= 10
is true
3. hello is printed if
Repeat until ctr <=10 true
4. ctr gets
false incremented by 1
5. repeat printing
Write “hello” ‘hello’ until
exit
ctr<=10 is true
true
6. stop printing
when ctr<=10 is
false
ctr = ctr+1

 Here ctr is loop control variable and is initialized to 1


 Repeat statement in hexagon tests whether condition is true or false (ctr<=500)
 ctr=ctr+1 updates the ctr value every time
 loop repeats until ctr <=500 and prints ‘hello’ so many times

Three important components of any loop are:


1. Initialization (example: ctr=1, i=0 etc)
2. Test Condition (example: ctr<=500, i != 0 etc)
3. Updating loop control values (example: ctr=ctr+1, i =i-1)

Pre-test and Post-test loops


Loops can be classified into two types based on the placement of test-condition.
If the test-condition is given in the beginning such loops are called pre-test loops (also
known as entry-controlled loops).
Otherwise if test condition is given at the end of the loop such loops are termed as post-
test loops (or exit controlled loops).
Here is a flowchart for pre-test loops:
Here test condition is
false
at the beginning of
while (test condition) loop. That is why it is
called pre-test loop!

(Note: the word


True ‘while’ is a keyword in
Exit/stop
C language and will be
discussed in next
Body of the loop topic)

Next is flowchart for post-test loops:

do
Here test condition is
at the end of the loop.
That is why it is called
Body of the loop post-test loop!

(Note: the word


‘do….while’ is a
True keyword in C
while (test condition) language and will be
false discussed in next
topic)
Exit/stop
Loops in C:
C language provides 3 looping structures namely:
1. while loop
2. do….while loop
3. for loop

while loop: It is a pre-test loop (also known as entry controlled loop). This loop has
following syntax:
while (test condition)
{
statement-block;
}
In the syntax given above ‘while’ is a key word and test condition is at beginning of the
loop. If the test condition is true the body of while loop will be executed.
Here is an example program using while loop for finding sum of 1 to 10.
Example:
Before loop execution:
void main()
N=10, sum=0, i=1
{
N=10;
First Round:
i=1;
N=10, sum=1, i=2
sum=0;
while (i<=N)
Second Round:
{
N=10, sum=3, i=3
sum=sum+i;
i=i+1;
Third Round:
}
N=10, sum=6, i=4
printf(“%d”, sum);
}
Tenth Round:
N=10, sum=55, i=10

do…. while loop: It is a post-test loop statement (also called exit controlled loop) it has
two keywords do and while. In this loop body of the loop is executed first and then test
condition is verified.
General syntax:
do
{
statement-block;
} while (test condition);

The example already discussed with while loop to compute sum of 1 to 10 numbers is
given here with do …while loop:

void main( ) Before loop execution:


{ N=10, sum=0, i=1
N=10;
i=1; First Round:
sum=0; N=10, sum=1, i=2
do
{ Second Round:
sum=sum+i; N=10, sum=3, i=3
i=i+1;
} Third Round:
while (i<=N); N=10, sum=6, i=4
printf(“%d”, sum); …….
} Tenth Round:
N=10, sum=55, i=10
for loop: It is a pre-test loop statement (also called entry controlled loop) it has one
keyword for. In this loop first test condition is verified and based on its value body of the
loop is executed. One important aspect of for loop is all the three components of a loop
(viz. initializing, testing condition and updating (increment/decrement)) is given in the
head of for loop.

General syntax:
for( initialization; test-condition; increment)
{
Body-of loop;
}

Same program to find some of 1 to 10 numbers can be written using for loop as follows:

void main( )
{
int i, N=10, sum=0;

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


{
sum=sum+i;
}
printf(“Total =%d”, sum);
}

Note: In for loops whether both i++ or ++i operations will be treated as pre-increment
only.
Flowchart of for loop looks as follows:

for(initialization; test-condition; increment)

false
Body of loop
true exit

c-v

Nested for loops:


In some programming situations within one for loop we have to write another for loop.
Such embedded for loops are called nested for loops. Following diagram depicts a nested
for loop flowchart.

for (initialization; test-condition; increment )

true
for (initialization; test-condition; increment ) false
true
false
Body of loop
exit

Here is an example program segment with sample outputs that illustrates the working of a
nested for loop:
Example:
for(rows=1; rows<=4; rows++)
for(cols=1;cols<=3; cols++)
{
printf(“%d %d”, rows, cols);
}

Working:
1. Initially value of rows=1 and 1 <=4 is true so control enters to inner
loop
2. In inner loop cols=1 and 1<=3 is also true so body of the loop (i.e.
printf gets executed)
Following are the outputs obtained in every repetition of inner/outer for
loops:

Output: Output: Output: Output:


1st round: 2nd
round: 3rd
round: 4th
round:
rows=1,1,1 rows=2,2,2 rows=3,3,3 rows=4,4,4
cols=1,2,3 cols=1,2,3 cols=1,2,3 cols=1,2,3
Event controlled and Counter controlled loops:
We have already classified loops as pre-test and post-test loops. Now we will classify
them into two types based on the control variable used. These two types are:
1. Event controlled loops
2. Counter controlled loops
Event controlled loops continue execution until an event has occurred or an event has
failed to occur. For instance you want to calculate square of a number until end-user
chooses to stop calculation. Here is a programmatic example to illustrate it:

void main( )
{
int num, square;
char choice= ‘Y ‘;
while(choice != ‘N’)
{
printf(“Enter the number whose square is required\n”);
scanf(“%d”, &num);
square=num*num;
printf(“square is=%d”, square);
printf(“\nDo You Want to Continue? say Y/N\n”);
choice=getchar( );
}
}

Sample outputs:
Enter the number whose square is required
8
square is=64
Do You Want to Continue? say Y/N
Y
Enter the number whose square is required
9
square is=81
Do You Want to Continue? say Y/N
N
Note: in event controlled loops number of repetitions is not known in
advance
Counter controlled loops:
In these loops number of repetitions is well known in advance as counter value
determines the number of repetitions.
Example:
void main()
{

i=1;
sum=0;
while (i<=10)
{
sum=sum+i;
i=i+1;
}
printf(“%d”, sum);
}
Note: this while loop executes 10 times and calculates sum of 10 numbers.
(i.e. 1+2+3+4+5+6+7+8 +9+10=55)

Output is: 55

Initializing, Test condition and Updating: Three Components of a Loop


Normally all loops should have three components:
1. Initialization (example: i=0; j=1 etc)
2. Test condition (example: ctr<=10, i<=20 etc)
3. Updating (example: ctr=ctr+1, i=i+2 etc)
If any of these three components are missing program behaves indifferently. For instance
if updating statement is missing loop goes into infinite mode as shown in following
example:

void main( )
{
int ctr=1, N=10;
while(ctr<=N)
{
printf(“Hello World\n”);
printf(“Hi Galaxy\n”);
}
}

Output: it prints,
Hello World
Hello Galaxy
infinite number of times as ctr value remains 1 forever as
updating statement ctr=ctr+1 is missing

Let us go through same example with initialization statement missing:


Example:
void main( )
{
int ctr, N=10;
while(ctr<=N)
{
printf(“Hello World\n”);
printf(“Hi Galaxy\n”);
ctr=ctr+1;

}
Output: Loop will not at all get executed as initial value of ctr
is unknown!
So program prints nothing.
Correction to be done is ctr=1

Other statements related to looping:


Loops in C Language are associated with three important statements namely:
1. break
2. continue
3. goto
‘break’— statement is useful to terminate a loop and transfer control out of loop under
special situations. break statement works with while, do….while, for and switch
statements.
Following program syntax diagrammatically represents the working mechanism of break
statement.
void main()
{
while(condition1 ==true)
{
statement1;
statement2;
if(condition2==true)
{
break;
}
statement4;
}
statement5;
}

Note:
Working of break statement:
When condition2 is true the loop gets terminated and control is transferred to
statement5 (which is outside the loop). Here we can observe that even though
test condition1 is true loop gets terminated abruptly.
Example program for break statement:
void main()
{
int count=1, sum=0, marks;
printf(“Enter the marks of all students\n”);
while (count<=999)
{
scanf(“%d”, &marks);
if(marks <0)
{
break; /* loop is and terminated and control shifts to printf*/
}
sum=sum+marks;
count=count+1;
}
printf(“Total marks=%d”,sum)
}/* end of main*/

Sample output:
Enter the marks of all students
95 , 45 ,55, 65, 35 -7
Total marks= 295

(i.e. 95+45+55+65+35) as soon as negative number (-7) is entered the loop


is terminated

continue—Statement is helpful to skip particular set of statements in loop body and to


continue execution from the beginning of loop. Following syntax clearly depicts how
control shifts to beginning of a loop on finding continue statement.
void main()
{
while(condition1 = = true)
{
statement1;
statement2;
if(condition2= =true)
{
continue;
statement4
}
Statement5;
}
Statement6;
}

Note:
Working of continue statement:
When condition2 is true continue statement is executed which results in transfer
of control to beginning of while loop skipping statement4 and statement5.
Example program for continue statement:

void main()
{ /* beginning of main*/
int count=1, root, num;
printf(“Enter the Numbers whose Square Root is required\n”);
while (count<=999) /* begin of loop */
{
scanf(“%d”, &num);
if(num <0)
{
printf(“Negative Number”);
continue;
/* continue statement changes control to beginning of loop*/
}
root= sqrt(num);
printf(“Square root=%d”, root);
count=count+1;
}
}/* end of main*/

Sample output:
Enter the Numbers whose Square Root is required
16
Square root=4
25
Square root=5
36
Square root =6
-7
Negative number
169
Square root=13
and so on……….until count <=999

goto statements
goto is an unconditional branching statement. The syntax of goto is as follows:

goto label;
statement1;
statement2;
label:

Here control jumps to label skipping statement1 and statement2 without verifying any
condition that is the reason we call it unconditional jumping statement.
Example program:
void main( )
{
int a=5, b=7;
goto delhi;
a=a+1;
b=b+1;
delhi: printf(“a=%d b=%d”, a,b);
}

Sample output:
a=5 b=7
(Note: a and b will not be incremented because of goto statement. goto shifts control to
position where label ‘delhi’ is located)

Nested loops and goto statements:


goto statements are very useful if we have to skip nested loops. break statement can be
used only to skip innermost loop, but by using goto we can abruptly terminate nested
loops and transfer control outside the outermost loop statement.
Following example illustrates use of goto in nested for loops:
for(rows=1; rows<=4; rows++)
{
for(cols=1;cols<=3; cols++)
{
printf(“rows=%d cols=%d”, rows, cols);
goto bangalore;
}
} /* end of outer for loop*/
bangalore:
printf(“Exit from both Loops”);

Sample output:
rows=1 cols=1
Exit from outer loop

(Note: Both for loops will be executed only once and due to goto statement
outer loop will be terminated and control goes to printf statement)

Loops Applications
Let us say we have to automate soft-drinks filling plant. The bottles coming over
conveyor belt one after other has to be filled and process has to be repeated infinite
number of times. In such situations repetitive tasks has to be carried out. Loop structures
are useful in such cases.

Another example is if we have to repeatedly add same number 10 times we cannot write a
program as below:
int A=10;
A=A+10;
A=A+10;
A=A+10;
A=A+10;
A=A+10;
A=A+10;
A=A+10;
A=A+10;
A=A+10;
A=A+10;
printf(“%d”, A);
Though this program works, it is nearly impossible to write the same program for adding
‘A’ 100 times. In such situations loops are very useful.

Recursion:
Definition: It is a programming technique where a function repeatedly calls itself.
First let us go through a non-recursive function call:
void main ( )
{
int x=10, y=20, sum;
sum= add( x,y)
printf(“total=%d”, sum);
}

int add( int a, int b) Function call


{
int sum;
sum=a+b;
return(sum);
}
In the example program given above main( ) calls add ( ) function this is non-
recursive call. Now let us take example program to calculate factorial where the
user-defined function fact( ) repeatedly calls itself

void main( )
{
int n,x;
n=5;
x=fact(n);
}

int fact( int p)


{
if(p==1)
return (1);
else
y= p*fact(p-1);
fact( ) calling itself
return(y);
}

Working of recursive function for factorial evaluation:

Say n=5; means p=5

Therefore: p*fact(p-1) is substituted with following values

5*fact(5-1) in turn calls

5*(4)*fact(4-1) calls

5* (4)* (3)*fact(3-1) calls

5*(4)*(3)*(2)*fact(2-1) calls

5*(4)*( 3)*(2)*fact(1)
------------------------------------------------------------------
fact(1)returns 1
so 5*4*3*2*1 =120  factorial of 5

Programming examples

Exercises:
1. What is the output of following program segment?
N=4;
M=3;
for (i=0, j=0; i<=N || j<=M; i++, j++)
{
printf(“%d %d”, i , j);
}
Answer:
i=0,1,2,3,4
j=0,1,2,3,4

2. What is the value of k when loop completes in following code?


k=1;
while(++k <=n)
{
printf(“%d”, k);
}
a. n+1
b. n-1
c. n+2
d. n
Answer n
Suppose if n=2,
Value printed is: 2

3. for( i=1,j=3; i<3;i++,j--)


printf(“i=%d, j=%d”, i,j) Output is:
Round-1: i=1, j=3
Round-2: i=2,j=2

4. sum=0 Output is:


for(n=1; n!=10; n+=2) Round-1: n=1, 1!=10 is true
sum = sum+n; sum=1
Round-2 n=3, 3!=10 is true
sum=4
Round-3 n=5, 5!=10 is true
sum=9
Round-4 n=7, 7!=10 is true
sum=16
Round-5 n=9, 9!=10 is true
sum=25

Round-6 n=11, 11!=10 is true


sum=36

This goes infinitely……………


5. what is the output of this segment? output:
int x=5, y=50; round-1: x=50/5  10
while(x<=y) round-2: x=50/10 5
{ so
x=y/x; x will toggle between 10 & 5
} and this loop goes on
infinitely as x<=y is always
true!

6. Write for statement to print following sequences:


• 1,2,4,8,16,32
• -4,-2,0,2,4
Ans:
 for( i=1; i<=32; i=i*2)
printf(“%d”, i);
 for(i=-4; i<=4; i=i+2)
printf(“%d”, i);

You might also like