Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Jump Statements
break, continue, return

In C, jump statements are used to control the flow of execution in a program. The primary jump statements are break, continue, and return. Each serves a different purpose in managing how loops and functions behave.

1. break Statement

The break statement is used to exit from loops (for, while, do-while) or switch statements prematurely. When a break statement is encountered, control is transferred to the statement immediately following the loop or switch.

Example:

#include <stdio.h>

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            break;  // Exit the loop when i is 5
        }
        printf("%d ", i);  // Output: 0 1 2 3 4
    }
    printf("\nLoop exited at i = 5\n");
    return 0;
}

In this example, the loop prints numbers from 0 to 4. When i reaches 5, the break statement is executed, and the loop is terminated.

2. continue Statement

The continue statement is used to skip the current iteration of a loop and jump to the next iteration. In for loops, it goes to the update expression; in while and do-while loops, it goes to the condition check.

Example:

#include <stdio.h>

int main() {
    for (int i = 0; i < 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip the even numbers
        }
        printf("%d ", i);  // Output: 1 3 5 7 9
    }
    printf("\n");
    return 0;
}

In this example, the loop skips printing even numbers. When i is even, the continue statement is executed, moving control to the next iteration of the loop.

3. return Statement

The return statement is used to exit from a function and optionally return a value to the calling function. In main, it can indicate the program’s exit status (typically 0 for success).

Example:

#include <stdio.h>

int add(int a, int b) {
    return a + b;  // Return the sum of a and b
}

int main() {
    int result = add(5, 3);
    printf("Result of addition: %d\n", result);  // Output: 8
    return 0;  // Exit the program with status 0
}

In this example, the add function returns the sum of two integers, which is then printed in the main function. The return statement in main indicates that the program completed successfully.

Summary

StatementPurposeUsage
breakExit a loop or switch statement prematurelyUsed in loops and switch cases
continueSkip the current iteration and continue with the next oneUsed in loops (for, while, do-while)
returnExit a function and optionally return a valueUsed in functions

    Leave a Reply

    Your email address will not be published.

    Need Help?