Kamis, 12 Januari 2012

Selection Statement (if-else if-else) in c++



To understand this chapter you should know about Comparison Operators which is explained in previous chapter. Selection statements are very important in programming because we make decisions using it.
// Program 1

#include
#include

using namespace std;

int main ()
{
int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
cin >> first;

    cout << "Second "<< setw (2) << ": ";
cin >> second;

    if (first > second)
cout << "first is greater than second." << endl;

    return 0;
}


// Program 2

#include
#include

using namespace std;

int main ()
{
int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
cin >> first;

    cout << "Second "<< setw (2) << ": ";
cin >> second;

    if (first > second)
cout << "first is greater than second." << endl;

    else
cout << "first is less than or equal to second." << endl;

    return 0;
}


// Program 3

#include
#include

using namespace std;

int main ()
{
int first, second;

    cout << "Enter two integers." << endl;

    cout << "First " << setw (3) << ": ";
cin >> first;

    cout << "Second "<< setw (2) << ": ";
cin >> second;

    if (first > second)
cout << "first is greater than second." << endl;

    else if (first < second)
cout << "first is less than second" << endl;

    else
cout << "first and second are equal." << endl;

    return 0;
}

Note: All the above three programs satisfies the condition that if first value
is greater then display the message "first is greater than second".

Question: When to use if, if-else and if-else if-else ?
Answer: It depends upon your program. The number of possibilities your program has. For example, in the above program there are three possibilities. The value could either be greater, smaller or equal. All these possibilities are covered using if-else if-else statements. Depending upon the possibilities you can add more "else if" statement before the final else statement. It is good programming to cover all the possibilities to make your program perfect.

In the next chapter we will learn about nested if statements.


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