Day 5 Tutorials

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Loops in C

• Set of statements are executed repeatedly

• This is achieved by loop statements

• Loops are helpful in writing efficient programs

• Types of loops
– while
– do while
– for
Loops in C
while loop (Entry Controlled loop)

Syntax: Analysis

while(test expression)
i test Condition print step
statements;

0 0<3 -T I am in loop 1

Example :
1 1<3 - T I am in loop 2
main()
{
int i =0; 2 2<3 -T I am in loop 3
while ( i < 3)
{
printf(“I am in loop\n”); 3 3<3 -F Out of Loop
i++;
}
printf(“Out of loop”) ;
}
Loops in C
do while (exit controlled loop)
Analysis
Syntax:
do {
statements;
i print step test Condition
} while(test_expression);
0 I am in loop 1 1 <3 -T
Example : 1 I am in loop 2 2 <3 -T
main()
{ 2 I am in loop 3 3 <3 -F
int i =0;
do 3 Out of Loop
{
printf(“I am in loop\n”);
i++;
} while ( i < 3) ;

printf(“Out of loop”) ;
}
Loops in C
for loop
Execution Sequence

Syntax:
for ( initialize; test_exp ; step) Initialize
{
statements;
}

Example : Test
Expression
main()
{
int i;

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


{
Step Loop Body
printf(“ In the loop”);
}
printf(“Out of loop”) ;
}
Infinite loops
While loop Using while loop Using do while loop

main() #define TRUE 1 #define TRUE 1


{ main() main()
while( Non_Zero ) // TRUE { {
printf("I am in loop\n"); while(TRUE)
printf("In loop\n"); do
} {
} printf("In loop\n");
}while(TRUE)
}
Nested Loops
Nested while loops Output :
main() 00
{ 01
int i = 0, j; 10
while(2<2) 11
{
j=0;
while( j <2)
{
printf(“%d %d\n”, i , j);
j++;
}
i++;
}
printf(“Out of loop\n”);
}
Nested Loops

Nested for loops OUTPUT:


main() 00
{ 01
int I, J; 10
11
for( I = 0 ; I < 2 ; I++ )
{
for( J=0; j<2 ; J++)
printf(“%d %d\n”, I, J);
}
printf(“Out of the loop”);
}
1. Find the some of the given N digit number

2. Print the multiplication of 2

3. Print all odd numbers between 0 and 100

4. Find 2N

5. Find the factorial of a number

6. Check if a given N digit number is palindrome


break and continue statements
• break statement – can be used inside switch or loop
• it will permanently terminate the loop or switch block
main()
{
int i=0;
while(i<5)
{
if(i==2)
{
break;
}
printf(“The value of I = %d”, i);
i++;
}
printf(“Out of Loop”);
}
continue statement
• continue statement – can be used only inside the loops
• it will terminate only the current iteration of the loop
main()
{
int i=0;
while(i<5)
{
i++;
if(i==2)
{
continue;
}
printf(“The value of I = %d”, i);
}
printf(“Out of Loop”);
}

You might also like