TeachMate
My ProgressJoin Session

Conditionals

0/6 completed · ~0h 35m

All Topics
C++LearnConditionalsSyllabus
1 / 6

Conditional Statements

beginner
7 min read

What you'll learn

  • Write if/else chains that choose exactly one path.
  • Use switch for many constant cases.
  • Trace a condition and predict which branch runs.

Conditional statements let your program make decisions.

Problem

A student is marked out of 100 and you must print whether they passed. Writing both outcomes as separate lines of code gets wrong the moment the pass mark changes.

Goal: Decide Passed or Failed from one condition so the pass mark is written down exactly once.

Pseudocode
READ marks
IF marks >= 40
    PRINT "Passed"
ELSE
    PRINT "Failed"

A program makes the same decision with an if statement:

if (marks >= 40) {
    cout << "Pass";
} else {
    cout << "Fail";
}

Every decision is a condition (true or false) plus what to do in each case. The rest of this note covers the different forms.

if Statement

if (condition) {
    // executes if condition is true
}

if-else

if (condition) {
    // executes if true
} else {
    // executes if false
}

if-else if-else

if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}

Nested if

if (age >= 18) {
    if (hasID) {
        cout << "Enter";
    } else {
        cout << "Need ID";
    }
} else {
    cout << "Too young";
}

Short Syntax (Single Statement)

if (x > 0) cout << "positive";  // No braces needed for one line

Ternary Operator (Shortcut)

string result = (score >= 50) ? "Pass" : "Fail";

Equivalent to:

string result;
if (score >= 50) {
    result = "Pass";
} else {
    result = "Fail";
}

Flowchart of an if / else-if Ladder

Flowchart: if / else-if grade ladderStartRead scorescore >= 90?YesGrade ANoscore >= 80?YesGrade BNoscore >= 70?YesGrade CNoGrade FEnd
Conditions are checked top to bottom; the first match wins.

Complete Program: Grading with if / else-if

#include <iostream>

int main() {
    int score = 72;

    if (score >= 90) {
        std::cout << "Grade A\n";
    } else if (score >= 80) {
        std::cout << "Grade B\n";
    } else if (score >= 70) {
        std::cout << "Grade C\n";
    } else {
        std::cout << "Grade F\n";
    }
    return 0;
}

Common mistakes: an = in a condition assigns instead of compares — if (x = 0) compiles but is almost always a bug; use ==.

Key takeaway: Always use braces even for single-line bodies, and chain mutually exclusive conditions with else-if for clear, readable decision logic.

Try it: Write a program that reads a temperature and prints "Freezing" if below 0, "Comfortable" between 18-24, and "Hot" above 30.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects