the World of Control Structures! ๐ŸŽข

ยท

6 min read

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 StructureDescriptionUse CaseExample
if-elseExecutes code based on a condition.Making decisions.If it's sunny โ˜€๏ธ, let's go to the beach ๐Ÿ–๏ธ.
switchEfficiently 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.
forRepeats a block of code a specific number of times.Iterating over a known number of times.Count the sheep ๐Ÿ‘ all over the field
whileRepeats 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-whileExecutes 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 ๐ŸŽถ.
foreachIterates 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 StatementActionAnalogy
breakExits a loop or switch statementPulling an emergency brake ๐Ÿ›‘
continueSkips the current iterationSkipping a boring scene โฉ
gotoJumps to a labeled statementTeleporting โšก
ย