Nested if-else statements in c++

Nested if-else statements in c++



/*A c++ program example that takes input from user for username and password and then makes decision.*/


// Program 1

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";


int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    cout << "Password: ";
    cin >> pass;

    if (name == userName)
    {
        if (pass == passWord)
            cout << "You are logged in!" << endl;
        else
            cout << "Incorrect username or password." << endl;
    }
    else
        cout << "Incorrect username or password." << endl;

    return 0;
}


/*A c++ program example that takes input from user for username and if username is correct then only asks for password and makes decision.*/


// Program 2

#include <iostream>
#include <string>

using namespace std;

const string userName = "computergeek";
const string passWord = "break_codes";

int main ()
{
    string name, pass;

    cout << "Username: ";
    cin >> name;

    if (name == userName)
    {
        cout << "Password: ";
        cin >> pass;

        if (pass == passWord)
            cout << "You are logged in!" << endl;
        else
            cout << "Incorrect password." << endl;
    }
    else
        cout << "Incorrect username." << endl;

    return 0;
}


Programming Advice & Explanation:


Whenever possible avoid nesting or deep nesting as it makes program difficult to read. We should program in a manner that it can be read and understood easily by us and other programmers. For example, in the "Program 1" the nesting can be avoided by using logical operator. However in "Program 2" the nesting is required as we want to take input for password only if username is correct.

In the next chapter we will learn about logical operators and will rewrite the "Program 1" using it.

Check out this stream