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

  1. if inside ifif-else-if chains
  2. for inside whilelooping over a loop
  3. switch inside ifconditional 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)
Exam Tip: When you see a question about nested statements, look for the “inner” part of the code. Identify the outer statement first, then the inner one. Remember that the inner statement only runs if the outer condition is true. Use the indentation to keep track of nesting levels.

7️⃣ Quick Practice

  1. Write a nested if that checks if a number is positive, and if it is, checks whether it is even or odd.
  2. Write nested for loops to print a 3×3 grid of numbers.
Exam Tip: Practice writing nested statements in plain English first. For example: “If the temperature is above 30°C, then if the humidity is above 70%, print ‘It’s hot and humid’.” Then translate that into code.

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.

1 views 0 suggestions