Menu
Coddy logo textTech

For Loop

Part of the Fundamentals section of Coddy's C journey — lesson 37 of 63.

The for loop is a control structure that allows you to execute a block of code repeatedly for a specific number of times.

A for loop has three components:

  • Initialization (executed once before the loop starts)
  • Condition (checked before each iteration)
  • Update (executed after each iteration)
for (initialization; condition; update) {
    // code to be executed
}

Let's create a simple for loop that counts from 1 to 5:

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

After executing the above code, the output will be:

1 2 3 4 5

How this works:

  1. First, we initialize i to 1
  2. Then we check if i <= 5 (true, so we execute the loop body)
  1. We print the value of i
  2. We increment i by 1
  3. We repeat steps 2-4 until the condition becomes false
challenge icon

Challenge

Easy

Create a program that takes an integer n from input and uses a for loop to print all numbers from 1 to n, each separated by a space.

Example output for n = 4:

1 2 3 4

Make sure to include a space after each number, including the last one.

Cheat sheet

The for loop executes a block of code repeatedly for a specific number of times.

For loop syntax:

for (initialization; condition; update) {
    // code to be executed
}

Components:

  • Initialization (executed once before the loop starts)
  • Condition (checked before each iteration)
  • Update (executed after each iteration)

Example - counting from 1 to 5:

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

Try it yourself

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    // Write your code here
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals