When ever we want to exit from the loop or from a function like main()/user defined function we use Break statement.It comes out of the loop and goes to the next line of the program.It exits only from the loop in which it has been written.
Syntax:-break;
Ex:- Case 1:-To print values from 1-n with in 100 using break statement.
#include<stdio.h> main() { int i,n; printf("Enter any number between 1-100\n"); scanf("%d",&n); for(i=1;i<=100;i++) { if(i!=n+1) { printf("I am in for loop with value %d\n",i); } else { break; } } printf("Out of for loop\n"); }
Explanation:-
Program:-
- In the above program first it takes the value of n
- Then for loop runs as normal from 1-100 and for every number it checks whether the value of 'i' is equal to the given number or not.
- If it is not equal then it prints the value of 'i' other wise goes to the else part where we had given break statement and this statement gets executed causing the loop to terminate(come out of the loop instatntly) at n+1 (here in the below output I have given 6 as 'n' so it terminates when 'i' is at 7 so that the values from 1-6 are printed).
- Then it goes to the next line of loop.
Output:-
Case 2:-
If we have two loops one within the other and the break is existed in the 2nd loop then,only the loop containing break statement gets terminated i.e 2nd loop and goes to the next line which is the first loop and the process goes on.
Ex:-
#include<stdio.h> main() { int i,j,n; for(i=1;i<=5;i++) { for(j=1;j<=5;j++) { if(i==j) { printf("I am in 2nd for loop \n"); } else { break; } } printf("I am in 1st for loop \n"); } printf("I am in main()\n"); }Explanation:-
Program:-
- Here in the above program when ever i becomes equal to j then the statement in the 2nd loop prints other wise it goes to the next loop i.e the loop which gets executed after the loop(here 1st loop).
- But in the above program the statement in 2nd loop gets printed only one time because of the following reason:-
- 1st step:---Wen i=0 the compiler moves to 2nd loop as i<=5 then at 2nd loop j=0 so both are equal then the statement in 2nd loop gets printed.Now it iterates again to the 2nd loop but now j=1 so the break executes which causes compiler to come out of loop and prints the statement "I am in the 1st loop" which is in 1st loop.
- 2nd step:--Now i becomes 1 (and i<=5) so which is not equal to j=0 so it break out of the loop and prints the statement in 1st loop which is "I am in the 1st loop" so the same continues until i=5.
- 3rd step:- After i=6 it does not satisfy the condition i<=5 so it comes out all the loops and then prints the statement I am in main()
OUTPUT:-
No comments:
Post a Comment