Search⌘ K
AI Features

Conditional Branching with if/else

Explore conditional branching in C++ using if, else, and else if statements to direct program logic based on evaluated conditions. Understand how to handle multiple conditions, user input, and variable scope within blocks. Learn common pitfalls like assignment vs equality and how nesting conditions can manage complex decision-making. This lesson helps you implement dynamic, responsive code that adapts to data and user input effectively.

Up to this point, our programs have followed a strictly linear execution model, in which statements run sequentially from beginning to end. However, real-world applications require the ability to make decisions based on data. For example, a game must determine whether a player has sufficient health to survive an attack, and a banking application must verify that a user has adequate funds before processing a transaction. To support this behavior, programs rely on conditional branching, which allows the flow of execution to change based on evaluated conditions.

In this lesson, we will use the if statement and its related constructs used to enable logical decision-making in C++ programs.

The if statement

The fundamental building block of decision-making in C++ is the if statement. It evaluates a condition (a boolean expression) and executes a block of code next to it, only if that condition is true.

Basic if Statement
Basic if Statement

If the condition is false, the program skips the block entirely and continues with the rest of the code.

if (condition) {
// Code to run if condition is true
}

We enclose the code to be executed within curly braces {}. This creates a block. While C++ allows omitting braces for a single statement, we always use them. This habit prevents serious bugs when we modify the code later.

C++ 23
#include <iostream>
int main() {
int score = 85;
std::cout << "Checking exam results...\n";
// Simple if statement
if (score >= 50) {
std::cout << "You passed the exam!\n";
}
std::cout << "Grade check complete.\n";
return 0;
}

Let’s break this down step by step:

  • Lines 4–6: We initialize score and print a status message.

  • Line 9: The if statement checks score >= 50. Since 85 is greater than 50, the expression evaluates to true.

  • Line 10: The ...