C# Loops
Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. In C#, loops are essential for tasks like processing collections of data, implementing repetitive calculations, or executing code until a specific condition is met.
Introduction to Loops
In programming, we often need to perform the same action multiple times. Instead of writing the same code over and over again, we use loops to repeat actions. C# provides several types of loops, each with its own use cases:
for
loops: Used when you know exactly how many times you want to loopforeach
loops: Designed for iterating over collections like arrays and listswhile
loops: Execute as long as a condition remains truedo-while
loops: Similar to while loops but guarantee at least one execution
Let's explore each type of loop in detail.
The for
Loop
The for
loop is one of the most common loops in C#. It's particularly useful when you know the exact number of iterations needed.
Syntax
for (initialization; condition; iteration)
{
// Code to be executed
}
The for
loop consists of three parts:
- Initialization: Executed once at the beginning
- Condition: Checked before each iteration; the loop continues as long as it's true
- Iteration: Executed after each iteration
Example: Counting from 1 to 5
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Count: {i}");
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
In this example:
int i = 1
initializes the counter variablei <= 5
sets the condition to continue loopingi++
increments the counter after each iteration
Practical Application: Calculating Factorial
using System;
class Program
{
static void Main()
{
int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial *= i;
}
Console.WriteLine($"The factorial of {number} is: {factorial}");
}
}
Output:
The factorial of 5 is: 120
The foreach
Loop
The foreach
loop is designed specifically for iterating through collections like arrays, lists, and other enumerable objects.
Syntax
foreach (type item in collection)
{
// Code to be executed for each item
}
Example: Iterating Through an Array
using System;
class Program
{
static void Main()
{
string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
foreach (string fruit in fruits)
{
Console.WriteLine($"Current fruit: {fruit}");
}
}
}
Output:
Current fruit: Apple
Current fruit: Banana
Current fruit: Cherry
Current fruit: Date
Current fruit: Elderberry
Unlike the for
loop, foreach
doesn't require you to manage indexes or check boundaries, making your code cleaner and less prone to errors when working with collections.
Practical Application: Calculating Average of Scores
using System;
class Program
{
static void Main()
{
int[] scores = { 85, 92, 78, 95, 88 };
int sum = 0;
foreach (int score in scores)
{
sum += score;
}
double average = (double)sum / scores.Length;
Console.WriteLine($"The average score is: {average}");
}
}
Output:
The average score is: 87.6
The while
Loop
The while
loop executes a block of code as long as a specified condition is true. It checks the condition before each iteration.
Syntax
while (condition)
{
// Code to be executed
}
Example: Counting Down from 5
using System;
class Program
{
static void Main()
{
int countdown = 5;
while (countdown > 0)
{
Console.WriteLine($"Countdown: {countdown}");
countdown--;
}
Console.WriteLine("Blast off!");
}
}
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Blast off!
The while
loop is particularly useful when you don't know in advance how many iterations you'll need.
Practical Application: Reading User Input Until a Condition
using System;
class Program
{
static void Main()
{
string input = "";
while (input != "exit")
{
Console.Write("Enter a command (type 'exit' to quit): ");
input = Console.ReadLine();
Console.WriteLine($"You entered: {input}");
}
Console.WriteLine("Program terminated.");
}
}
Output (example interaction):
Enter a command (type 'exit' to quit): hello
You entered: hello
Enter a command (type 'exit' to quit): C#
You entered: C#
Enter a command (type 'exit' to quit): exit
You entered: exit
Program terminated.
The do-while
Loop
The do-while
loop is similar to the while
loop, with one key difference: it checks the condition after the code block executes, guaranteeing at least one execution of the code.
Syntax
do
{
// Code to be executed
} while (condition);
Example: Basic do-while
Loop
using System;
class Program
{
static void Main()
{
int i = 1;
do
{
Console.WriteLine($"Iteration: {i}");
i++;
} while (i <= 5);
}
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Practical Application: Input Validation
using System;
class Program
{
static void Main()
{
int number;
do
{
Console.Write("Enter a positive number: ");
number = Convert.ToInt32(Console.ReadLine());
if (number <= 0)
{
Console.WriteLine("That's not a positive number. Please try again.");
}
} while (number <= 0);
Console.WriteLine($"You entered the positive number: {number}");
}
}
Output (example interaction):
Enter a positive number: -5
That's not a positive number. Please try again.
Enter a positive number: 0
That's not a positive number. Please try again.
Enter a positive number: 10
You entered the positive number: 10
Control Statements in Loops
C# provides special statements to alter the normal flow of loops:
break
Statement
The break
statement immediately exits the loop, regardless of the condition.
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 6)
{
Console.WriteLine("Breaking the loop at i = 6");
break;
}
Console.WriteLine($"Current value: {i}");
}
Console.WriteLine("Loop finished");
}
}
Output:
Current value: 1
Current value: 2
Current value: 3
Current value: 4
Current value: 5
Breaking the loop at i = 6
Loop finished
continue
Statement
The continue
statement skips the current iteration and moves to the next one.
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
Console.WriteLine("Skipping iteration for i = 3");
continue;
}
Console.WriteLine($"Current value: {i}");
}
}
}
Output:
Current value: 1
Current value: 2
Skipping iteration for i = 3
Current value: 4
Current value: 5
Nested Loops
You can place loops inside other loops, creating nested loops. This is useful for working with multi-dimensional data structures.
using System;
class Program
{
static void Main()
{
int rows = 3;
int columns = 4;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write($"({i},{j}) ");
}
Console.WriteLine(); // Move to the next line after each row
}
}
}
Output:
(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3)
Practical Application: Printing a Pattern
using System;
class Program
{
static void Main()
{
int rows = 5;
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Infinite Loops
Sometimes we need a loop to run indefinitely until an explicit break condition. This is called an infinite loop.
using System;
class Program
{
static void Main()
{
int count = 0;
while (true)
{
Console.WriteLine($"Iteration: {count}");
count++;
if (count >= 5)
{
Console.WriteLine("Breaking out of the infinite loop");
break;
}
}
}
}
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Breaking out of the infinite loop
Be careful with infinite loops! Always ensure there's a way to exit the loop.
Summary
Loops are powerful constructs in C# that allow you to execute code repeatedly based on specific conditions:
for
loops: Best when you know the exact number of iterations neededforeach
loops: Ideal for iterating through collections like arrays and listswhile
loops: Perfect when you need to continue execution until a condition becomes falsedo-while
loops: Similar to while loops but guarantees at least one execution
Choosing the right loop depends on your specific requirements:
- Use
for
when you need precise control over the iteration process - Use
foreach
for clean and safe iteration through collections - Use
while
when the number of iterations is indeterminate - Use
do-while
when you need to guarantee at least one execution
Understanding loops and how to control them with break
and continue
statements is essential for writing efficient C# programs.
Exercises
- Write a program that uses a
for
loop to print all even numbers between 1 and 20. - Create an array of your favorite movies and use a
foreach
loop to display them. - Write a program using a
while
loop that asks the user to guess a number between 1 and 10. - Use a
do-while
loop to create a simple calculator that continues to run until the user chooses to exit. - Create a nested loop to print a multiplication table for numbers 1 through 5.
Additional Resources
- Microsoft's Official C# Documentation on Loops
- W3Schools C# Loops
- C# Corner: Understanding Loops in C#
- Tutorialspoint: C# Loops
Happy coding!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)