C# if, else, and Loops: A Beginner's Guide
Programs rarely perform the same action from start to finish. They make decisions based on data and often repeat an operation for a collection or range of values. In C#, if, else, and loops provide the basic building blocks for this control flow.
if and else
int age = 20;
if (age >= 18)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Minor");
}
The condition inside the parentheses must evaluate to a Boolean value. When it is true, the first block runs. Otherwise the else block runs.
else if for multiple choices
int score = 72;
if (score >= 90)
{
Console.WriteLine("A");
}
else if (score >= 60)
{
Console.WriteLine("B");
}
else
{
Console.WriteLine("Needs practice");
}
The conditions are checked from top to bottom. Once one condition is true, its block runs and the remaining branches are skipped.
for loop
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
A for loop is useful when you can describe the repetition with an initialization, a condition, and an update. Here the output is the numbers 1 through 5.
foreach
string[] names = { "Asha", "Ravi", "Meena" };
foreach (var name in names)
{
Console.WriteLine(name);
}
foreach is convenient when the goal is to process every item in a collection without managing an index yourself.
while loop
int count = 3;
while (count > 0)
{
Console.WriteLine(count);
count--;
}
A while loop repeats as long as its condition is true. Make sure something inside the loop changes the state when necessary; otherwise the loop may never end.
Common beginner mistakes
- Using
=when a comparison such as==is required. - Creating an infinite
whileloop by never updating its condition. - Using an off-by-one loop boundary when choosing
<versus<=.
When to use each construct
Use conditional statements when the next action depends on a condition. Use for for counted repetition, foreach for processing each item in a collection, and while when the number of repetitions depends on a condition that changes during execution.
Next step
Move reusable logic into C# Methods.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.