C++ if-else Statements

C++ if-else Statements control the flow of the program based on conditions. If the expression evaluates to true, it executes certain statements within the if block; Otherwise, it executes statements within the else code block. This tutorial will teach you how to use if-else Statements in C++.

The basic format of if-else Statement is:

Syntax:

if(test_expression)
{
    //execute your code
}
else
{
    //execute your code
}

Figure - Flowchart of if-else Statement:

c++-if-else

Example of a C++ program to demonstrate an if-else Statement:

Example:

#include <iostream>
using namespace std;

int main()
{
    int a = 15, b = 20;

    if (b > a) {  
        cout << "b is greater" << endl;
    } else {  
        cout << "a is greater" << endl;
    }  
    system("PAUSE");
}

Program Output:

cplusplus-if-else

Example:

#include <iostream>
using namespace std;

int main()
{
    char name;
    int password;

    cout << "Enter the name: "; cin >> name;
    cout << " Enter your password: "; cin >> password;
    if (name == 'GG') {
        if (password == 1346) {
            cout << "Login successful";
        }
        else {
            cout << "Incorrect PASSWORD, Try again.";
        }
    }
    else {
        cout << " Incorrect Login Details, Try again.";
    }
}

Program Output:

Enter the name: GG
Enter your password: 1346
Login successful


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.