For Loop in C

The for loop is used when the number of iterations is known. It provides a concise way to initialize a loop variable, check a condition, and update the variable in one line.

Syntax of For Loop

for (initialization; condition; update) {
    // Code to execute
}

Example: Printing an Array

#include <stdio.h>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int i;
    for (i = 0; i < 5; i++) {
        printf("Element %d: %d\n", i, numbers[i]);
    }
    return 0;
}

Output:

Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
                    

Code Explanation: The for loop initializes i to 0, checks that i < 5, and increments i after each iteration. It accesses each element of the array.

Best Practices

  • Use the for loop when the number of iterations is known.
  • Keep the initialization, condition, and update expressions concise.
  • Use meaningful variable names for loop counters.

Don'ts

  • Don't modify the loop counter within the loop body unless necessary.
  • Don't use floating-point variables as loop counters.
  • Don't forget to update the loop counter; this can lead to infinite loops.
  • Key Takeaways

    • The for loop is ideal for situations where the number of iterations is predetermined.
    • Combines initialization, condition, and update in one line for clarity.
    • Proper use of the for loop enhances code readability and efficiency.