Lesson 4 — Beginner

If-Else and Loops: Making Decisions in Code

.NETBeginnerC#Tutorial

Your banking app refuses a withdrawal when your balance is too low. Netflix asks "Are you still watching?" only after hours of playback. WhatsApp shows a blue tick only when the message is delivered and read. These are all decisions — and loops repeating checks until something changes.

So far you can store data in variables (Lesson 3). Now we teach your C# program to think: choose different paths with if-else and repeat work with loops.

If-Else: Choosing a Path

An if statement runs code only when a condition is true. A condition is a question with a yes/no answer — like "Is the balance greater than the withdrawal amount?"

double balance = 1200.00;
double withdrawal = 1500.00;

if (balance >= withdrawal)
{
    Console.WriteLine("Withdrawal approved.");
    balance = balance - withdrawal;
}
else
{
    Console.WriteLine("Insufficient funds. Transaction declined.");
}

The else block runs when the condition is false — your backup plan. Without it, the program simply skips the if block and moves on.

Comparison operators build conditions:

  • == equal to (note: double equals, not single)
  • != not equal
  • >, <, >=, <= greater/less comparisons

Else If: Multiple Choices

Food delivery apps charge different fees by city. Use else if to chain conditions:

string city = "Mumbai";
double deliveryFee;

if (city == "Mumbai")
    deliveryFee = 40;
else if (city == "Pune")
    deliveryFee = 30;
else
    deliveryFee = 50;

Console.WriteLine("Delivery fee: Rs " + deliveryFee);

C# checks from top to bottom and stops at the first match — like trying UPI first, then card, then cash on delivery.

Loops: Repeat Without Copy-Paste

A loop repeats a block of code. Imagine printing receipt lines for ten cart items — you would not write ten identical lines by hand.

For Loop — Known Count

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine("Sending reminder " + i + " of 5");
}

i starts at 1, runs while i <= 5, and increases by 1 each time. Perfect when you know how many repetitions you need — like sending five payment reminders.

While Loop — Unknown Count

int unreadCount = 3;

while (unreadCount > 0)
{
    Console.WriteLine("Showing next WhatsApp chat...");
    unreadCount = unreadCount - 1;
}

The while loop keeps going while the condition stays true. Use it when you stop based on a changing situation — processing messages until the inbox is empty.

Decision Flow Diagram

Check balance >= withdrawal?
        ↓ Yes              ↓ No
   Approve debit      Show error message
        ↓
   Update balance
        ↓
   Send SMS receipt

Real apps nest many if statements and loops. The logic stays the same — just more branches.

Real-World Example: Netflix Continue Prompt

int minutesWatching = 0;
bool userActive = true;
bool showContinuePrompt = false;

while (userActive)
{
    minutesWatching++;
    if (minutesWatching >= 180)
    {
        showContinuePrompt = true;
        userActive = false;  // stop the loop
    }
}

if (showContinuePrompt)
    Console.WriteLine("Are you still watching?");

Simplified, but the pattern is real: count time, compare to a threshold, trigger an action. Variables from Lesson 3 plus conditions from this lesson working together.

Common Misconceptions

"= and == mean the same thing." Single = assigns. Double == compares. Mixing them up is a classic beginner bug.

"Loops are always bad for performance." Small loops are fine. Problems come from loops that never end or process millions of rows inefficiently — topics for later.

"I need many nested ifs for everything." Sometimes switch (matching one value against many options) reads cleaner. Start with if-else; refactor later.

"The for loop must start at zero." It can start anywhere. Match the loop to your problem — episode numbers might start at 1.

Quick Recap

  • if / else choose paths based on true/false conditions.
  • else if handles multiple exclusive options.
  • for loops suit a fixed number of repetitions.
  • while loops suit "keep going until…" logic.
  • Use == for comparison, = for assignment.

Summary

Programs that only run straight down are like GPS with no turns — useless for real life. If-else gives your code junctions; loops give it stamina to handle lists, retries, and timers.

Lesson 5 introduces classes and objects — grouping variables and behaviour together, like bundling a customer's name, balance, and transfer method into one neat package.

Frequently Asked Questions

Code that runs only when a condition evaluates to true — like checking whether balance covers a withdrawal before approving it.

Use for when you know how many repetitions you need. Use while when repetition depends on a condition that changes during execution.

Additional conditions checked in order when the first if is false — like trying backup payment methods one after another.

Yes — an infinite loop happens if the exit condition never becomes false. Always ensure something inside the loop moves toward stopping.

break exits a loop early when you find what you need — like stopping a search once the product appears in results.

Symbols like ==, !=, >, and < that compare values and produce true or false for conditions.

Key Takeaways

  • If-else lets programs branch based on conditions.
  • For loops repeat a known number of times; while loops repeat until a condition fails.
  • Use == to compare, not =.
  • Combine conditions and variables from earlier lessons for real logic.
  • Always plan how a loop will end.

Suggested Next Reads

Share: LinkedIn Facebook X

Need help implementing this in your organization?

Contact Emerrank Consultancy