Control Flow

Lesson 2.3: Control Flow


Control flow determines the order in which statements are executed in your C# program. Without control flow, your code would run from top to bottom, executing each line only once. This lesson explores two essential control flow concepts:


1. Conditional Statements (Decision Making)


Conditional statements allow your program to choose different paths of execution based on certain conditions. The most common type is the if/else statement.


if Statement: Executes a block of code only if a specified condition is true.

C#

int age = 20;


if (age >= 18) 

{

    Console.WriteLine("You are an adult.");

}


else Statement: Executes a block of code if the if condition is false.

C#

int score = 75;


if (score >= 60) 

{

    Console.WriteLine("You passed!");

}

else

{

    Console.WriteLine("You need to study more.");

}


else if Statement: Allows you to check multiple conditions in sequence.

C#

int grade = 85;


if (grade >= 90) 

{

    Console.WriteLine("Excellent!");

}

else if (grade >= 80) 

{

    Console.WriteLine("Great job!");

}

else

{

    Console.WriteLine("Keep trying!");

}


2. Loops (Repetition)


Loops let you repeat a block of code multiple times. C# offers three main loop types:


for Loop: Repeats a block of code a specific number of times.

C#

for (int i = 0; i < 5; i++) // Start at 0, continue as long as i is less than 5, increment i by 1 each time

{

    Console.WriteLine("Hello!");  // Prints "Hello!" five times

}

Use code with caution.

content_copy

while Loop: Repeats a block of code as long as a condition is true.

C#

int count = 0;

while (count < 10) 

{

    Console.WriteLine(count);

    count++; 

}

do-while Loop: Similar to a while loop, but the block of code is executed at least once before the condition is checked.

C#

int number = 0;

do

{

    Console.WriteLine(number);

    number++;

} while (number < 5);


Choosing the Right Loop


Use a for loop when you know exactly how many times you want the loop to run.

Use a while loop when you want to repeat as long as a condition is true, but you don't know the exact number of repetitions in advance.

Use a do-while loop when you need the code inside the loop to execute at least once, even if the condition is initially false.

Example: Putting It Together


C#

Console.WriteLine("Enter your age:");

int age = int.Parse(Console.ReadLine()); // Read age from the user


if (age < 13)

{

    Console.WriteLine("You are a child.");

}

else if (age < 18)

{

    Console.WriteLine("You are a teenager.");

}

else

{

    Console.WriteLine("You are an adult.");


    // Count down from the current age to 0

    for (int i = age; i >= 0; i--)

    {

        Console.WriteLine(i);

    }

}


Key Takeaways


Control flow makes your programs dynamic and responsive.

Conditional statements allow your code to make decisions.

Loops automate repetitive tasks, making your programs more efficient.

Course Syllabus