Control Statements
1. Conditional Statements
Conditional statements help your program make decisions.
1.1 if, else if, else
int number = 20;
if (number > 0)
{
Console.WriteLine("Number is positive");
}
else if (number < 0)
{
Console.WriteLine("Number is negative");
}
else
{
Console.WriteLine("Number is zero");
}
Explanation:
if→ Checks a condition and executes block if true.else if→ Checks another condition if the first is false.else→ Executes if all previous conditions are false.
1.2 switch statement
The switch statement is used when you have multiple discrete values to check.
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Explanation:
case→ Checks each value.break→ Exits the switch block.default→ Executes if no case matches.
2. Loops
Loops are used to execute a block of code repeatedly.
2.1 for loop
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Iteration: " + i);
}
Explanation:
i = 1→ Initializationi <= 5→ Conditioni++→ Increment
2.2 while loop
int i = 1;
while (i <= 5)
{
Console.WriteLine("Iteration: " + i);
i++;
}
Explanation: Executes the block while the condition is true.
2.3 do-while loop
int j = 1;
do
{
Console.WriteLine("Iteration: " + j);
j++;
} while (j <= 5);
Explanation: Executes the block at least once, then checks the condition.
2.4 foreach loop
Used to iterate over collections or arrays.
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Explanation: fruit takes each element in fruits array automatically.
3. Jump Statements
Jump statements control the flow inside loops or methods.
3.1 break
Exits the current loop or switch statement.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
break; // Stops the loop when i = 3
Console.WriteLine(i);
}
Output:
1
2
3.2 continue
Skips the current iteration and moves to the next.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue; // Skips iteration when i = 3
Console.WriteLine(i);
}
Output:
1
2
4
5
3.3 return
Exits the method immediately.
int AddNumbers(int a, int b)
{
if (a < 0 || b < 0)
return 0; // Exit method if invalid input
return a + b;
}
Console.WriteLine(AddNumbers(5, 3)); // 8
3.4 goto
Jumps to a labeled statement (use sparingly).
int k = 1;
start:
Console.WriteLine(k);
k++;
if (k <= 3)
goto start; // Jumps back to 'start' label
Output:
1
2
3
Summary of Chapter 3:
- Conditional statements (
if,else if,else,switch) make decisions. - Loops (
for,while,do-while,foreach) repeat code execution. - Jump statements (
break,continue,return,goto) control program flow inside loops and methods.