Understand and use nested statements
Nested Statements
Nested statements are statements that are placed inside other statements. Think of them as layers of an onion – each layer can control the next one. For example, the condition $x > 0$ checks if x is positive.
1️⃣ What are Nested Statements?
In programming, a statement is a line of code that performs an action. A nested statement is a statement that appears inside another statement, such as an if inside an if or a for inside a while.
2️⃣ Why Use Them?
- Control flow becomes more precise.
- Allows complex decision-making.
- Reduces the need for multiple separate statements.
3️⃣ Common Nested Structures
ifinsideif– if-else-if chainsforinsidewhile– looping over a loopswitchinsideif– conditional branching
4️⃣ Example: Nested If Statements
Consider a simple program that checks a student’s grade and gives a remark.
if (grade >= 90) {
if (attendance >= 90) {
console.log("Excellent! 🎉");
} else {
console.log("Excellent, but improve attendance. 📚");
}
} else if (grade >= 75) {
console.log("Good job! 👍");
} else {
console.log("Needs improvement. 🔄");
}
5️⃣ Example: Nested Loops
Printing a multiplication table using nested for loops.
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(i + " × " + j + " = " + (i * j));
}
}
The product of i and j is represented as $i \times j$.
6️⃣ Visualising Nested Statements
| Statement | Nested Inside |
|---|---|
if (x > 0) |
if (y > 0) |
for (i = 0; i < n; i++) |
while (condition) |
indentation to keep track of nesting levels.
7️⃣ Quick Practice
- Write a nested
ifthat checks if a number is positive, and if it is, checks whether it is even or odd. - Write nested
forloops to print a 3×3 grid of numbers.
8️⃣ Summary
Nested statements let you build complex decision trees and loops. They are essential for:
- Decision making (if-else, switch)
- Iterating over data structures (for inside while)
- Organising code logically
Remember: indentation is your best friend – it shows the hierarchy of nested statements. 🧩
Revision
Log in to practice.