Kamis, 12 Januari 2012

Nested if-else statements in c++



// Program 1

#include
#include

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;
}


// Program 2

#include
#include

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;
}


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.


Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.


View the original article here



Peliculas Online

0 komentar:

Posting Komentar