Jumping statements are used to alter the normal flow of program execution in loops or conditional blocks.
Thank you for reading this post, don't forget to subscribe!- They help manage the execution flow by skipping iterations, exiting loops, or stopping the program.
C provides three primary jumping statements:
- break Statement
- continue Statement
- goto Statement
- return Statement
1.) break Statement
The break statement is used to exit from a loop or a switch statement prematurely. It stops the execution of the loop or switch and transfers control to the next statement outside of the loop.
Example:
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit loop when i equals 5
}
printf("%d\n", i);
}
return 0;
}2.) continue Statement
The continue statement is used to skip the current iteration of a loop and move on to the next iteration. It does not terminate the loop; it just skips the code below it for the current iteration.
Example:
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // skip printing when i equals 3
}
printf("%d\n", i);
}
return 0;
}3.) goto Statement:
The goto statement allows you to jump to another part of the program by using a label. Although powerful, it’s generally discouraged due to reduced code readability.
Example:
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
if (i == 5)
goto skip;
printf("%d\n", i);
i++;
}
skip:
printf("Skipped when i = 5\n");
return 0;
}4.) return Statement:
The return statement is used to exit from a function and optionally return a value to the calling function.
- Once return is executed, the control is passed back to the caller, and the remaining code in the function (if any) is skipped.
Example:
#include <stdio.h>
// Function that returns an integer
int add(int a, int b) {
return a + b; // return sum to main
}
int main() {
int result = add(5, 3);
printf("Sum = %d\n", result);
return 0;
}