Monday 16 March 2015

Break Statement in C

1. For Loop

#include<stdio.h>
int main()
{
    int i;
    for(i=0;i<10;i++)
    {
        if(i%2!=0)
            break;
        printf("%d ",i);
    }
    return 0;
}
Output:
0

2.While Loop
#include<stdio.h>
int main()
{
    int i;
    i=0;
    while(i++<10)
    {
        if(i%2==0)
            break;
        printf("%d ",i);
    }
    return 0;

}
Output:
1

3. Do-While Loop
#include<stdio.h>
int main()
{
    int i;
    i=0;
    do
    {
        if(i%2!=0)
            break;
        printf("%d ",i);
    }while(i++<10);
    return 0;

}
Output:
0

4. Nested Loop
#include<stdio.h>
int main()
#include<stdio.h>
int main()
{
    int i,j;
    for(j=0;j<3;j++)   // outer loop
    {
        for(i=0;i<10;i++)  //inner loop
        {
            if(i%2!=0)
                break;
            printf("%d ",i);
        }
    }  
    return 0;

}
Output:
0 0 0 

5. Continue the outer loop:
#include<stdio.h>
int main()
{
    int i,j;
    Outer: for(j=0;j<3;j++)
    {
        for(i=0;i<10;i++)
        {
            if(i%2!=0)
                break Outer;
            printf("%d ",i);
        }
    }    
    return 0;
}

No comments:

Post a Comment