C++ Tutorial menu

C++ If...Else and Switch

Conditions let your program decide what to do based on the data it has.

if and else

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int balance = 1500;
  int fare = 250;

  if (balance >= fare) {
    balance -= fare;
    cout << "Ride booked. Balance left: " << balance << "\n";
  } else {
    cout << "Please top up your wallet\n";
  }
  return 0;
}
Output
Ride booked. Balance left: 1250

else if

Check conditions one after another. Only the first true block runs:

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int hour = 15;

  if (hour < 12) {
    cout << "Good morning\n";
  } else if (hour < 17) {
    cout << "Good afternoon\n";
  } else {
    cout << "Good evening\n";
  }
  return 0;
}
Output
Good afternoon

Nested if

You can put an if inside another if:

Example

cpp
int age = 20;
bool hasLicense = false;

if (age >= 18) {
  if (hasLicense) {
    cout << "You can drive\n";
  } else {
    cout << "Get a license first\n";
  }
}
Output
Get a license first

Deep nesting is hard to read. Often you can join the conditions with && instead, like if (age >= 18 && hasLicense).

The Ternary Operator

condition ? a : b gives a when true and b when false:

Example

cpp
int marks = 45;
string result = (marks >= 50) ? "Pass" : "Fail";
cout << result << "\n";
Output
Fail

switch

switch compares one value (an integer, char or enum) against fixed cases:

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int option = 2;

  switch (option) {
    case 1:
      cout << "Check balance\n";
      break;
    case 2:
      cout << "Withdraw cash\n";
      break;
    case 3:
      cout << "Change PIN\n";
      break;
    default:
      cout << "Invalid option\n";
  }
  return 0;
}
Output
Withdraw cash
KeywordMeaning
caseOne value to match
breakStops the switch here
defaultRuns when no case matches

switch does not work with string. For text, use if and else if instead.

if with an Initializer (C++17)

Modern C++ lets you create a variable that only lives inside the if:

Example

cpp
if (int stock = 3; stock < 5) {
  cout << "Low stock: " << stock << "\n";
}
Output
Low stock: 3

Exercise

Exercise

What happens if you leave out break at the end of a case in a C++ switch?

Learn C++ with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp