Control Statements
Control Statements
1. Conditional Statements
Conditional statements help your program make decisions.
1.1 if, else if, else
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.
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
Explanation:
i = 1→ Initializationi <= 5→ Conditioni++→ Increment
2.2 while loop
Explanation: Executes the block while the condition is true.
2.3 do-while loop
Explanation: Executes the block at least once, then checks the condition.
2.4 foreach loop
Used to iterate over collections or arrays.
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.
Output:
3.2 continue
Skips the current iteration and moves to the next.
Output:
3.3 return
Exits the method immediately.
3.4 goto
Jumps to a labeled statement (use sparingly).
Output:
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.