Control Flow Concepts
Understanding how your program executes instructions sequentially is fundamental. Control flow statements allow you to alter this default sequence, enabling your applications to make decisions, repeat actions, and manage the execution path dynamically.
Sequential Execution
By default, code is executed line by line, from top to bottom. This is the most basic form of control flow. Each statement is processed in order unless a control flow statement directs otherwise.
Consider this simple sequence:
int a = 10;
int b = 20;
int sum = a + b;
Console.WriteLine("The sum is: " + sum);
Here, each line is executed exactly once in the order it appears.
Conditional Statements
Conditional statements allow your program to execute different blocks of code based on whether a certain condition is true or false. The most common are if
, else if
, and else
.
The if
Statement
The if
statement executes a block of code only if a specified condition evaluates to true.
int age = 18;
if (age >= 18) {
Console.WriteLine("You are an adult.");
}
The if-else
Statement
The if-else
statement provides an alternative block of code to execute if the if
condition is false.
int temperature = 15;
if (temperature > 25) {
Console.WriteLine("It's hot!");
} else {
Console.WriteLine("It's not too hot.");
}
The if-else if-else
Chain
This structure allows you to test multiple conditions in sequence. The first condition that evaluates to true will have its corresponding block of code executed.
int score = 85;
if (score >= 90) {
Console.WriteLine("Grade: A");
} else if (score >= 80) {
Console.WriteLine("Grade: B");
} else if (score >= 70) {
Console.WriteLine("Grade: C");
} else {
Console.WriteLine("Grade: D or F");
}
The switch
Statement
The switch
statement provides an alternative way to select one of many code blocks to be executed. It is often used when you have a single variable that you want to compare against multiple constant values.
char grade = 'B';
switch (grade) {
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Good job!");
break;
case 'C':
Console.WriteLine("Fair.");
break;
default:
Console.WriteLine("Needs improvement.");
break;
}
The break
statement is crucial to exit the switch block after a match is found.
Looping Statements (Iteration)
Loops are used to execute a block of code repeatedly. This is essential for processing collections of data or performing tasks multiple times.
The for
Loop
The for
loop is typically used when you know in advance how many times you want to execute the loop. It consists of an initializer, a condition, and an iterator.
for (int i = 0; i < 5; i++) {
Console.WriteLine("Iteration number: " + i);
}
The while
Loop
The while
loop executes a block of code as long as a specified condition is true. The condition is checked before each iteration.
int count = 0;
while (count < 3) {
Console.WriteLine("Count is: " + count);
count++;
}
The do-while
Loop
Similar to the while
loop, but the condition is checked *after* the loop body is executed. This guarantees that the loop body will execute at least once.
int number = 5;
do {
Console.WriteLine("Processing number: " + number);
number--;
} while (number > 0);
The foreach
Loop
The foreach
loop is used to iterate over elements in a collection (like arrays or lists) without needing to manage an index.
string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (string fruit in fruits) {
Console.WriteLine("I like " + fruit);
}
Jump Statements
Jump statements alter the flow of control by transferring execution to another part of the program.
break
Used to exit a loop or a switch
statement immediately.
Example shown in the switch
statement above.
continue
Skips the rest of the current iteration of a loop and proceeds to the next iteration.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
Console.WriteLine("Odd number: " + i);
}
return
Exits the current method and optionally returns a value. If the method has a void
return type, it simply exits.
public int Add(int x, int y) {
return x + y; // Returns the sum and exits the method
}
goto
Transfers control directly to a labeled statement within the same function. While powerful, its use is generally discouraged as it can make code harder to read and debug.
goto MyLabel;
// ... some code ...
MyLabel:
Console.WriteLine("Jumped to the label.");