๐ 8. Decision Making
This lesson is organized in the same order a faculty member would normally teach it: meaning โ purpose โ syntax/model โ internal working โ examples โ common confusion โ safe use. The guided examples from the earlier lesson are preserved afterward for reinforcement.
8.1 What Is Decision Making?
So far, our programs have mostly followed statements from top to bottom. Real programs cannot always do that. They need to choose a different action depending on the data.
Input / current state
โ
Condition
/ \\
true false
โ โ
Action A Action B
\\ /
ContinueDecision 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.
int x = -5;
if (x)
{
puts("x is nonzero");
}
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.
Use braces even when there is only one statement. They make the intended block obvious and reduce maintenance mistakes.
8.4 if-else โ Choose Between Two Alternatives
if (n % 2 == 0)
{
puts("Even");
}
else
{
puts("Odd");
}
n % 2 == 0
โ
โโโโดโโโ
true false
โ โ
Even Odd
โโโโฌโโโโโ
โ
continueFor one execution of this statement, one branch is selected. The else block is the fallback when the if condition is false.
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
elseexecutes, if present.
If a broad condition is placed before a narrower condition, the later branch may never be reached. Write conditions from the most appropriate first test to the fallback cases.
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 allowedNested decisions are useful when the second question makes sense only after the first condition succeeds.
Deep nesting can make code difficult to understand. When the logic becomes complicated, consider clearer conditions, early returns, or separate functions.
8.7 The Dangling else โ A Common Beginner Trap
if (a > 0)
if (b > 0)
puts("both positive");
else
puts("b is not positive");
if owns the else?In C, an else belongs to the nearest unmatched if. Therefore the else above belongs to if (b > 0).
Braces remove the ambiguity and make the intended structure visible:
if (a > 0)
{
if (b > 0)
puts("both positive");
}
else
{
puts("a is not positive");
}
For beginner code and production code, braces are usually the safer and clearer choice.
8.8 switch โ Multi-Way Selection
switch is useful when one expression is compared against a set of discrete constant values.
switch (choice)
{
case 1:
puts("Add");
break;
case 2:
puts("Delete");
break;
default:
puts("Invalid choice");
}
switch is not a general replacement for conditions such as marks >= 90 or age > 18 && age < 60. It is designed around matching an expression with 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 โโโโโโโโโโโโโโโโ defaultWhen multiple labels intentionally share one block, fall-through is useful. When it happens accidentally because a break was forgotten, it becomes a bug.
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 when | Use switch when |
|---|---|
| Ranges or inequalities matter | One expression is matched against discrete constant values |
| Several variables participate in the condition | A menu, command or state maps naturally to cases |
| Complex logical expressions are required | Many exact-value alternatives would be clearer as cases |
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.
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 transfers control directly to a labeled statement in the same function.
if (resource2_failed)
goto cleanup_resource1;
/* normal work */
cleanup_resource1:
release_resource1();
In low-level C, a carefully controlled goto is sometimes used for cleanup when several resources may need to be released on different failure paths.
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");
The difference between > 40 and >= 40 changes the result for exactly one important boundary value.
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 casesRequirement: marks below 40 โ Fail; 40โ59 โ Pass; 60โ74 โ First Class; 75โ89 โ Distinction; 90+ โ Outstanding.
Before coding, write the ranges clearly. Then order the conditions so every value is covered exactly once.
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 Quick Revision
๐ 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.
๐ฌ Decision Making โ else-if Path
Follow how marks = 82 moves through an else-if ladder and selects exactly one grade.
๐ฌ Grade Decision Visualizer
The currently evaluated decision step becomes active as you move through the ladder.
๐ Program Tracing โ Decision Making
Trace an else-if ladder and observe how C stops checking conditions after the first true branch.
โ
8.16 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.
The if statement evaluates a condition and executes its block when the condition is true.
if-else provides one path when the condition is true and another path when it is false.
break exits the switch so execution does not continue into the following case.
The default label runs when none of the case values match the switch expression.
10 > 5 is true, so the if block executes and prints Yes.
switch is well suited to discrete fixed choices such as menu options 1, 2, 3, and 4.
8.17 ๐ฏ 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.
Problem 1: Check whether a number is positive, negative or zero.
Input: One integer n.
Output: Print Positive, Negative, or Zero.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
if (n > 0)
printf("Positive");
else if (n < 0)
printf("Negative");
else
printf("Zero");
return 0;
}Problem 2: Check whether a number is even or odd.
Input: One integer n.
Output: Print Even or Odd.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
if (n % 2 == 0)
printf("Even");
else
printf("Odd");
return 0;
}Problem 3: Find the largest of two numbers.
Input: Two integers a and b.
Output: Print the larger value.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int a, b;
scanf("%d %d", &a, &b);
if (a > b)
printf("%d", a);
else
printf("%d", b);
return 0;
}Problem 4: Find the largest of three numbers.
Input: Three integers a, b and c.
Output: Print the largest value.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
if (a >= b && a >= c)
printf("%d", a);
else if (b >= a && b >= c)
printf("%d", b);
else
printf("%d", c);
return 0;
}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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int marks;
scanf("%d", &marks);
if (marks >= 40)
printf("Pass");
else
printf("Fail");
return 0;
}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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int marks;
scanf("%d", &marks);
if (marks >= 90)
printf("Grade A");
else if (marks >= 75)
printf("Grade B");
else if (marks >= 60)
printf("Grade C");
else if (marks >= 40)
printf("Grade D");
else
printf("Fail");
return 0;
}Problem 7: Check whether a year is a leap year.
Input: One integer year.
Output: Print Leap Year or Not a Leap Year.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int year;
scanf("%d", &year);
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
printf("Leap Year");
else
printf("Not a Leap Year");
return 0;
}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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int a, b;
char op;
scanf("%d %c %d", &a, &op, &b);
switch (op)
{
case '+': printf("%d", a + b); break;
case '-': printf("%d", a - b); break;
case '*': printf("%d", a * b); break;
case '/':
if (b != 0) printf("%d", a / b);
else printf("Division by zero is not allowed");
break;
default: printf("Invalid operator");
}
return 0;
}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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int choice, a, b;
scanf("%d %d %d", &choice, &a, &b);
switch (choice)
{
case 1: printf("%d", a + b); break;
case 2: printf("%d", a - b); break;
case 3: printf("%d", a * b); break;
default: printf("Invalid choice");
}
return 0;
}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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int age, hasID;
scanf("%d %d", &age, &hasID);
if (age >= 18 && hasID == 1)
printf("Eligible");
else
printf("Not Eligible");
return 0;
}Problem 11: Find whether a character is a vowel or consonant.
Input: One alphabetic character.
Output: Print Vowel or Consonant.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
char ch;
scanf(" %c", &ch);
switch (ch)
{
case 'a': case 'e': case 'i': case 'o': case 'u':
case 'A': case 'E': case 'I': case 'O': case 'U':
printf("Vowel");
break;
default:
printf("Consonant");
}
return 0;
}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.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
if (a > 0 && b > 0 && c > 0 &&
a + b > c && a + c > b && b + c > a)
printf("Valid Triangle");
else
printf("Invalid Triangle");
return 0;
}8.18 Key Takeaway
Remember:
Problem โ Condition โ Decision โ Output
Master if, if-else, else-if, nested if and switch before moving to loops.
๐ค Decision Making โ Interview Questions
๐ก 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.
โ๏ธ Decision Making โ Extra Practice Questions
- Write conditions to classify a temperature as cold, moderate, or hot.
- Write an else-if ladder to classify a score into five ranges and test every boundary.
- Predict the output of a switch program when one case intentionally omits break.
- Rewrite a simple menu program once using if-else and once using switch, then compare readability.
- Write a nested decision that allows entry only when age is sufficient and an ID is available.
- Create test cases for a leap-year program that include century years such as 1900, 2000 and 2100.