Mark As Completed Discussion

Control Flow and Loops

Control flow statements and loops are essential tools in programming to control the flow of execution and perform repetitive tasks.

Control Flow Statements

Control flow statements allow you to execute different code blocks based on specified conditions. One commonly used control flow statement is the if statement.

TEXT/X-CSHARP
1int age = 25;
2
3if (age >= 18)
4{
5    Console.WriteLine("You are an adult.");
6}
7else
8{
9    Console.WriteLine("You are a minor.");
10}

In this example, the if statement checks if the age variable is greater than or equal to 18. If the condition evaluates to true, the program will execute the code block inside the if statement. Otherwise, the program will execute the code block inside the else statement.

Loops

Loops allow you to repeat a set of statements multiple times. One common type of loop is the for loop.

TEXT/X-CSHARP
1for (int i = 1; i <= 5; i++)
2{
3    Console.WriteLine("Count: " + i);
4}

In this example, the for loop is used to print the numbers from 1 to 5. The loop starts with initializing a counter variable i with 1, then it checks the condition i <= 5, and if the condition is true, it executes the code block inside the loop, which in this case prints the value of i. After each iteration, the loop updates the counter variable i by incrementing it by 1.

By using control flow statements and loops, you can create more complex programs that can make decisions based on conditions and perform repetitive tasks.

CSHARP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment