For Loop

C Programming Tutorial: for Loop

Welcome to the Codes With Pankaj "for Loop in C Programming" tutorial! This tutorial will guide you through the usage of the for loop in C for iterative tasks.

Table of Contents


1. Introduction to for Loop

The for loop in C is used to execute a block of code repeatedly for a fixed number of iterations. It is commonly used when the number of iterations is known in advance.

2. Syntax of for Loop

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

3. Example: Simple for Loop

#include <stdio.h>

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

4. Loop Control Variables

  • Initialization: Executes once before the loop starts and initializes the loop control variable.

  • Condition: Checked before each iteration. If true, the loop continues; if false, the loop terminates.

  • Update: Executed after each iteration and updates the loop control variable.

5. Infinite for Loop

An infinite loop occurs when the loop condition always evaluates to true, causing the loop to execute indefinitely.

for (;;) {
    // Code to execute indefinitely
}

6. Nested for Loops

for loops can be nested inside other for loops to perform multi-dimensional iteration.

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

7. Skipping Loop Iterations with continue

The continue statement is used to skip the remaining code in the current iteration and proceed to the next iteration of the loop.

for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // Skip iteration when i equals 2
    }
    printf("Iteration %d\n", i);
}

8. Terminating a Loop with break

The break statement is used to exit the loop prematurely based on a certain condition.

for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // Exit loop when i equals 3
    }
    printf("Iteration %d\n", i);
}

9. Best Practices

  • Use meaningful loop control variable names to improve code readability.

  • Ensure loop conditions are properly defined to avoid infinite loops.

  • Keep the loop body concise and focused on a single task.

10. Exercises

Try these exercises to practice for loops in C:

  1. Exercise 1: Write a program to display the first 10 natural numbers.

  2. Exercise 2: Implement a program to calculate the sum of the first 100 positive integers.

  3. Exercise 3: Create a program to print the multiplication table of a given number.

  4. Exercise 4: Write a program to find the factorial of a given number.

  5. Exercise 5: Implement a program to generate the Fibonacci series up to the nth term.


We hope this tutorial has helped you understand the for loop in C programming. Practice with the exercises provided to reinforce your understanding. Happy coding!

For more tutorials, visit www.codeswithpankaj.com.

Last updated