C# For Loop - Real-Life Examples
Real-Life Examples
A for loop is a good choice when you know how many times the code should run.
This chapter shows how you can use it in small programs that solve everyday problems.
Count by Tens
This program counts from 0 to 100 in steps of 10:
Example
for (int i = 0; i <= 100; i = i + 10)
{
Console.WriteLine(i);
}
i = i + 10 adds 10 to i after each round, so the loop prints 0, 10, 20 and so on, up to 100.
Even Numbers
This program checks the numbers 1 to 10, and prints only the even ones.
A number is even when you can divide it by 2 with nothing left over. The % (modulus) operator gives the remainder of a division, so i % 2 == 0 is true for even numbers:
Example
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
Console.WriteLine(i + " is even");
}
}
Multiplication Table
This program prints the multiplication table for the number 7:
Example
int number = 7;
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(number + " x " + i + " = " + (number * i));
}
The parentheses around number * i make sure that the multiplication happens first, before the result is added to the text.
Add Up Numbers
This program adds all the numbers from 1 to 100:
Example
int sum = 0;
for (int i = 1; i <= 100; i++)
{
sum = sum + i;
}
Console.WriteLine("The sum of 1 to 100 is " + sum);
sum starts at 0. Each round adds the next number to it, so after the loop, sum is 5050.