Welcome to The Coding College! In this tutorial, we’ll explore the while
loop in C#. The while
loop is one of the fundamental control structures in programming that allows you to execute a block of code repeatedly based on a condition.
By the end of this guide, you will:
- Understand the concept of a
while
loop. - Learn the syntax and structure of a
while
loop. - Practice with examples to see how the loop works.
Let’s get started! 🚀
What is a While Loop?
A while
loop in C# allows you to repeatedly execute a block of code as long as the specified condition is true. It checks the condition before each iteration, and if the condition becomes false, the loop stops executing.
Syntax of While Loop
Here’s the basic syntax of a while
loop in C#:
while (condition)
{
// Code to be executed repeatedly
}
How It Works:
- The
condition
is evaluated. - If the
condition
is true, the code block inside thewhile
loop executes. - After the block executes, the
condition
is checked again. - This process continues until the
condition
becomes false.
Example 1: Basic While Loop
Let’s see a simple example of a while
loop that prints numbers from 1 to 5.
using System;
class Program
{
static void Main()
{
int i = 1;
while (i <= 5)
{
Console.WriteLine("Number: " + i);
i++;
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
- We initialize
i
with1
. - The
while
loop checks ifi <= 5
. - If true, it executes the code inside and increments
i
usingi++
. - This continues until
i
becomes6
, at which point the condition becomes false, and the loop stops.
Example 2: Infinite While Loop
If you forget to update the condition or use a stopping condition, the loop can run infinitely.
using System;
class Program
{
static void Main()
{
int i = 1;
while (true) // Infinite loop
{
Console.WriteLine("This is an infinite loop. Count: " + i);
i++;
// Stop the loop after 5 iterations
if (i > 5)
{
break;
}
}
}
}
Output:
This is an infinite loop. Count: 1
This is an infinite loop. Count: 2
This is an infinite loop. Count: 3
This is an infinite loop. Count: 4
This is an infinite loop. Count: 5
Explanation:
while (true)
creates an infinite loop.- The
break
statement is used to exit the loop wheni > 5
.
Example 3: While Loop with User Input
Let’s use a while
loop to repeatedly ask for a number until the user enters 0
.
using System;
class Program
{
static void Main()
{
int number;
Console.WriteLine("Enter numbers (0 to exit):");
number = Convert.ToInt32(Console.ReadLine());
while (number != 0)
{
Console.WriteLine("You entered: " + number);
number = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Program exited.");
}
}
Output:
Enter numbers (0 to exit):
5
You entered: 5
3
You entered: 3
0
Program exited.
Explanation:
- The loop runs until the user enters
0
. - It continuously takes input and prints it back to the user.
Example 4: Sum of Natural Numbers Using While Loop
Here’s an example to calculate the sum of the first n
natural numbers.
using System;
class Program
{
static void Main()
{
int n = 5; // Sum up to 5
int i = 1;
int sum = 0;
while (i <= n)
{
sum += i;
i++;
}
Console.WriteLine("Sum of first " + n + " natural numbers is: " + sum);
}
}
Output:
Sum of first 5 natural numbers is: 15
Explanation:
- The
while
loop adds each value ofi
(from1
to5
) to thesum
. - The loop stops when
i
becomes greater than5
.
Difference Between While Loop and For Loop
Feature | While Loop | For Loop |
---|---|---|
Initialization | Outside the loop | Inside the loop header |
Condition Check | At the start of each iteration | At the start of each iteration |
Use Case | When the number of iterations is unknown | When the number of iterations is known |
Best Practices for Using While Loops
- Avoid Infinite Loops: Always ensure the condition eventually becomes
false
to avoid infinite loops. - Update Condition Variables: Update the loop control variable inside the loop to make progress.
- Use Break Statements: Use
break
to exit a loop if a certain condition is met. - Clear Logic: Use
while
loops when the number of iterations isn’t known in advance.
Conclusion
The while
loop in C# is a powerful control structure for situations where you need to repeat code based on a condition. Whether it’s taking user input, processing data, or handling unknown iterations, the while
loop helps you write efficient and clean code.
For more tutorials, examples, and tips on C# programming, visit The Coding College—your ultimate destination for coding knowledge.