0
**What is the usage of "Break" statement here and how 6 came on the output? **
#include <stdio.h> main() { int i, j, x = 0; for (i = 0; i < 5; ++i) for (j = 0; j < i; ++j) { x += (i + j - 1); printf("%d\n", x); break; } printf("\nx = %d\n", x); } Output on compiler: 0 1 3 6 x = 6 Press any key to continue . . .
1 Answer
0
i loop
x = 0, i = 0, i < 5, goto j loop
i = 0, j = 0, j == i, not match, ++i, i = 1, goto next i loop
x = 0, i = 1, i < 5, goto j loop
i = 1, j = 0, j < i, execute the block
i = 1, j = 0, x = 0, i + j - 1 = 0, x = x + 0, x = 0, output x, break all of this j loop, ++i, i = 2, goto next i loop
x = 0, i = 2, i < 5, goto j loop
i = 2, j = 0, j < i, execute the block
i = 2, j = 0, x = 0, i + j - 1 = 1, x = x + 1, x = 1, output x, break all of this j loop, ++i, i = 3, goto next i loop
x = 1, i = 3, i < 5, goto j loop
i =3, j = 0, j < i, execute the block
i = 3, j = 0, x = 1, i + j - 1 = 2, x = x + 2, x = 3, output x, break all of this j loop, ++i, i = 4, goto next i loop
x = 3, i = 4, i < 5, goto j loop
i =4, j = 0, j < i, execute the block
i = 4, j = 0, x = 3, i + j - 1 = 3, x = x + 3, x = 6, output x, break all of this j loop, ++i, i = 5, goto next i loop
x = 6, i = 5, i == 5, not match, end i loop
i = 5, x = 6, output x