C For Loop


In C programming, loops are a fundamental concept for repeating a block of code multiple times. While the while loop is useful when the number of iterations is unknown, the for loop is ideal when the number of repetitions is known beforehand.

The for loop allows a programmer to control initialization, condition checking, and increment/decrement in a single, compact statement. It is widely used in scenarios like iterating over arrays, generating sequences, or performing repeated calculations.

Structure of a For Loop

A for loop consists of three main components:

  1. Initialization: Sets the starting point of the loop.

  2. Condition: Checked before each iteration; the loop runs as long as this condition is true.

  3. Increment/Decrement: Updates the loop variable after each iteration.

Syntax:

for(initialization; condition; increment/decrement) {
    // code to execute repeatedly
}
  • Initialization: Usually sets the loop counter, e.g., int i = 1.

  • Condition: Boolean expression controlling loop execution, e.g., i <= 10.

  • Increment/Decrement: Modifies the loop variable after each iteration, e.g., i++ or i--.

Example: Basic For Loop

#include <stdio.h>

int main() {
    int i;

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

    return 0;
}

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Here, the loop starts with i = 1, checks the condition i <= 5 before each iteration, and increments i by 1 after every iteration. The loop stops once i becomes 6.

Advantages of For Loops

  1. Compact and readable: All loop components are in a single line.

  2. Easy to control loop variable: Initialization, condition, and update are clearly visible.

  3. Ideal for fixed iterations: When you know how many times to repeat the block.

  4. Works well with arrays: For loops are often used to traverse arrays efficiently.

For Loop With Arrays

For loops are commonly used to process arrays:

#include <stdio.h>

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    int i;

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

    return 0;
}

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
  • i starts at 0 (first array index) and goes up to 4.

  • Arrays are zero-indexed in C, making for loops perfect for iteration.

Nested For Loops

You can place a for loop inside another for loop to handle multi-dimensional tasks:

#include <stdio.h>

int main() {
    int i, j;

    for(i = 1; i <= 3; i++) {
        for(j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}

Output:

* 
* * 
* * * 

Nested loops are useful for printing patterns, tables, and grids.

For Loop With Break and Continue

  • Break: Exits the loop immediately.

  • Continue: Skips the rest of the current iteration and moves to the next.

Example:

#include <stdio.h>

int main() {
    int i;

    for(i = 1; i <= 10; i++) {
        if(i == 5) {
            continue; // skip printing 5
        }
        if(i == 8) {
            break; // stop loop at 8
        }
        printf("%d\n", i);
    }

    return 0;
}

Output:

1
2
3
4
6
7
  • continue skips 5, and break stops the loop at 8.

For Loop With Multiple Variables

C allows initialization and update of multiple variables in a for loop:

#include <stdio.h>

int main() {
    int i, j;

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

    return 0;
}

Output:

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

This allows synchronized updates of multiple variables within the same loop.

Common Mistakes

  1. Infinite loop: Forgetting to increment/decrement the loop variable.

  2. Off-by-one errors: Using <= or < incorrectly can cause extra or missing iterations.

  3. Incorrect loop variable type: Always match the type with the expected range.

  4. Improper nesting: Nested loops can lead to high complexity if not managed properly.

Practical Example: Sum of First N Numbers

#include <stdio.h>

int main() {
    int n, sum = 0, i;

    printf("Enter a number: ");
    scanf("%d", &n);

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

    printf("Sum of first %d numbers is %d\n", n, sum);
    return 0;
}
  • The loop adds numbers from 1 to n to the sum variable.

  • This shows the power and simplicity of for loops for iterative calculations.

Summary of the Tutorial

The for loop in C provides a compact and readable way to repeat code a fixed number of times. With its clear structure of initialization, condition, and update, it is ideal for tasks such as array traversal, pattern printing, and arithmetic calculations. Mastering for loops, along with concepts like nested loops, break, and continue, equips you to handle repetitive tasks efficiently and cleanly in your programs.


Practice Questions

  1. Write a program to print numbers from 1 to 50 using a for loop.

  2. Create a program to calculate the sum of the first N natural numbers, where N is input by the user.

  3. Write a program to print all even numbers between 1 and 100 using a for loop.

  4. Develop a program to print a multiplication table of a number entered by the user.

  5. Write a program to print the first N Fibonacci numbers using a for loop.

  6. Create a program to print a right-angled triangle pattern of stars using nested for loops.

  7. Write a program to calculate the factorial of a number using a for loop.

  8. Develop a program to print all prime numbers between 1 and 100 using a for loop.

  9. Write a program that takes two numbers start and end, and prints all numbers between them divisible by 5.

  10. Create a program that prints a diamond or pyramid pattern using nested for loops.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top