Chapter 6: Decision Making (Control Flow)

1. if Statement (Simple Decision)

Syntax:

C

Condition must be something that is true (non-zero) or false (zero).

Example:

C

Sample Output:

  • If you enter 20 → “You are eligible to vote!”
  • If you enter 15 → Nothing special, just “Thank you…”

2. if…else Statement (Two Choices)

Syntax:

C

Example:

C

3. Nested if…else (if inside if)

When you need more than two choices or conditions depend on each other.

Example:

C

4. else if Ladder (Multiple Choices)

Used when you have many conditions to check one by one.

Syntax:

C

Example – Grading System

C

5. switch…case Statement (Best for Multiple Fixed Choices)

Used when you have one variable and many exact values to compare.

Syntax:

C

Important:

  • Always use break; otherwise next cases will also run (called fall-through)
  • default is optional – runs if no case matches

Example – Day of the Week

C

6. Ternary Operator (?:) – Short if…else

Syntax:

C

Example:

C

Very useful for short decisions.

7. goto Statement (and Why You Should Avoid It)

goto jumps to a labeled part of the code.

Syntax:

C

Example (just for understanding – NOT recommended):

C

Why Avoid goto?

  • Makes code very hard to read and understand (spaghetti code)
  • Can create bugs that are difficult to find
  • Almost every program can be written better using if, else, loops, functions
  • Famous programmers (like Dijkstra) said: “goto is considered harmful”

Rule: Never use goto in normal programs. Use it only in very special cases (like breaking out of nested loops – but even then, better ways exist).

Today’s Homework

  1. Write a program using if…else to check if a number is positive, negative, or zero.
  2. Create a program using else if ladder to check temperature:
    • 35 → Very Hot

    • 25–35 → Hot
    • 15–25 → Pleasant
    • < 15 → Cold
  3. Write a switch program that takes a character (A, B, C, D, F) and prints the meaning (Excellent, Very Good, Good, Average, Fail).
  4. Use ternary operator to find the maximum of two numbers entered by the user.

You may also like...