Control Statements - Textnotes

Control Statements


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:

  1. if → Checks a condition and executes block if true.
  2. else if → Checks another condition if the first is false.
  3. 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:

  1. case → Checks each value.
  2. break → Exits the switch block.
  3. 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:

  1. i = 1 → Initialization
  2. i <= 5 → Condition
  3. i++ → 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:

  1. Conditional statements (if, else if, else, switch) make decisions.
  2. Loops (for, while, do-while, foreach) repeat code execution.
  3. Jump statements (break, continue, return, goto) control program flow inside loops and methods.