Menu
CoddyTech

For Loop

Part of the Fundamentals section of Coddy's C# journey. Lesson 41 of 69.

Sometimes when programming, it's necessary to perform the same or almost the same operation a couple of times.

To prevent writing the same thing over and over again, we can use Loops.

The for loop has the following syntax:

for (initialization; condition; update) {
	code
}

The initialization, condition and update determine what is the start value and what is the end value.

For example, loop from 0 to 5 (not including):

for (int i = 0; i < 5; i++) {
	Console.WriteLine(i);
}

Breaking down the for loop:

  1. Initialization: int i = 0
    • This runs once at the very beginning
    • Creates a variable i and sets its starting value to 0
  2. Condition: i < 5
    • This is checked before each iteration
    • The loop continues as long as this condition is true
    • When i becomes 5, the condition becomes false and the loop stops
  3. Update: i++
    • This runs after each iteration
    • Increases the value of i by 1 each time
    • i++ is shorthand for i = i + 1
for (int i = 0;  i < 5;  i++) {
     │           │        │
     │           │        └── Update
     │           └─────────── Condition
     └─────────────────────── Initialization

It will execute the print statement 5 times:

0
1
2
3
4

Loops have many use cases. For example, let's sum all the numbers from 1 to 100:

int sumNumbers = 0;
for (int i = 1; i <= 100; i++) {
	sumNumbers += i;
}
Console.WriteLine(sumNumbers);

This will first loop through all numbers between 1 and 100 (including 100 because of <= sign) and sum all of them, then it will print the sumNumbers variable

challenge icon

Challenge

Beginner

Read an integer n (the starter code already does this). Use a for loop to print "Hello Coddy: " and the i value for every number from 3 to n, both included.

For example, if n is 6, the output is:

Hello Coddy: 3
Hello Coddy: 4
Hello Coddy: 5
Hello Coddy: 6

If n is 27, the loop prints 25 lines, from Hello Coddy: 3 to Hello Coddy: 27.

Try it yourself

using System;

class Program {
    public static void Main(string[] args) {
        int n = int.Parse(Console.ReadLine());
        // Write code here
    }
}
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online C# compiler