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:
- Initialization:
int i = 0- This runs once at the very beginning
- Creates a variable
iand sets its starting value to 0
- Condition:
i < 5- This is checked before each iteration
- The loop continues as long as this condition is true
- When
ibecomes 5, the condition becomes false and the loop stops
- Update:
i++- This runs after each iteration
- Increases the value of
iby 1 each time i++is shorthand fori = i + 1
for (int i = 0; i < 5; i++) {
│ │ │
│ │ └── Update
│ └─────────── Condition
└─────────────────────── InitializationIt will execute the print statement 5 times:
0
1
2
3
4Loops 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
BeginnerWrite a program that prints "Hello Coddy: " and the i value from 3 to 27 (including, which means printing the numbers 3, 4, 5, ..., 26, 27, making it 27 - 3 + 1 = 25 times in total), do it using a for loop.
It will look like this:
Hello Coddy: 3
Hello Coddy: 4
...
Hello Coddy: 27Cheat sheet
The for loop allows you to repeat code multiple times with the following syntax:
for (initialization; condition; update) {
code
}Example - loop from 0 to 5 (not including):
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}This outputs:
0
1
2
3
4Example - sum numbers from 1 to 100:
int sumNumbers = 0;
for (int i = 1; i <= 100; i++) {
sumNumbers += i;
}
Console.WriteLine(sumNumbers);Try it yourself
using System;
class Program {
public static void Main(string[] args) {
// Write code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3