SkillPilotAI

if, switch and loops

Control flow decides which code runs and how many times: if/else and switch choose a path, loops repeat work. Getting condition order, switch rules and the right loop wrong leads to quiet business bugs like a 2500 order getting only 50 off.

7.1 Problem: wrong discount

C#
decimal Discount(decimal total){    if (total >= 500)        return 50;    else if (total >= 2000)        return 300;    else        return 0;} Console.WriteLine(Discount(800));Console.WriteLine(Discount(2500));
Output
$ dotnet run Discount.cs5050
How the if-else chain decided
  1. 1.Discount(2500) enters the chain

  2. 2.Check 1: total >= 500 -> true (2500 passes too)

  3. 3.return 50: the rest of the chain is skipped

  4. 4.Check 2: total >= 2000 never runs

  5. 5.Fix: put the biggest / most specific condition first

First true condition wins

7.2 Fix: biggest condition first

C#
decimal Discount(decimal total){    if (total >= 2000)        return 300;    else if (total >= 500)        return 50;    else        return 0;} Console.WriteLine(Discount(800));Console.WriteLine(Discount(2500));Console.WriteLine(Discount(300));
Output
$ dotnet run Discount.cs503000

7.3 switch statement

  • Cleaner than if/else when one value is compared with many fixed options.
  • Stacked empty case labels (upi + wallet) share one body.
  • Every case ends with break (or return/throw); default runs when nothing matches.
C#
string mode = "card";switch (mode){    case "upi":    case "wallet":        Console.WriteLine("Fee: 0");        break;    case "card":        Console.WriteLine("Fee: 15");        break;    default:        Console.WriteLine("Fee: 25");        break;}
Output
$ dotnet run Payment.csFee: 15

7.4 switch expression

  • Modern style: it returns a value instead of running statements.
  • Each arm: pattern => result; or combines patterns; _ works like default.
  • Relational patterns (>= 2000) fit the discount logic in three arms, checked top to bottom.
C#
int Fee(string mode) => mode switch{    "upi" or "wallet" => 0,    "card" => 15,    _ => 25}; decimal Discount(decimal sum) => sum switch{    >= 2000 => 300,    >= 500 => 50,    _ => 0};Console.WriteLine(Fee("card"));Console.WriteLine(Discount(2500));
Output
$ dotnet run Fees.cs15300
Pointswitch statementswitch expression
PurposeRuns an action per caseReturns a value
Ending a casebreak / return / throw requiredNo break; each arm is pattern => value
Defaultdefault:_ =>
Missing casesNothing happensCompiler warning; unmatched value throws at runtime

7.5 for loop

  • Use when the count is known: a 3-month EMI on a 12000 phone.
  • Three parts: start (m = 1), condition checked before every round (m <= months), step after every round (m++).
C#
decimal price = 12000;int months = 3;decimal emi = price / months; for (int m = 1; m <= months; m++){    Console.WriteLine($"Month {m}: {emi}");}
Output
$ dotnet run Emi.csMonth 1: 4000Month 2: 4000Month 3: 4000

7.6 foreach, break, continue

  • foreach: every item, no index needed; the most readable loop.
  • continue skips only the current item (price 0 = out of stock).
  • break stops the whole loop (budget crossed at 3500, so 250 is never checked).
C#
int[] prices = [499, 0, 1299, 3500, 250];int budget = 2000;int total = 0; foreach (int price in prices){    if (price == 0)        continue;   // out of stock    if (total + price > budget)        break;    total += price;    Console.WriteLine($"Added {price}");}Console.WriteLine($"Final total: {total}");
Output
$ dotnet run Cart.csAdded 499Added 1299Final total: 1798

7.7 while and do while

  • while: count unknown, run while the condition is true (savings goal reached in 4 months).
  • do while: condition checked at the end, so the body runs at least once (Tries: 1 even though tries < 0 is false).
C#
decimal savings = 0;int month = 0;while (savings < 10000){    month++;    savings += 3000;}Console.WriteLine($"Goal in {month} months"); int tries = 0;do{    tries++;} while (tries < 0);Console.WriteLine($"Tries: {tries}");
Output
$ dotnet run Savings.csGoal in 4 monthsTries: 1
Which loop when?
  1. 1.Know the count? -> for

  2. 2.Need every item but not the index? -> foreach

  3. 3.Only know a condition? -> while

  4. 4.Body must run at least once? -> do while

  5. 5.Inside any loop: continue skips one round, break stops the loop

Pick the loop that fits the job

7.8 Checkpoint: continue vs break

C#
for (int i = 1; i <= 5; i++){    if (i == 2) continue;    if (i == 4) break;    Console.Write(i);}
Output
$ dotnet run Quiz.cs13
  • 1 printed, 2 skipped, 3 printed, loop ends at 4, so 5 never runs.

7.9 Common mistakes

  • Forgetting break at the end of a case: C# does not fall through, it gives error CS0163 (Control cannot fall through).
  • Putting a smaller condition before a bigger one in an if/else chain.
  • A switch expression without _: an unmatched value throws at runtime.
  • Myth: foreach is always slower than for. On arrays the compiler turns foreach into an indexed for loop; speed is practically the same.
C#
string mode = "upi";int fee = 25;switch (mode){    case "upi":        fee = 0;        break;    case "card":        fee = 15;        break;}Console.WriteLine(fee);

7.10 Interview tips

  • switch statement runs actions and every case ends with break/return; switch expression returns a value and supports patterns.
  • The compiler warns when a switch expression does not cover all cases.
  • C# has no implicit fall-through: only empty case labels can be stacked.
  • if/else: first true condition wins, so order conditions from most specific to least.
  • continue skips one iteration; break exits the loop.