Friday, June 21, 2024

LOOP STATEMENT

Loop statements are used to execute a block of code repeatedly, either for a specified number of times or until a certain condition is met. Here's an overview of various loop constructs and control statements:

  • for: Repeats code a specified number of times.
  • for/in: Iterates over the properties of an object (JavaScript).
  • for/of: Iterates over iterable objects (JavaScript).
  • while: Repeats code as long as a condition is true.
  • do/while: Executes code once, then repeats as long as a condition is true.
  • Infinite Loop: Runs indefinitely.
  • break: Exits the loop immediately.
  • continue: Skips to the next iteration of the loop.


1. for Loop


The for loop is used when you know in advance how many times you want to execute a statement or a block of statements.

  • Syntax:
    for (initialization; condition; update) {
    // code to be executed
    }

  • Example:
    for (int i = 0; i < 5; i++) {
    printf("i = %d\n", i);
    }


2. for/in Loop (JavaScript)

The for...in loop iterates over the properties of an object.

  • Syntax:
    for (variable in object) {
    // code to be executed
    }

  • Example:
    let person = {fname: "John", lname: "Doe", age: 25};
    for (let x in person) {
    console.log(x + ": " + person[x]);
    }


3. for/of Loop (JavaScript)

The for...of loop iterates over iterable objects (arrays, strings, etc.).

  • Syntax:
    for (variable of iterable) {
    // code to be executed
    }

  • Example:
    let arr = [1, 2, 3, 4, 5];
    for (let value of arr) {
    console.log(value);
    }


4. while Loop

The while loop executes a block of code as long as the specified condition is true.

  • Syntax:
    while (condition) {
    // code to be executed
    }

  • Example:
    int i = 0;
    while (i < 5) {
    printf("i = %d\n", i);
    i++;
    }


5. do/while Loop

The do/while loop is similar to the while loop, but it executes the block of code once before checking the condition.

  • Syntax:
    do {
    // code to be executed
    } while (condition);

  • Example:
    int i = 0;
    do {
    printf("i = %d\n", i);
    i++;
    } while (i < 5);


6. Infinite Loop

An infinite loop runs indefinitely because the condition never becomes false. Use with caution.

  • Example:
    while (1) {
    // code to be executed endlessly
    }


    for (;;) {
    // code to be executed endlessly
    }


7. break Statement

The break statement exits the loop immediately.

  • Syntax:
    for (int i = 0; i < 10; i++) {
    if (i == 5) {
    break;
    }
    printf("i = %d\n", i);
    }


8. continue Statement

The continue statement skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.

  • Syntax:
    for (int i = 0; i < 10; i++) {
    if (i == 5) {
    continue;
    }
    printf("i = %d\n", i);
    }


No comments:

Post a Comment