Nesting of loop | Break Statement | Continue statement tutorial for beginners | C program | Codingclasspoint

Nesting of loop 



When a loop written inside the body of another loop then, it is known as nesting of loop. Any type of loop can be nested in any type such as while, do while, for. For example nesting of for loop can be represented as :

void main() 

{ int i,j; 

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

 for(j=0;j<5; j++) 

printf(“%d %d”, i, j); 

 } 

Output: 

i=0 

 j=0 1 2 3 4

 i=1 

 j=0 1 2 3 4

Break statement(break)

Sometimes it becomes necessary to come out of the loop even before loop condition becomes false then break statement is used. Break statement is used inside loop and switch statements. It cause immediate exit from that loop in which it appears and it is generally written with condition. It is written with the keyword as break. When break statement is encountered loop is terminated and control is transferred to the statement, immediately after loop or situation where we want to jump out of the loop instantly without waiting to get back to conditional state. 

When break is encountered inside any loop, control automatically passes to the first statement after the loop. This break statement is usually associated with if statement. 

Example : 

void main() 
{
int j=0; 
for(;j<6;j++) 
if(j==4) 
break; 

Output: 0 1 2 3

Continue statement (key word continue)

Continue statement is used for continuing next iteration of loop after skipping some statement of loop. When it encountered control automatically passes through the beginning of the loop. It is usually associated with the if statement. It is useful when we want to continue the program without executing any part of the program. 

The difference between break and continue is, when the break encountered loop is terminated and it transfer to the next statement and when continue is encounter control come back to the beginning position. 

In while and do while loop after continue statement control transfer to the test condition and then loop continue where as in, for loop after continue control transferred to the updating expression and condition is tested. 

Example 

void main() 
int n; 
for(n=2; n<=9; n++) 
if(n==4)
continue; 
printf(“%d”, n); 
 } 
}
Printf(“out of loop”); 
}

Output: 2 3 5 6 7 8 9 out of loop 

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.