C++ If else


Go to main Page

if else in C++

In this tutorial, we are going to learn if else in C++ with the help of examples

In computer programming, we use if for running a block of code if the condition is true.


For example assignment grades:

Forms of if..else statement

There are three forms of if..else statement.

  1. if statement
  2. if else statement
  3. if else..if else statements

C++ if Statement

Syntax

if (condition) {
   // body of if statement
}
    }

Explaination
Diagram

Example :Print positive number entered by user

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Enter an integer: ";
    cin >> number;

    // checks if the number is positive
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    }
    cout << "This statement is always executed.";
    return 0;
}

Output

Enter an integer: 5
You entered a positive number: 5
This statement is always executed.


C++ if...else

syntax

if (condition) {
    // block of code if condition is true
}
else {
    // block of code if condition is false
}

Diagram
Example :Find whether the number is even or odd.

#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter a number: ";
    cin >> n;

    if ( n % 2 == 0)
        cout << n << " is even.";
    else
        cout << n << " is odd.";

    return 0;
}

Output

Enter a number: 13
13 is odd.


C++ if...else if..else

syntax

if (condition1) {
    // code block 1
}
else if (condition2){
    // code block 2
}
else {
    // code block 3
}

Diagram
Example :Find whether the number is even or odd.

#include <iostream>
using namespace std;

int main() {
     int number;

    cout << "Enter an integer: ";
    cin >> number;
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    } 
else if (number < 0) {
      cout << "You entered a negative integer: " << number << endl;
     } 
else {
        cout << "You entered 0." << endl;
    }
     cout << "This line is always printed.";
    return 0;
}

Output

Enter an integer: 1
You entered a positive integer: 1.
This line is always printed.