Home C for loops in C tutorial

for loops in C tutorial

In C programming, the for loop is used for iterating over a sequence of values or a range of numbers.

It’s commonly used when the number of iterations is known in advance.

The for loop provides a compact syntax that combines initialization, condition-checking, and increment or decrement in a single line.

1. Basic Syntax of the for Loop

for (initialization; condition; increment/decrement) {
    // Code to execute on each iteration
}
  • Initialization: Sets up the loop control variable (usually a counter).
  • Condition: The loop continues as long as this condition is true.
  • Increment/Decrement: Updates the loop control variable each time the loop runs.

2. Basic Example of for Loop

Here’s a simple example of a for loop that prints numbers from 1 to 5.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }

    return 0;
}

Explanation:

  • int i = 1: Initializes i to 1.
  • i <= 5: The loop runs as long as i is less than or equal to 5.
  • i++: Increments i by 1 after each iteration.

Output:

1
2
3
4
5

3. for Loop with Decrement

You can use the for loop to count down by decrementing the loop control variable.

#include <stdio.h>

int main() {
    for (int i = 5; i >= 1; i--) {
        printf("%d\n", i);
    }

    return 0;
}

Explanation:

  • The loop starts with i = 5 and decrements i by 1 on each iteration until i is less than 1.

Output:

5
4
3
2
1

4. for Loop with Multiple Initialization and Increment Statements

The for loop can initialize and increment multiple variables.

#include <stdio.h>

int main() {
    for (int i = 1, j = 10; i <= 5; i++, j -= 2) {
        printf("i = %d, j = %d\n", i, j);
    }

    return 0;
}

Explanation:

  • The loop initializes two variables, i and j.
  • i increments by 1, while j decrements by 2 on each iteration.

Output:

i = 1, j = 10
i = 2, j = 8
i = 3, j = 6
i = 4, j = 4
i = 5, j = 2

5. Infinite for Loop

An infinite loop occurs when the loop condition never becomes false. You can create an infinite for loop by omitting the condition.

#include <stdio.h>

int main() {
    for (;;) {
        printf("This is an infinite loop.\n");
        break; // Break statement to exit the loop
    }

    return 0;
}

Explanation:

  • The condition is omitted, making the loop infinite. However, the break statement inside the loop stops it after one iteration.

Output:

This is an infinite loop.

6. Summing Numbers Using for Loop

A for loop can be used to calculate the sum of a series of numbers.

#include <stdio.h>

int main() {
    int sum = 0;

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

    printf("The sum of numbers from 1 to 10 is: %d\n", sum);

    return 0;
}

Explanation:

  • The loop iterates from 1 to 10, adding each i to sum.
  • After the loop, sum contains the total of all numbers from 1 to 10.

Output:

The sum of numbers from 1 to 10 is: 55

7. for Loop with Arrays

The for loop is commonly used to iterate over arrays.

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);

    for (int i = 0; i < size; i++) {
        printf("Element %d: %d\n", i, arr[i]);
    }

    return 0;
}

Explanation:

  • sizeof(arr) / sizeof(arr[0]) calculates the number of elements in arr.
  • The loop iterates over each element, printing the value.

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

8. Nested for Loops

A for loop can be nested inside another for loop, which is useful for multi-dimensional data like matrices.

Example: Printing a 3×3 Matrix

#include <stdio.h>

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            printf("%d ", j);
        }
        printf("\n");
    }

    return 0;
}

Explanation:

  • The outer loop iterates over rows, while the inner loop iterates over columns, printing numbers in a 3×3 grid.

Output:

1 2 3 
1 2 3 
1 2 3 

9. for Loop with Conditional Statements

You can use conditional statements inside a for loop to filter values or perform specific actions.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            printf("%d is even\n", i);
        } else {
            printf("%d is odd\n", i);
        }
    }

    return 0;
}

Explanation:

  • The loop checks if i is even or odd, printing the appropriate message.

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even

10. Calculating Factorial Using for Loop

The for loop can be used to calculate the factorial of a number.

#include <stdio.h>

int main() {
    int num = 5;
    int factorial = 1;

    for (int i = 1; i <= num; i++) {
        factorial *= i;
    }

    printf("Factorial of %d is: %d\n", num, factorial);

    return 0;
}

Explanation:

  • The loop multiplies factorial by each integer up to num.
  • After the loop, factorial contains the result.

Output:

Factorial of 5 is: 120

Summary Table of for Loop Examples

Use Case Description Example Code
Basic counter Print numbers from 1 to 5 for (int i = 1; i <= 5; i++)
Decrement Count down from 5 to 1 for (int i = 5; i >= 1; i–)
Multiple variables Use two variables in the loop for (int i = 1, j = 10; i <= 5; i++, j–)
Infinite loop Loop forever for (;;) { … }
Sum of numbers Calculate total sum of numbers for (int i = 1; i <= 10; i++) sum += i;
Iterating over arrays Access each element of an array for (int i = 0; i < size; i++)
Nested loops Create 2D patterns for (int i = 1; i <= 3; i++) for (int j…)
Conditional statements Filter even/odd numbers if (i % 2 == 0) { … }
Factorial calculation Multiply numbers up to n for (int i = 1; i <= num; i++)

Complete Example: Multiple Uses of for Loop

This example demonstrates using a for loop for summing, finding maximum values, and displaying arrays.

#include <stdio.h>

int main() {
    int arr[] = {3, 7, 1, 9, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int sum = 0;
    int max = arr[0];

    for (int i = 0; i <

 size; i++) {
        sum += arr[i]; // Calculate sum
        if (arr[i] > max) {
            max = arr[i]; // Find maximum
        }
    }

    printf("Sum of array elements: %d\n", sum);
    printf("Maximum value in array: %d\n", max);

    printf("Array elements:\n");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

Explanation:

  • The first for loop calculates the sum and finds the maximum value in arr.
  • The second for loop displays each element of the array.

Output:

Sum of array elements: 25
Maximum value in array: 9
Array elements:
3 7 1 9 5 

The for loop in C provides a powerful way to iterate over values, perform calculations, and work with data structures.

You may also like