-4
#include<stdio.h>
#include<conio.h>

void main()
{
    int i, j, k, l;
    i = j = 0;
    clrscr();

    for(k = 0; k < 3; k++)
    {
        printf("Flag A\t");

        for(l = 0; l < 2; l++)         
        { 
            printf("Flag B\t");
            if(i == 5)
            {
                printf("Flag C\t");

                if(j == 5)
                {
                    printf("Flag D\n");
                    break;
                }
            }
            i++;
            j++;
        }
    }

    printf("Value of i=%d,j=%d,k=%d,l=%d", i, j, k, l);
    getch();
}

When I trace the output of above code, it is:

Flag A Flag B Flag B Flag A Flag B Flag B Flag A Flag B Flag B Flag C Flag D 

values of i=5 j=5 k=3 l=1

I get the same answer manually. Also, my question is: when I trace the output, the break condition occurs when i=5 and j=5. At that time, control breaks two if loops and the l for loop, and gets started from the next iteration of the k for loop. Is that the regular behavior of the break (cracks 3 nested loops when it is nested inside 3 loops), or does it happen due to the combination of the loops? What happens if I use other possible combinations of the loops? Please explain behavior of the break statement when it's used with multiple combinations of other loops. Please explain behavior with switch also.

SumS
  • 25
  • 6

1 Answers1

2

Note that if is not considered a loop. Rather it is a decision structure.

The only loops you have in this example are the two for loops. The break will stop the execution of the inner-most for loop.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • @ code-apprentice-I assume while,do while & switch are also loops & if is the decision making statement ?? – SumS Sep 07 '14 at 06:11
  • 2
    @SumeetBajiraoGaikwad `switch` is not a loop. The word "loop" implies a repetition of some kind. Neither `if` nor `switch` cause a repetition. Only `for`, `while`, and `do...while` are repeating structures and therefore the only flavors of loops in C. – Code-Apprentice Sep 07 '14 at 06:12