CSE NotesCSE Notes
Simplifying Complexity

for loop

The for loop in C is a control flow statement that allows you to execute a block of code repeatedly with a counter. It is commonly used when the number of iterations is known beforehand. Here’s a breakdown of its syntax, structure, and some examples.

Syntax

The basic syntax of a for loop is as follows:

for (initialization; condition; increment/decrement) {
// Code to be executed
}

Components

  1. Initialization: This step is executed once at the beginning of the loop. It typically initializes a counter variable.
  2. Condition: Before each iteration, the condition is evaluated. If it evaluates to true (non-zero), the loop body is executed. If it evaluates to false (zero), the loop terminates.
  3. Increment/Decrement: This step is executed after each iteration of the loop body. It typically updates the counter variable.

Example 1: Counting from 1 to 10

Here’s a simple example that counts from 1 to 10 and prints each number:

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
printf(“%d “, i);
}
printf(“\n”);
return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

Example 2: calculates the sum of the first 10 natural numbers:

#include <stdio.h>

int main() {
int sum = 0;

for (int i = 1; i <= 10; i++) {
sum += i; // Add i to sum
}

printf(“Sum of first 10 natural numbers: %d\n”, sum);
return 0;
}

Output

Sum of first 10 natural numbers: 55

Example 3: Nested For Loop

You can also nest for loops. Here’s an example of a simple multiplication table:

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
printf(“%d\t”, i * j); // Print product
}
printf(“\n”); // New line after each row
}
return 0;
}

1     2    3     4    5     6     7     8     9     10
2    4    6     8    10   12   14   16    18   20
3    6    9     12   15   18   21   24   27   30

10 20 30    40  50  60  70  80    90   100

Key Points

  • Loop Control: You can use break to exit the loop prematurely and continue to skip the current iteration and move to the next one.
  • Variable Scope: Variables declared in the initialization part of the for loop are local to the loop and cannot be accessed outside it.
  • Multiple Variables: You can initialize multiple variables in the for loop:

for (int i = 0, j = 10; i < 10; i++, j–) {
printf(“%d %d\n”, i, j);
}

The for loop is a powerful and flexible control structure in C that allows for concise iteration, making it ideal for situations where the number of iterations is predetermined. Whether counting, summing, or executing complex nested iterations, the for loop is a fundamental tool in programming.