Jump Statement in C

Jump statements in C are used to alter the normal flow of program execution. They allow you to transfer control to a different part of the program based on certain conditions. There are three main jump statements in C: break, continue, and return.

1. break statement

The break statement is used to terminate the execution of the innermost loop or switch statement. When encountered, it causes the program to exit the current loop or switch statement and resume execution at the next statement after the loop or switch.

Syntax

while (condition) {
    if (someCondition) {
        break; // exits the loop
    }
    // other code
}

Example

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break; // terminates the loop when i equals 5
    }
    printf("%d\n", i);
}

In this example, the break statement is used to exit the loop when i equals 5.

2. continue statement

The continue statement is used to skip the remaining code in the current iteration of a loop and proceed to the next iteration. It causes the program to jump directly to the loop's control expression or condition.

Syntax

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        continue; // skips the code below and proceeds to the next iteration
    }
    // code to be executed for each iteration except when i equals 5
}

Example

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue; // skips the remaining code for even numbers
    }
    printf("%d\n", i);
}

In this example, the continue statement is used to skip the printf statement for even numbers and proceed to the next iteration of the loop.

3. return statement

The return statement is used to terminate the execution of a function and return a value (if the function has a non-void return type) back to the caller. It can be used at any point within a function.

Syntax

int addNumbers(int a, int b) {
    int sum = a + b;
    return sum; // returns the sum to the caller
}

Example

int multiply(int a, int b) {
    if (a == 0 || b == 0) {
        return 0; // returns 0 if either operand is 0
    }
    return a * b; // returns the product of a and b
}

In this example, the return statement is used to exit the function and return a value back to the caller.

Jump statements provide control over the flow of execution in a program by allowing you to break out of loops, skip iterations, or terminate functions. They are useful for handling specific conditions and controlling program behavior based on different scenarios.

Next Article ❯