If-Else — Teaching Your Code to Make Decisions
Give your code the power to think! Learn how to make it choose different paths based on conditions.
Open interactive version (quiz + challenge)Real-world analogy
If-else is like a traffic light. When the light is green (condition is true), you GO — the code inside the if-block runs. When the light is red (condition is false), you STOP — and the code inside the else-block runs instead. Your code reaches a fork in the road and decides which way to go based on a condition you set!
What is it?
If-else statements let your code make decisions. The 'if' checks a condition — if it is true, one block of code runs. If it is false, the 'else' block runs instead. This is called 'conditional execution' or 'branching' because your program branches into different paths.
Real-world relevance
Decisions are everywhere in programs! ATMs check if you have enough balance before dispensing cash. Games check if your health reaches zero to trigger 'Game Over.' Login forms check if the password matches. In CP, if-else is used to handle different cases in a problem: positive vs negative, even vs odd, possible vs impossible.
Key points
- The if Statement — 'Do This If True' — The if statement checks a condition and runs code ONLY if the condition is true. Syntax: if (condition) { code here }. The condition goes inside parentheses (). The code to run goes inside curly braces {}. If the condition is false, the code is simply skipped. It is like saying: 'If it is raining, take an umbrella.'
- The else Statement — 'Otherwise Do This' — The else block runs when the if condition is FALSE. Syntax: if (condition) { code A } else { code B }. Exactly ONE of the two blocks runs — never both, never neither. It is like saying: 'If it is raining, take an umbrella. Otherwise, wear sunglasses.' You always get one outcome.
- Comparison Operators — How to Compare — To make conditions, you use comparison operators: == (equal to), != (not equal), (greater than), = (greater than or equal). IMPORTANT: == has TWO equal signs! A single = is assignment (setting a value), not comparison. Writing if (a = 5) is a VERY common bug — it sets a to 5 instead of comparing!
- == vs = — The Classic Trap — This is the most common beginner mistake: = means 'assign' (put a value in a variable), == means 'compare' (check if two things are equal). if (x = 5) does NOT check if x equals 5 — it SETS x to 5 and always runs! You want if (x == 5). Many CP veterans have lost hours to this one-character bug!
- Nested If — Decisions Inside Decisions — You can put an if inside another if. This is called nesting. Example: if (age >= 18) { if (hasID) { enter(); } }. This checks two conditions: first age, then ID. Nesting more than 2-3 levels deep gets messy though — later we will learn logical operators (&&, ||) as a cleaner alternative.
- Common CP Pattern — Checking Conditions on Input — In CP, the most common use of if-else is: read input, check some condition, print a result. Like: 'Read a number. If it is even, print YES. Otherwise print NO.' This pattern appears in hundreds of CP problems. Read → Check → Print. Simple but powerful!
- One-Line If — No Braces Needed — If your if/else block has only ONE line, you can skip the curly braces: if (n > 0) cout << "Positive"; But be careful! If you later add a second line, it will NOT be part of the if. Most CP coders always use braces to be safe. It is a style choice, but braces prevent bugs.
Code example
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
// Basic if-else: check positive or negative
if (n > 0) {
cout << "Positive\n";
} else if (n < 0) {
cout << "Negative\n";
} else {
cout << "Zero\n";
}
// Check even or odd
if (n % 2 == 0) {
cout << "Even\n";
} else {
cout << "Odd\n";
}
// CP classic: read two numbers and print the bigger one
int a, b;
cin >> a >> b;
if (a > b) {
cout << a << "\n";
} else if (b > a) {
cout << b << "\n";
} else {
cout << "Equal\n";
}
// Comparison operators demo
int x = 10, y = 20;
cout << (x == y) << "\n"; // 0 (false)
cout << (x != y) << "\n"; // 1 (true)
cout << (x < y) << "\n"; // 1 (true)
cout << (x >= y) << "\n"; // 0 (false)
return 0;
}Line-by-line walkthrough
- 1. int n; cin >> n; — we read a number from input. This is the number we will test with our if-else conditions.
- 2. if (n > 0) — we check: is n greater than zero? If yes, the code inside the curly braces runs.
- 3. cout 0 is true.
- 4. else if (n < 0) — if the first condition was false, we check: is n less than zero?
- 5. else — if n is not positive AND not negative, it must be zero. The else block catches everything that the if and else-if did not.
- 6. if (n % 2 == 0) — classic even/odd check. n % 2 gives the remainder when dividing by 2. If the remainder is 0, n is even.
- 7. int a, b; cin >> a >> b; — we read two numbers to compare them.
- 8. if (a > b) — checks if a is larger. else if (b > a) checks if b is larger. else means they are equal. This three-way comparison covers ALL cases.
- 9. cout << (x == y); — the comparison x == y evaluates to true (1) or false (0). In C++, true is 1 and false is 0.
- 10. cout << (x != y); — checks if x is NOT equal to y. Since 10 != 20 is true, this prints 1.
Spot the bug
#include <bits/stdc++.h>
using namespace std;
int main() {
int password = 1234;
int guess;
cin >> guess;
if (guess = password) {
cout << "Access Granted!\n";
} else {
cout << "Wrong Password!\n";
}
return 0;
}Need a hint?
Look very carefully at the if condition. Is it COMPARING guess to password, or doing something else?
Show answer
The bug is using = (assignment) instead of == (comparison) in the if condition. 'if (guess = password)' SETS guess to 1234 and then checks if 1234 is non-zero (it is!), so it ALWAYS prints 'Access Granted!' no matter what you type. The fix: change to if (guess == password). One extra = makes all the difference!
Explain like I'm 5
Imagine you are at an ice cream shop. You ask: 'Do you have chocolate?' If YES, you get chocolate ice cream. If NO (else), you get vanilla instead. That is exactly what if-else does — it asks a question, and depending on the answer, your code does different things!
Fun fact
The first 'conditional branching' in computing history was in Charles Babbage's Analytical Engine design from 1837 — almost 200 years ago! Ada Lovelace wrote about how the machine could 'decide' which instructions to follow based on results. Every if-else you write today is using the same idea that Ada thought of before computers even existed!
Hands-on challenge
Write a program that reads an integer n. If n is divisible by both 3 and 5, print 'FizzBuzz'. If only divisible by 3, print 'Fizz'. If only divisible by 5, print 'Buzz'. Otherwise, print the number itself. Test with n=15 (FizzBuzz), n=9 (Fizz), n=10 (Buzz), n=7 (7).
More resources
- Codeforces — Anton and Danik (Codeforces)
- If-Else in C++ — Beginner Friendly (YouTube)
- USACO Guide — Basic Complete Search (USACO Guide)