Tuesday, 2 May 2017

Loops



How to use Loops in C Language

In any programming language, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

How it Works


A sequence of statements are executed until a specified condition is true. This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After every execution of loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not executed.

There are 3 type of Loops in C language

  1. while loop(entry controlled loop)
  2. for loop(entry controlled loop)
  3. do-while loop(exit controlled loop)

while loop

while loop can be addressed as an entry control loop. It is completed in 3 steps.
  • Variable initialization.( e.g int x=0; )
  • condition( e.g while( x<=10) )
  • Variable increment or decrement ( x++ or x-- or x=x+2 )
Syntax :
variable initialization ;
while (condition)    
{     
statements ;    
variable increment or decrement ;     
}        
  

Example : Program to print first 10 natural numbers

#include<stdio.h>  
#include<conio.h>  
void main( )  
{   
int x;   
x=1;   
while(x<=10)   
{     
printf("%d\t", x);     
x++;   
}   
getch();  
}  
Output
1 2 3 4 5 6 7 8 9 10  

for loop

for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. we can say it an open ended loop. General format is,
for(initialization; condition ; increment/decrement)  
{    
statement-block;  
}        


In for loop we have exactly two semicolons, one after initialization and second after condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. for loop can have only one condition.

Above Example with for loop

#include<stdio.h>    
#include<conio.h>    
void main( )    
{     
int x;     
for(x=1; x<=10; x++)     
{       
printf("%d\t",x);     
}     
getch();    
}  
Output
1 2 3 4 5 6 7 8 9 10  

Nested for loop

We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,
for(initialization; condition; increment/decrement)    
{      
for(initialization; condition; increment/decrement)         
{            
statement ;         
}    
}  

Example : Program to print half Pyramid of numbers

#include<stdio.h>    
#include<conio.h>    
void main( )    
{   
int i,j;     
for(i=1;i<5;i++)     
{       
printf("\n");       
for(j=i;j>0;j--)       
{         
printf("%d",j);       
}     
}     
getch();    
}  
Output
1  21  321  4321  54321  

In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. General format of do-while loop is,
it's exit control loop
c-do-while
do    
{ 
      
statement(s);      
}  while( condition );        

Example : Program to print first ten multiple of 5.

#include<stdio.h>    
#include<conio.h>    
void main()    
{     
int a,i;   
a=5;   
i=1;     
do   
{      
 printf("%d\t",a*i);       
i++;    
}while(i <= 10);   
 getch();    
}  
Output
5 10 15 20 25 30 35 40 45 50  

Jumping Out of Loops

Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true, that is called jumping out of loop. C language allows jumping from one statement to another within a loop as well as jumping out of the loop.

1) break statement

When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.
https://cdn.programiz.com/sites/tutorial2program/files/c-break-statement.jpg
break statement in loops in c language
// Program to calculate the sum of maximum of 10 numbers    
// Calculates sum until user enters positive number      
# include <stdio.h>    
int main()    
{        
int i;       
 double number, sum = 0.0;          
for(i=1; i <= 10; ++i)        
{            
printf("Enter a n%d: ",i);            
scanf("%lf",&number);              // If user enters negative number, loop is terminated            
if(number < 0.0)            
{               
 break;            
}              
sum += number; // sum = sum + number;        
}          
printf("Sum = %.2lf",sum);              
return 0;    
}
Output
Enter a n1: 2.4  Enter a n2: 4.5  Enter a n3: 3.4  Enter a n4: -3  Sum = 10.30  

2) continue statement

It causes the control to go directly to the test-condition and then continue the loop process. On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.
Flowchart of continue statement
continue statement in loops in c language
/ Program to calculate sum of maximum of 10 numbers    
// Negative numbers are skipped from calculation      
# include <stdio.h>    
int main()    
{        
int i;        
double number, sum = 0.0;          
for(i=1; i <= 10; ++i)        
{            
printf("Enter a n%d: ",i);            
scanf("%lf",&number);              
// If user enters negative number, loop is terminated            
if(number < 0.0)            
{                
continue;            
}              
sum += number;   // sum = sum + number;        
}         
printf("Sum = %.2lf",sum);              
return 0;    
}  
Output
Enter a n1: 1.1    
Enter a n2: 2.2    
Enter a n3: 5.5    
Enter a n4: 4.4    
Enter a n5: -3.4    
Enter a n6: -45.5    
Enter a n7: 34.5    
Enter a n8: -4.2    

No comments:

Post a Comment

Please write your view and suggestion....