Jump statements are used to transfer control to a different part of the program. There are several jump statements available in C language:
break: The break statement is used to exit a loop or switch statement. When the break statement is encountered inside a loop or switch, the loop or switch is immediately terminated, and control is transferred to the statement following the loop or switch.
continue: The continue statement is used to skip the rest of the current iteration of a loop, and proceed to the next iteration. When the continue statement is encountered inside a loop, the rest of the loop is skipped, and control is transferred to the beginning of the next iteration.
goto: The goto statement is used to transfer control to a labeled statement in the same function. The labeled statement can be anywhere in the function, and control is transferred to it unconditionally.
Here is an example that demonstrates the use of break and continue statements:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 5) {
break; // exit the loop when i becomes 5
}
printf("%d ", i);
}
printf("\n");
for (i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // skip the rest of the loop when i is even
}
printf("%d ", i);
}
printf("\n");
return 0;
}
In this example, the first loop iterates from 0 to 9, and terminates when i becomes 5 (break statement is encountered). The output of this loop is “0 1 2 3 4”. The second loop iterates from 0 to 9, but skips the rest of the loop when i is even (continue statement is encountered). The output of this loop is “1 3 5 7 9”.
Here is an example that demonstrates the use of the goto statement:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 5) {
goto end; // jump to the labeled statement when i becomes 5
}
printf("%d ", i);
}
printf("\n");
end:
printf("Done\n");
return 0;
}
In this example, the loop iterates from 0 to 9, and jumps to the labeled statement when i becomes 5 (goto statement is encountered). The output of this code is “0 1 2 3 4 Done”.
It is generally recommended to avoid using the goto statement, as it can make the code difficult to understand and maintain. The break and continue statements are generally preferred for controlling the flow of loops.