If-Else Statements

Conditional branching in C++

Interview Relevant: Basic control flow

If-Else Statements

Conditional statements control program flow based on conditions.

Syntax Forms

  • if: Execute if condition is true
  • if-else: Choose between two paths
  • if-else if-else: Multiple conditions
  • if with init (C++17): Initialize variable in if

Code Examples

Various forms of if-else statements.

cpp
1int score = 85;
2
3// Simple if
4if (score >= 60) {
5    cout << "Passed" << endl;
6}
7
8// if-else
9if (score >= 90) {
10    cout << "Grade A" << endl;
11} else {
12    cout << "Grade B or lower" << endl;
13}
14
15// if-else if-else chain
16if (score >= 90) {
17    cout << "A" << endl;
18} else if (score >= 80) {
19    cout << "B" << endl;
20} else if (score >= 70) {
21    cout << "C" << endl;
22} else {
23    cout << "F" << endl;
24}
25
26// C++17: if with initializer
27if (auto it = map.find(key); it != map.end()) {
28    cout << it->second << endl;
29}
30
31// Ternary operator
32string result = (score >= 60) ? "Pass" : "Fail";

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In