๐Ÿ”€ 8. Decision Making

๐ŸŽ“ Learn Decision Making Step by Step

A decision lets a program choose what to do next. Start with a simple condition, then learn how to choose between two or more actions. The examples show which branch runs, why it runs, and how to test the boundary values.

8.1 What Is Decision Making?

๐ŸŽฏ A Program Sometimes Has to Choose

The programs so far have mainly followed one statement after another. To print Pass for one mark and Fail for another, a program must choose a different action depending on the data.

Input / current state
        โ†“
     Condition
      /      \\
   true      false
    โ†“          โ†“
 Action A    Action B
        \\    /
         Continue
ifRun a block only when a condition is true
if-elseChoose between two alternatives
else-ifChoose among several conditions
switchChoose among discrete constant cases
?:Choose one of two values inside an expression
gotoTransfer control to a labeled statement; use carefully
๐Ÿ’ก Main idea

Decision making is not about memorizing if syntax. It is about controlling which path the program follows.

8.2 Conditions in C โ€” What Counts as True?

When C evaluates a controlling expression such as the expression inside if, zero means false and any nonzero value means true.

0false
1true
-5true
100true
int x = -5;

if (x)
{
    puts("x is nonzero");
}
โš ๏ธ Important:

A condition does not have to equal exactly 1. Any nonzero value is treated as true. Relational and logical operators commonly produce 0 or 1, but if can test other scalar expressions too.

8.3 Simple if โ€” Run Something Only When Needed

Use if when there is an action that should happen only if a condition is satisfied.

if (temperature > 40)
{
    puts("High temperature");
}
Evaluate temperature > 40
          โ†“
       Is it true?
       /       \\
     YES        NO
      โ†“          โ†“
 print message  skip block
      \          /
       โ†“        โ†“
       continue after if
  • The condition is evaluated first.
  • If it is nonzero, the controlled statement/block executes.
  • If it is zero, the block is skipped.
  • Execution then continues with the statement after the if.
๐ŸŽฏ Good habit:

Use braces even for one statement. If you add another line later, the braces make it clear whether that line belongs inside the decision.

8.4 if-else โ€” Choose Between Two Alternatives

if (n % 2 == 0)
{
    puts("Even");
}
else
{
    puts("Odd");
}
n % 2 == 0
     โ†“
  โ”Œโ”€โ”€โ”ดโ”€โ”€โ”
 true  false
  โ†“       โ†“
Even     Odd
  โ””โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜
     โ†“
  continue

For one execution of this statement, one branch is selected. The else block is the fallback when the if condition is false.

๐Ÿ’ก When to use it

Use if-else when the problem naturally says โ€œif this happens, do A; otherwise, do B.โ€

8.5 else-if Ladder โ€” Check Conditions in Order

if (marks >= 90)
    grade = 'A';
else if (marks >= 75)
    grade = 'B';
else if (marks >= 60)
    grade = 'C';
else
    grade = 'D';
marks >= 90 ?  โ†’ A
      โ†“ no
marks >= 75 ?  โ†’ B
      โ†“ no
marks >= 60 ?  โ†’ C
      โ†“ no
     else     โ†’ D
  • Conditions are evaluated from top to bottom.
  • The first true condition selects its branch.
  • Once a branch is selected, the remaining conditions are skipped.
  • If no condition is true, the final else executes, if present.
โš ๏ธ Condition order matters

For a grade ladder, check marks >= 90 before marks >= 75. A score of 95 satisfies both conditions. If the 75 test comes first, the 90 branch will never run for that score.

8.6 Nested if โ€” A Decision Inside Another Decision

if (usernameValid)
{
    if (passwordValid)
    {
        puts("Login allowed");
    }
    else
    {
        puts("Wrong password");
    }
}
Username valid?
      โ†“
   โ”Œโ”€โ”€โ”ดโ”€โ”€โ”
  NO    YES
  โ†“       โ†“
stop   Password valid?
          โ†“
       โ”Œโ”€โ”€โ”ดโ”€โ”€โ”
      NO    YES
      โ†“       โ†“
 wrong     allowed

A nested decision checks another condition inside a selected branch. For example, first check whether a user is old enough, then check whether an ID is available.

๐ŸŽฏ Readability rule

Keep each level of nesting easy to follow. If there are too many levels, combine related conditions or move a separate task into a function.

8.7 The Dangling else โ€” A Common Beginner Trap

if (a > 0)
    if (b > 0)
        puts("both positive");
    else
        puts("b is not positive");
โš ๏ธ Which if owns the else?

In C, an else belongs to the nearest unmatched if. Therefore the else above belongs to if (b > 0).

Use braces to show exactly which statements belong to each branch:

if (a > 0)
{
    if (b > 0)
        puts("both positive");
}
else
{
    puts("a is not positive");
}
๐Ÿ’ก CodeBhavya rule:

Indent the branches clearly and use braces. Indentation helps a person read the program; the braces determine the actual blocks.

8.8 switch โ€” Multi-Way Selection

switch is useful when one expression is compared against a set of discrete constant values. Its controlling expression must have an integer type, such as int or char. Each case needs an integer constant expression, and duplicate case values are not allowed. Strings and floating-point values cannot be used directly as switch cases.

switch (choice)
{
    case 1:
        puts("Add");
        break;

    case 2:
        puts("Delete");
        break;

    default:
        puts("Invalid choice");
}
switchExpression being tested
caseConstant value to match
breakLeave the switch
defaultRuns when no case matches
โš ๏ธ Not for every condition

switch is not a general replacement for conditions such as marks >= 90 or age > 18 && age < 60. Use if-else for these comparisons. A switch matches one integer value against fixed case values.

8.9 break and Fall-Through in switch

After a matching case is entered, execution continues through following statements until a control-flow transfer such as break occurs or the switch ends.

switch (grade)
{
    case 'A':
    case 'B':
        puts("Pass with strong grade");
        break;

    default:
        puts("Other grade");
}
grade == 'A' โ”€โ”
              โ”œโ†’ same block โ†’ break โ†’ exit switch
grade == 'B' โ”€โ”˜

no match โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ default

When multiple labels intentionally share one block, fall-through is useful. When it happens accidentally because a break was forgotten, it becomes a bug.

๐ŸŽฏ Interview point:

break exits the nearest enclosing switch or loop. It does not mean โ€œgo to the next case.โ€

8.10 if-else vs switch โ€” Choose by the Problem

Use if/else whenUse switch when
Ranges or inequalities matterOne expression is matched against discrete constant values
Several variables participate in the conditionA menu, command or state maps naturally to cases
Complex logical expressions are requiredMany exact-value alternatives would be clearer as cases
๐Ÿ’ก Example

marks >= 90 is naturally an if condition. A menu choice such as 1 = Add, 2 = Delete, 3 = Exit is naturally expressed with switch.

8.11 Conditional Operator ?: โ€” Choose a Value

int max = (a > b) ? a : b;
condition: a > b
       โ†“
   โ”Œโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”
 true     false
  โ†“          โ†“
  a          b
   \        /
    โ†’ value โ†

The conditional operator is an expression. It evaluates the condition and produces one of two expression results.

conditionTest to perform
?Choose the true expression
true expressionResult when condition is true
:Separates the two choices
false expressionResult when condition is false
โš ๏ธ Don't overuse it

A short value selection can be clear with ?:. Large nested conditional expressions can become harder to read than a normal if-else.

8.12 goto and Labels โ€” Unconditional Transfer

goto jumps to a labeled statement within the same function. Execution continues from that label rather than from the next line.

if (resource2_failed)
    goto cleanup_resource1;

/* normal work */

cleanup_resource1:
    release_resource1();
๐Ÿ’ก Where it can be useful

In low-level C, a carefully controlled goto can send several error paths to one cleanup section. For example, that section might close an already opened file before returning.

โš ๏ธ Why beginners are told to avoid it

Unstructured jumps can make control flow difficult to follow. Do not use goto merely to replace normal if, loops or functions. Understand structured control flow first.

8.13 Boundary Conditions Are Part of the Algorithm

A decision is not complete until you know what happens at the boundary values.

if (marks >= 40)
    puts("Pass");
else
    puts("Fail");
39Fail
40Pass
41Pass

The difference between > 40 and >= 40 changes the result for exactly one important boundary value.

๐ŸŽฏ Placement habit

Whenever you write a condition, test at least one value below, one value at, and one value above the boundary.

8.14 Decision-Design Method โ€” Think Before Writing if

1. Understand the requirement
          โ†“
2. Identify the possible outcomes
          โ†“
3. Identify the condition for each outcome
          โ†“
4. Check boundary values
          โ†“
5. Choose if / if-else / else-if / switch
          โ†“
6. Write the simplest clear structure
          โ†“
7. Test normal + boundary + invalid cases
Step 1What decision does the problem require?
Step 2What are all possible outcomes?
Step 3What exact condition selects each outcome?
Step 4What happens at equality and boundaries?
Step 5Which C construct communicates the rule best?
Step 6Can another programmer understand it quickly?
๐Ÿ’ก Example: student result

Example rule for marks from 0 to 100: below 40 โ†’ Fail; 40โ€“59 โ†’ Grade D; 60โ€“74 โ†’ Grade C; 75โ€“89 โ†’ Grade B; 90โ€“100 โ†’ Grade A. These are the practice programโ€™s sample rules, not an official university grading policy.

Write the ranges before coding. Check that every permitted mark belongs to exactly one range, then test each boundary.

โš ๏ธ Avoid โ€œcondition guessingโ€

Do not start writing if statements before deciding the ranges. Most decision bugs come from missing boundaries, overlapping conditions or incorrect condition orderโ€”not from the if syntax itself.

8.15 Multiple switch Labels and Explicit Fallthrough

Several case labels can lead to the same statements. Here, day 6 and day 7 both print Weekend. The break leaves the switch after that shared action. The default branch handles a value that matches no case.

Complete C program:

#include <stdio.h>

int main(void)
{
    int day = 6;
    switch (day) {
        case 6:
        case 7:
            puts("Weekend");
            break;
        case 1: case 2: case 3: case 4: case 5:
            puts("Weekday");
            break;
        default:
            puts("Invalid day");
    }
    return 0;
}

Expected output:

Weekend

Step-by-step explanation:

  1. case 6 is selected.
  2. There are no statements before case 7, so execution continues into the shared group.
  3. The break exits the switch.
Remember: A missing break can make the next group run too. Leave it out only when that continuation is intentional and clearly explained.

8.16 Quick Revision

๐Ÿ“Œ if โ†’ One condition

๐Ÿ“Œ if-else โ†’ Two alternatives

๐Ÿ“Œ else-if โ†’ Multiple conditions

๐Ÿ“Œ Nested if โ†’ Decision inside another decision

๐Ÿ“Œ switch โ†’ Multiple discrete choices

๐Ÿ“Œ break โ†’ Exit switch

๐Ÿ“Œ default โ†’ No case matched

๐Ÿ“Œ Always test boundary cases.
INTERACTIVE LEARNING

๐ŸŽฌ Decision Making โ€” else-if Path

Follow how marks = 82 moves through an else-if ladder and selects exactly one grade.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” Decision Making

Trace an else-if ladder and observe how C stops checking conditions after the first true branch.

8.17 Quick MCQs

Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.

1.Which statement is used to make a decision based on a condition?
2.Which statement provides two alternatives?
3.Which keyword terminates a switch case when fall-through is not intended?
4.Which keyword handles unmatched switch cases?
5.What is the output of: int n = 10; if (n > 5) { printf("Yes"); }
6.Which is best suited for checking multiple fixed menu choices?
PRACTICE

8.18 ๐ŸŽฏ Practice Problems

Decision making becomes easy when you practice conditions and boundary cases. Use ๐Ÿ’ป Solve It Yourself first, open Hint only when needed, and use Show Program after attempting the problem.

๐Ÿ“ˆ Decision Making Practice Progress
Solved0 / 12
Completed with Solution0
Total Score0 / 240
Completion0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Positive, Negative or Zero

Problem 1: Check whether a number is positive, negative or zero.

Input: One integer n.

Output: Print Positive, Negative, or Zero.

2. Even or Odd

Problem 2: Check whether a number is even or odd.

Input: One integer n.

Output: Print Even or Odd.

3. Largest of Two Numbers

Problem 3: Find the largest of two numbers.

Input: Two integers a and b.

Output: Print the larger value.

4. Largest of Three Numbers

Problem 4: Find the largest of three numbers.

Input: Three integers a, b and c.

Output: Print the largest value.

5. Pass or Fail

Problem 5: Check whether a student has passed or failed.

Input: One integer marks. Assume 40 is the pass mark.

Output: Print Pass or Fail.

6. Grade Based on Marks

Problem 6: Print the grade based on marks.

Input: One integer marks from 0 to 100.

Output: Print Grade A, Grade B, Grade C, Grade D, or Fail.

7. Leap Year

Problem 7: Check whether a year is a leap year.

Input: One integer year.

Output: Print Leap Year or Not a Leap Year.

8. Calculator Using switch

Problem 8: Create a calculator using switch.

Input: An integer a, an operator (+, -, *, /), and an integer b.

Output: Print the integer result, Invalid operator, or Division by zero is not allowed.

9. Menu-Driven Arithmetic

Problem 9: Create a menu-driven program for addition, subtraction and multiplication.

Input: choice, a and b. Use 1 for addition, 2 for subtraction and 3 for multiplication.

Output: Print the result or Invalid choice.

10. Eligibility with Two Conditions

Problem 10: Check whether a person is eligible based on age and another condition.

Input: Two integers: age and hasID, where hasID is 1 for yes and 0 for no.

Output: Print Eligible only when age >= 18 and hasID == 1; otherwise print Not Eligible.

11. Vowel or Consonant

Problem 11: Find whether a character is a vowel or consonant.

Input: One alphabetic character.

Output: Print Vowel or Consonant.

12. Valid Triangle

Problem 12: Check whether three sides can form a valid triangle.

Input: Three integers a, b and c representing side lengths.

Output: Print Valid Triangle or Invalid Triangle.

8.19 Key Takeaway

๐ŸŽฏ Decision making is the bridge between understanding a problem and writing a program.

Remember:

Problem โ†’ Condition โ†’ Decision โ†’ Output

Master if, if-else, else-if, nested if and switch before moving to loops.
INTERVIEW PREPARATION

๐ŸŽค Decision Making โ€” Interview Questions

1.What is the difference between if and if-else?
2.Why does the order of conditions matter in an else-if ladder?
3.When is switch preferred over if-else?
4.What happens when break is omitted in a switch case?
5.What is the role of default in switch?
6.What is a nested if statement?
7.Why are boundary cases important in decision-making programs?
8.What common mistake occurs with = and == inside conditions?
PLACEMENT TIPS

๐Ÿ’ก Decision Making โ€” Placement Tips

  • For an else-if ladder, write the most restrictive or highest-range conditions first when ranges overlap.
  • Always test the exact boundary values around a condition: for a pass mark of 40, test 39, 40 and 41.
  • Use switch for discrete menu values; use if-else for ranges, relational tests and compound logical conditions.
  • In output-prediction questions, trace only the branch that actually executes and remember that an else-if ladder stops at the first true condition.
  • When using switch, check whether fall-through is intentional before omitting break.
  • Keep nested decisions readable. If nesting becomes deep, simplify the conditions or split the logic into smaller functions later.
EXTRA PRACTICE

โœ๏ธ Decision Making โ€” Extra Practice Questions

  1. Write conditions to classify a temperature as cold, moderate, or hot.
  2. Write an else-if ladder to classify a score into five ranges and test every boundary.
  3. Predict the output of a switch program when one case intentionally omits break.
  4. Rewrite a simple menu program once using if-else and once using switch, then compare readability.
  5. Write a nested decision that allows entry only when age is sufficient and an ID is available.
  6. Create test cases for a leap-year program that include century years such as 1900, 2000 and 2100.
โ† Previous Topic: ExpressionsNext Topic: Loops โ†’