CPP if and else

Controlling Flow with if and else Statements

Programs needs to take action based on a true condition, or another action based on a false condition.

For this we are using if and else statements which also both can be nested:

if (expression1) {
 if (expression2)
 else {
  if (expression3)
  • If the expression followed by the if statements evaluates to true, statements after the if statement will be executed else the statements after a else starts executing.
  • If more than one statement exists for either the true or the false part you need to surround the statements with braces ({}).
if & else example:
Source code Result
// Demonstrates if/else and 
// proper use of braces
// in nested if statements
#include <iostream>
int main()
  int number;
  std::cout << "Enter a number less than \n";
  std::cout << "5 or greater than 20: ";
  std::cin >> number;
  std::cout << "\n";
  if (number >= 5) {
    if (number > 20)
      std::cout << "Number is greater than 20!\n";
    std::cout << "Number is less than 5!\n";
  return 0;
Enter a number less than
5 or greater than 20: 23

Number is greater than 20!

You can download this example here (needed tools can be found in the right menu on this page).

The Conditional (Ternary) Operator.

This is a short notation to use for a simple if & else statement:
(expression1) ? (expression2) : (expression3)

This is: if expression1 is true, return the value of expression2; otherwise, return the value of expression3.
z = (x > y) ? x : y;
// returns x into z if x>y else z will be y
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.