Exit Multiple Loops using Goto or Flags in C
In C, we can exit multiple loops using techniques such as the goto
statement or a flag variable. The goto
statement allows us to jump to a labeled section in the program, effectively breaking out of nested loops, while a flag variable is used as a condition to control the loop execution.
Examples of Exiting Multiple Loops
1. Exiting Multiple Loops Using goto
In this example, we will use the goto
statement to exit a nested loop when a specific condition is met.
main.c
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i == 3 && j == 2) {
goto exit_loops; // Exit both loops
}
printf("i = %d, j = %d\n", i, j);
}
}
exit_loops:
printf("Exited from loops\n");
return 0;
}
Explanation:
- We have two nested
for
loops iterating from 1 to 5. - Inside the inner loop, we check if
i == 3
andj == 2
. - If the condition is met, we use the
goto
statement to jump to the labelexit_loops
. - This skips all remaining iterations of both loops and executes the statement after
exit_loops:
.
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 1, j = 4
i = 1, j = 5
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 2, j = 4
i = 2, j = 5
i = 3, j = 1
Exited from loops
2. Exiting Multiple Loops Using a Flag Variable
In this example, we will use a flag variable to break out of nested loops when a condition is met.
main.c
#include <stdio.h>
int main() {
int flag = 0; // Flag variable to indicate loop exit
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i == 3 && j == 2) {
flag = 1; // Set flag to 1 to indicate exit condition
break;
}
printf("i = %d, j = %d\n", i, j);
}
if (flag) break; // Break outer loop if flag is set
}
printf("Exited from loops\n");
return 0;
}
Explanation:
- We declare an integer
flag
initialized to 0. - In the inner loop, we check if
i == 3
andj == 2
. - If the condition is met, we set
flag = 1
and break the inner loop. - After the inner loop, we check if
flag
is set, and if so, we break the outer loop.
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 1, j = 4
i = 1, j = 5
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 2, j = 4
i = 2, j = 5
i = 3, j = 1
Exited from loops
Conclusion
We explored two methods for exiting multiple loops in C:
- Using
goto
: Directly jumps to a labeled section in the program. - Using a Flag Variable: Uses a variable to indicate when to break out of loops.
Both methods are useful depending on the scenario, but using goto
should be limited as it can make code harder to read. The flag approach is generally more readable and structured.