VOOZH about

URL: https://www.geeksforgeeks.org/cpp/c-c-if-else-statement-with-examples/

⇱ C++ if else Statement - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ if else Statement

Last Updated : 31 Mar, 2026

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it won’t. But what if we want to do something else if the condition is false. Here comes the C++ ifelse statement. We can use the else statement with if statement to execute a block of code when the condition is false.

Example:


Output
10 is less than 15

Explanation: The condition in the if block checks if 10 is less than 15. Its true so the statement inside if block, “10 is less than 15” gets printed and else block is skipped. If the condition was false, all the statements inside the if block will be skipped and else block will be executed.

Syntax

if (condition) {
// Executes this block if
// condition is true
}
else {
// Executes this block if
// condition is false
}

The if statement condition can be anything that evaluates to a boolean value or a boolean converted value. We generally use relational and equality operator to specify the condition.

Working of if-else statement

👁 Image
  1. Control enters the if statement.
  2. The condition is evaluated.
  3. If the condition is true, control goes to the if body.
  4. The if block statements are executed.
  5. If the condition is false, control goes to the else body.
  6. The else block statements are executed.
  7. After executing either block, control moves to the statement just below the if–else.
  8. The flow then exits the if–else structure.

Examples of if else Statement in C++

The following are a few basic examples of the if-else statement that shows the use of the if-else statement in a C++ program.

Check for Odd and Even Number


Output
Odd

You may have noticed that we skipped using the braces for the body of the if statement. If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block.

Find Largest Among Three Numbers


Output
11

Explanation: Finding largest element requires users to compare multiple condition. We can compare multiple conditions by nesting one condition inside other. There is also another way of combining multiple conditions.

The above program can also be written by using compound expressions as:


Output
11

In this code, we are grouping multiple conditions in a single if statement using logical AND operator. (&&)

Comment
Article Tags:
Article Tags: