C Programs Tutorials | IT Developer
IT Developer

C Programming - C for Loop



Share with a Friend

C Programming - C for Loop

for Loop in C

The for loop is a control flow statement used to repeatedly execute a block of code a known number of times. It is particularly useful when the number of iterations is known in advance, and the loop needs to run a specific number of times.

The for loop in C combines initialization, condition checking, and iteration in a single statement, making it concise and efficient.

Syntax of for Loop:

C

for (initialization; condition; update) {

    // Code to be executed

}

  • initialization: This step is executed first, and typically involves initializing one or more loop counters or variables.
  • condition: This is checked before each iteration. If it evaluates to true (non-zero), the loop continues. If it evaluates to false (zero), the loop terminates.
  • update: This is executed after each iteration, typically to update the loop counter.

How for Loop Works:

  1. Initialization: The loop counter is initialized.
  2. Condition Check: Before each iteration, the condition is checked. If the condition is true, the loop continues. If false, the loop terminates.
  3. Loop Body Execution: If the condition is true, the loop body executes.
  4. Update: After each iteration, the loop counter or condition variable is updated (typically incremented or decremented).
  5. Termination: When the condition becomes false, the loop exits.

Example:

C

#include <stdio.h>

int main() {

    // A simple for loop to print numbers from 0 to 4

    for (int i = 0; i < 5; i++) {

        printf("i = %d\n", i);

    }

    return 0;

}

Explanation:

  • The loop counter i is initialized to 0.
  • The condition i < 5 is checked. If true, the loop body executes.
  • After each iteration, i is incremented by 1.
  • The loop stops when i becomes 5, at which point the condition i < 5 is false.

Output:

i = 0

i = 1

i = 2

i = 3

i = 4

Variations of the for Loop:

  1. Multiple Initialization: You can initialize multiple variables in the initialization part by separating them with commas.

C

for (int i = 0, j = 10; i < 5; i++, j--) {

    printf("i = %d, j = %d\n", i, j);

}

Explanation:

    • Initializes i to 0 and j to 10.
    • Increments i and decrements j in each iteration.
  1. Omitting Parts: You can omit any part of the for loop, as long as the semicolons remain.
    • Omitting Initialization:

C

int i = 0;

for (; i < 5; i++) {

    printf("i = %d\n", i);

}

    • Omitting Condition: If the condition is omitted, the loop will run indefinitely unless there is a break or another exit condition.

C

for (int i = 0; ; i++) {

    if (i == 5) break;  // Exits the loop when i becomes 5

    printf("i = %d\n", i);

}

    • Omitting Update: The update can also be omitted, but you will need to manually update the counter inside the loop.

C

for (int i = 0; i < 5;) {

    printf("i = %d\n", i);

    i++;  // Manually updating the loop counter

}

Nested for Loop:

A nested for loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.

Example:

C

#include <stdio.h>

int main() {

    // Nested for loop to print a multiplication table

    for (int i = 1; i <= 3; i++) {

        for (int j = 1; j <= 3; j++) {

            printf("%d\t", i * j);

        }

        printf("\n");

    }

    return 0;

}

Explanation:

  • The outer loop runs 3 times (i from 1 to 3).
  • For each iteration of the outer loop, the inner loop runs 3 times (j from 1 to 3).
  • This prints the multiplication table for numbers 1 to 3.

Output:

1       2       3      

2       4       6      

3       6       9      

for Loop with break and continue Statements:

  • break: Terminates the loop immediately.
  • continue: Skips the current iteration and moves to the next iteration.

Example with break and continue:

C

#include <stdio.h>

int main() {

    for (int i = 0; i < 10; i++) {

        if (i == 5) {

            break;  // Exit the loop when i equals 5

        }

        if (i % 2 == 0) {

            continue;  // Skip even numbers

        }

        printf("i = %d\n", i);  // Prints only odd numbers less than 5

    }

    return 0;

}

Explanation:

  • When i == 5, the break statement terminates the loop.
  • When i is even, the continue statement skips that iteration.

Output:

i = 1

i = 3

Summary of for Loop:

  • The for loop is a powerful looping mechanism that is typically used when the number of iterations is known in advance.
  • The initialization, condition, and update can be customized to suit various needs.
  • It is a preferred loop when performing tasks that require counting or repeating tasks with a known limit.

Advantages:

  • Compact syntax.
  • Efficient for known iteration count.
  • Easy to manage and read when iteration conditions are straightforward.

Disadvantages:

  • Can be overused or become less readable for complex looping conditions or when the loop condition changes in multiple places.