What is a For Loop?
A for loop is used when you know exactly how many times you want to repeat code. It's more compact than a while loop for counting scenarios.
Basic Syntax
for (initialization; condition; increment/decrement)
{
// Code to execute
}
Three Parts:
- Initialization: Sets starting value (runs once)
- Condition: Checked before each iteration
- Increment/Decrement: Updates counter after each iteration
Simple Examples
Example 1: Count from 1 to 5
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5
Example 2: Count from 0 to 4
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// Output:
// 0
// 1
// 2
// 3
// 4
Example 3: Count Down
for (int i = 5; i >= 1; i--)
{
Console.WriteLine(i);
}
Console.WriteLine("Blast off!");
// Output:
// 5
// 4
// 3
// 2
// 1
// Blast off!
Example 4: Count by 2s
for (int i = 0; i <= 10; i += 2)
{
Console.WriteLine(i);
}
// Output: 0, 2, 4, 6, 8, 10
How For Loops Work
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("Iteration " + i);
}
Step by step:
1. int i = 1
→ Initialize i to 1
2. i <= 3?
→ Check condition (true)
3. Execute code block → Print "Iteration 1"
4. i++
→ Increment i to 2
5. i <= 3?
→ Check condition (true)
6. Execute code block → Print "Iteration 2"
7. i++
→ Increment i to 3
8. i <= 3?
→ Check condition (true)
9. Execute code block → Print "Iteration 3"
10. i++
→ Increment i to 4
11. i <= 3?
→ Check condition (false)
12. Exit loop
Practical Examples from Course
Example 1: Temperature Conversion Table (From Practical Test 1)
using System;
namespace TemperatureTable
{
class Program
{
static void Main(string[] args)
{
string sMsg = "Celsius\tFahrenheit\t|\tFahrenheit\tCelsius\n";
sMsg += "========================================================\n";
for (double dCelsius = 40.0, dFahrenheit = 120.0;
dFahrenheit >= 30.0;
dCelsius--, dFahrenheit -= 10)
{
sMsg += dCelsius.ToString("0.0") + "\t" +
CelsiusToFahrenheit(dCelsius).ToString("0.0") + "\t\t|\t" +
dFahrenheit.ToString("0.0") + "\t\t" +
FahrenheitToCelsius(dFahrenheit).ToString("0.0") + "\n";
}
Console.WriteLine(sMsg);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static double CelsiusToFahrenheit(double dCelsius)
{
return (9.0 / 5) * dCelsius + 32;
}
static double FahrenheitToCelsius(double dFahrenheit)
{
return (5.0 / 9) * (dFahrenheit - 32);
}
}
}
Example 2: Random Number Statistics (From Worksheet 1)
using System;
namespace RandomStats
{
class Program
{
static void Main(string[] args)
{
Console.Write("How many random numbers: ");
int iN = int.Parse(Console.ReadLine());
Random rnd = new Random();
int iCountEven = 0, iCountOdd = 0;
int iSumEven = 0, iSumOdd = 0;
Console.WriteLine();
for (int i = 1; i <= iN; i++)
{
int iR = rnd.Next(0, 31); // Random 0-30
Console.Write(iR + " ");
if (iR % 2 == 0)
{
iCountEven++;
iSumEven += iR;
}
else
{
iCountOdd++;
iSumOdd += iR;
}
}
double dEvenPercentage = iCountEven * 100.0 / iN;
double dOddPercentage = iCountOdd * 100.0 / iN;
double dAvgEven = (iCountEven > 0) ? iSumEven * 1.0 / iCountEven : 0;
double dAvgOdd = (iCountOdd > 0) ? iSumOdd * 1.0 / iCountOdd : 0;
Console.WriteLine("\n\nStatistics:");
Console.WriteLine("Percentage of Even numbers: " + dEvenPercentage.ToString("0.00") + "%");
Console.WriteLine("Percentage of Odd numbers: " + dOddPercentage.ToString("0.00") + "%");
Console.WriteLine("Sum of even numbers: " + iSumEven);
Console.WriteLine("Sum of odd numbers: " + iSumOdd);
Console.WriteLine("Average of even numbers: " + dAvgEven.ToString("0.00"));
Console.WriteLine("Average of odd numbers: " + dAvgOdd.ToString("0.00"));
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 3: Multiplication Table
using System;
namespace MultiplicationTable
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int iNumber = int.Parse(Console.ReadLine());
Console.WriteLine($"\nMultiplication Table for {iNumber}:");
Console.WriteLine("============================");
for (int i = 1; i <= 10; i++)
{
int iResult = iNumber * i;
Console.WriteLine($"{iNumber} x {i} = {iResult}");
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 4: Sum and Average Calculator
using System;
namespace SumAverage
{
class Program
{
static void Main(string[] args)
{
int iSum = 0;
int iCount = 5;
Console.WriteLine("Enter 5 numbers:");
for (int i = 1; i <= iCount; i++)
{
Console.Write($"Number {i}: ");
int iNumber = int.Parse(Console.ReadLine());
iSum += iNumber;
}
double dAverage = (double)iSum / iCount;
Console.WriteLine($"\nSum: {iSum}");
Console.WriteLine($"Average: {dAverage:0.00}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Multiple Variables in For Loop
You can declare multiple variables:
// Two variables: one increases, one decreases
for (int i = 0, j = 10; i < 5; i++, j--)
{
Console.WriteLine($"i = {i}, j = {j}");
}
// Output:
// i = 0, j = 10
// i = 1, j = 9
// i = 2, j = 8
// i = 3, j = 7
// i = 4, j = 6
Break and Continue in For Loops
Break: Exit Loop Early
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break; // Exit loop when i is 5
}
Console.WriteLine(i);
}
// Output: 1, 2, 3, 4
Continue: Skip Current Iteration
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip even numbers
}
Console.WriteLine(i);
}
// Output: 1, 3, 5, 7, 9
Common For Loop Patterns
Pattern 1: Sum of Numbers
int iSum = 0;
for (int i = 1; i <= 10; i++)
{
iSum += i;
}
Console.WriteLine("Sum: " + iSum); // Sum: 55
Pattern 2: Factorial
int iNumber = 5;
int iFactorial = 1;
for (int i = 1; i <= iNumber; i++)
{
iFactorial *= i;
}
Console.WriteLine($"Factorial of {iNumber} is {iFactorial}"); // 120
Pattern 3: Print Pattern
// Print stars
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("*****");
}
// Output:
// *****
// *****
// *****
// *****
// *****
Pattern 4: Build String
string sResult = "";
for (int i = 1; i <= 5; i++)
{
sResult += i + " ";
}
Console.WriteLine(sResult); // Output: 1 2 3 4 5
For Loop vs While Loop
Same Result, Different Syntax
Using For Loop:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
Using While Loop:
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
When to Use Which?
Use For Loop When: ✅ You know the number of iterations ✅ You have a counter variable ✅ Simple incrementing/decrementing
Use While Loop When: ✅ Number of iterations is unknown ✅ Condition-based looping ✅ Input validation
Infinite For Loop
// Missing increment - infinite loop!
for (int i = 1; i <= 5; ) // No i++
{
Console.WriteLine(i); // Prints 1 forever
}
// Intentional infinite loop
for (;;)
{
Console.WriteLine("This runs forever");
// Need break statement to exit
}
Practice Exercises
Exercise 1: Even Numbers
Print all even numbers from 1 to 20.
Exercise 2: Countdown Timer
Create a countdown from 10 to 1, printing "GO!" at the end.
Exercise 3: Power Calculator
Calculate 2^10 (2 to the power of 10) using a loop.
Exercise 4: Grade Statistics
Ask user for 10 grades, calculate and display: - Total sum - Average - Number of grades above 70
Exercise 5: Fibonacci Sequence
Print first 10 numbers of Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
Common Mistakes to Avoid
❌ Off-by-one errors:
// Prints 0-4 (5 numbers)
for (int i = 0; i < 5; i++)
// Prints 0-5 (6 numbers)
for (int i = 0; i <= 5; i++)
❌ Wrong increment:
for (int i = 1; i <= 10; i--) // Infinite loop! i never reaches 10
✅ Correct:
for (int i = 1; i <= 10; i++) // Correct increment
❌ Modifying loop variable inside:
for (int i = 0; i < 10; i++)
{
i = i + 2; // Confusing! Avoid this
}
✅ Better:
for (int i = 0; i < 10; i += 3) // Clear increment
{
Console.WriteLine(i);
}
❌ Semicolon after for:
for (int i = 0; i < 5; i++); // WRONG! Empty loop
{
Console.WriteLine(i); // This runs once after loop
}
✅ Correct:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Key Takeaways
✅ For loops are best when you know iteration count ✅ Three parts: initialization, condition, increment ✅ Counter variable is only accessible inside loop ✅ Can declare multiple variables ✅ Use break to exit early ✅ Use continue to skip iteration ✅ Watch for off-by-one errors ✅ Perfect for counting and iteration tasks
Next Topic: C# Nested Loops