🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C++ Notes
Topic #42

C++ If...Else


C++ Conditions and If Statements

You already know that C++ supports familiar comparison conditions from mathematics, such as:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to: a == b
  • Not equal to: a != b

These conditions are used to perform different actions depending on whether something is true or false.

C++ has the following conditional statements:

  • Use if to specify a block of code to be executed, if a condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of C++ code to be executed if a condition is true.

Syntax

if (condition) {
  // block of code to be executed if the condition is true
}

Note: that if is written in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, we print a message:

Example

if (20 > 18) {
  cout << "20 is greater than 18";
}

We can also use variables in conditions:

Example

int x = 20;
int y = 18;

if (x > y) {
  cout << "x is greater than y";
}

Example explained

In the example above, we use two variables, x and y, to test whether x is greater than y. Because 20 is greater than 18, the condition is true, and the message is printed.


Using a Boolean Variable

Since the condition in an if statement must be either true or false, you can store the result in a boolean variable instead of writing the comparison directly:

Example

int x = 20;
int y = 18;

bool isGreater = x > y;

if (isGreater) {
  cout << "x is greater than y";
}

This can make your code easier to read, especially when the condition is complex or used more than once.

Want to go beyond the notes?

Join CodingNow 2.0's C++ course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

C++ If...Else – FAQs

Quick answers about learning C++ If...Else in C++.

This free note from CodingNow 2.0 explains C++ If...Else in C++ — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C++ topic on CodingNow 2.0, including C++ If...Else, is 100% free with no signup required.
With focused practice, most students grasp C++ If...Else in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now