the World of Control Structures! ๐ข
the World of Control Structures! ๐ข
"Life is all about the choices we make and path we follow." Same goes for the code as well. Control Structures Let's explore how code can make decisions.
Control structures are the building blocks that dictate the flow of execution in your programs. They allow you to make decisions, repeat actions, and create dynamic and interactive applications.
Decision-Making Structures
if Statement:
If you're feeling hungry ๐, let's order some pizza ๐!
C#
if (hungry) // Check if the 'hungry' condition is true { OrderPizza(); // If hungry, place a pizza order }
int number = 10; if (number % 2 == 0) { Console.WriteLine("The number is even."); } else { Console.WriteLine("The number is odd."); }
if-else Statement:
If it's sunny โ๏ธ, let's go to the beach ๐๏ธ. Otherwise, let's stay home and watch a movie ๐ฅ.
C#
if (isSunny) // Check if it's sunny { GoToBeach(); // If sunny, go to the beach } else // If not sunny { WatchMovie(); // Stay home and watch a movie }
int marks = 85; if (marks >= 90) { Console.WriteLine("Grade: A"); } else if (marks >= 80) { Console.WriteLine("Grade: B"); } else if (marks >= 70) { Console.WriteLine("Grade: C"); } else { Console.WriteLine("Grade: F"); }
switch Statement:
Imagine you're a traffic light controller. ๐ฆ You need to change the lights at specific intervals: red ๐ด, yellow ๐ก, and green ๐ข
C#
string currentLight = "red"; // Initial state switch (currentLight) { case "red": Console.WriteLine("๐ Stop! Red light is on."); // Code to turn on the red light and turn off others break; case "yellow": Console.WriteLine("๐ก Slow down! Yellow light is on."); // Code to turn on the yellow light and turn off others break; case "green": Console.WriteLine("๐ข Go! Green light is on."); // Code to turn on the green light and turn off others break; default: Console.WriteLine("โ ๏ธ Be Alert, Be safe!"); //When there is no Signal at a Juntion }
Looping Structures ๐
for Loop:
Let's count to ten! ๐ข
C#
for (int i = 1; i <= 10; i++) // Initialize i to 1, loop while i is less than or equal to 10, increment i by 1 in each iteration { Console.WriteLine(i); // Print the current value of i }
while Loop:
Keep playing the game ๐ฎ until you win!
C#
while (!hasWon) // Keep looping as long as the 'hasWon' condition is false { PlayGame(); // Play a round of the game }
int secretNumber = 5; int guess; do { Console.Write("Guess the number: "); guess = int.Parse(Console.ReadLine()); if (guess < secretNumber) { Console.WriteLine("Too low. Try again."); } else if (guess > secretNumber) { Console.WriteLine("Too high. Try again."); } } while (guess != secretNumber); Console.WriteLine("You guessed it!");
do-while Loop:
At least one round of the game ๐ฎ, no matter what!
C#
do { PlayRound(); // Play a round of the game } while (wantToContinue); // Keep looping as long as the 'wantToContinue' condition is true
int age; do { Console.Write("Enter your age: "); age = int.Parse(Console.ReadLine()); } while (age < 0); Console.WriteLine("Your age is: " + age);
foreach Loop:
Let's eat all the fruits in the basket ๐๐๐!
C#
foreach (var fruit in fruitBasket) // Iterate over each fruit in the fruitBasket collection { EatFruit(fruit); // Eat the current fruit }
string[] names = { "Alice", "Bob", "Charlie" }; foreach (string name in names) { Console.WriteLine("Hello, " + name + "!"); }
Master Example
using System;
namespace LostTempleAdventure
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Lost Temple!");
Console.WriteLine("Your journey begins...");
int health = 100;
int gold = 0;
bool isAlive = true;
while (isAlive)
{
Console.WriteLine("\nWhat do you do? (1: Explore, 2: Rest, 3: Quit)");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("You venture deeper into the jungle...");
Random random = new Random();
int encounter = random.Next(3);
switch (encounter)
{
case 0:
Console.WriteLine("You found a hidden treasure chest! +20 gold.");
gold += 20;
break;
case 1:
Console.WriteLine("You encountered a venomous snake! -10 health.");
health -= 10;
break;
case 2:
Console.WriteLine("You discovered a mysterious artifact! +5 health.");
health += 5;
break;
}
break;
case 2:
Console.WriteLine("You rest at a nearby oasis. +20 health.");
health += 20;
break;
case 3:
Console.WriteLine("You give up the quest. Game Over.");
isAlive = false;
break;
default:
Console.WriteLine("Invalid choice. Try again.");
break;
}
if (health <= 0)
{
Console.WriteLine("You've succumbed to your wounds. Game Over.");
isAlive = false;
}
}
if (gold >= 100)
{
Console.WriteLine("Congratulations! You've found the Lost Temple and claimed its treasure.");
}
else
{
Console.WriteLine("You may not have found the temple, but your adventure was a journey worth taking.");
}
}
}
}
Comparison :-)
Control Structure | Description | Use Case | Example |
if-else | Executes code based on a condition. | Making decisions. | If it's sunny โ๏ธ, let's go to the beach ๐๏ธ. |
switch | Efficiently handles multiple choices based on a single value. | Menu-driven programs, state machines. | Choose your adventure: โ๏ธ Fight a dragon, ๐งโโ๏ธ Learn a spell, or ๐ก๏ธ Rest at the inn. |
for | Repeats a block of code a specific number of times. | Iterating over a known number of times. | Count the sheep ๐ all over the field |
while | Repeats a block of code as long as a condition is true. | Repeating until a condition is met. | ๐ Keep playing the game ๐ฎ until you win ๐. |
do-while | Executes a block of code at least once, then repeats as long as a condition is true. | Ensuring at least one iteration. | ๐ Dance at least once ๐, then keep dancing while the music plays ๐ถ. |
foreach | Iterates over each element in a collection. | Processing each item in a collection. | ๐ฆ Open the treasure chest ๐ and take one item at a time. |
Jump Statements ๐ฆ
break: Stop the loop or switch statement.
continue: Skip the current iteration of the loop and move to the next one.
goto: Jump to a specific label (use with caution, as it can make code less readable).
for (int i = 1; i <= 10; i++)
{
// If the number is even, skip to the next iteration
if (i % 2 == 0)
{
continue;
}
// If the number is 7, break out of the loop
if (i == 7)
{
break;
}
Console.WriteLine(i);
}
// This part will only execute if the loop is broken before reaching 10
Console.WriteLine("Loop terminated early.");
Output:
1
3
5
Loop terminated early.
int i = 1;
goto MyLabel;
Console.WriteLine("Hello World.");
MyLabel: Console.WriteLine("Good Morning."); //This message will be printed first.
Output:
Good Morning.
Hello World.
Jump Statement | Action | Analogy |
break | Exits a loop or switch statement | Pulling an emergency brake ๐ |
continue | Skips the current iteration | Skipping a boring scene โฉ |
goto | Jumps to a labeled statement | Teleporting โก |