Saturday 25 October 2014

Control Statement break and continue

Break Statement

break statement is used inside loops and switch statements. Sometime it becomes necessary to come out of the loop even before the condition becomes false. in such a situation, break statement is used to terminate the loop. This statement causes an immediate exit from that loop in which this statement appears. it can be written as-

break;
When break statement is encountered, loop is terminated and the control is transferred to the statement immediately after the loop. The break statement is generally written along with a condition. if condition. if break is written inside a nested loop structure then it causes exit from the innermost loop.


// program to understand the use of break/

#include<stdio.h>
main()
{
int n;
for(n=1;n<=5;n++)
{
     if(n==3)
     {
       printf("I understand the use of break\n");
       break;
     }
       printf("Number =%d\n",n);
}
printf("Out of for loop\n");
}

Output:

Number=1
Number=2
I understand the use of break
out of for loop

// program to understand use of break another example:
#include<stdio.h>
main()
{
    int choice;
    printf("Enter Your choice:");
    scanf("%d",&choice);
    switch(choice)
    {
        case 1:
        printf("First\n");
        break;
          
          case 2:
          printf("Second\n");
           break;
          
           case 3:
           printf("Third\n");
             break;
          
           default:
           printf("Wrong choice:\n");

}

Output

Enter your choice : 2
second 

in second example when break find then compiler goes out of switch condition, if we does not use break condition in the above example then if we select case 1 then print "First" as well as "second" Third and wrong choice all printed because c is sequential programming language program compile in sequentially, when above program compiler find the break that terminate the condition and goes out of that block. 


1 comment:

  1. 1xBet korean | Legalbet Sports
    1XBet is the premier online casino 온카지노 providing sports betting and betting to players around the world. With 1xbet korean its unique 3D graphics, you can experience 제왕 카지노 the thrill

    ReplyDelete