Back home Next view contents in a pop up window
Skip to: Go to: if - switch - while / for / do - continue
The
else command.
The else command can be used by it self or in combination with the the if command. The if else command is a double selection structure. It gives ut the oppurtinity to specify more than one condition. The program has the chance to select between operations according to which condition is set by the programer and if that condition is met.
#include <iostream.h>
int main ()
{
int num1, int num2;
cout << " Please enter 2 numbers:";
cin >> num1 >> num2;
if (num1>num2)
cout << num1 << " is larger than " << num2 << endl;
if (num1<num2)
cout << num1 << " is smaller than " << num2 << endl;
else
cout << num1 << " and " << num2 << " are equal
." << endl;
return 0;
}
outputs of 1.2
| output when num1<num2.
Please enter 2 numbers:2 3 2 is smaller than 3 Press any key to continue |
----------------------------------------
|
Please enter 2 numbers:10 10 10 and 10 are equal . Press any key to continue |
----------------------------------------//font>
As you can see from the code we can simply insert more than one if statements. Needless to say that on each new if statement you have to set the condition and the instructions on what the program has to do if the condition is met.
You can view this command as the “left over handler”. In program 1.2 there can be only three possible statements. The first two if statements covered the two possible outcomes. If the first two conditions are not met, then the program will go to the else statement and execute. This does not mean though that the program knows that num1 is equal to num2. This simply means that the program did not find the first two conditions true and instead of ending, it went to the else statement and executed the command fallowing it.
A more sufficient way to write this program would be:
#include <iostream.h>
int main ()
{
int num1, int num2;
cout << " Please enter 2 numbers:";
cin >> num1 >> num2;
if (num1>num2)
cout << num1 << " is larger than " << num2 << endl;
if (num1<num2)
cout << num1 << " is smaller than " << num2 << endl;
if (num1==num2)
cout << num1 << " and " << num2 << " are equal .";
else
cout << " wrong input." << endl;
return 0;
}
output of 1.3
|
Please enter 2 numbers:45 Press any key to continue |
Program 1.3
does the same thing as program 1.2 with one small difference. After we Input a
value for the variable num1 the program will check to see if any of the
conditions are met. If if (num1>num2)
or if (num1<num2) or if
(num1==num2) are not met the program will go to the else and execute the instruction fallowing it. This is a good technique to
help the program avoid errors and plus it is easy to maintain. In addition now
the program will know that num1 and num2 are equal if that is
case. Now the program is not in a state of ignorance. This is always usefull
because in more complex programs it helps you to avoid errors or/and find find
them. ALWAYS TRY (WHEN POSSIBLE) TO KEEP YOUR PROGRAM "INFORMED". THE MORE IT KNOWS
THE MORE THE COMPILER WILL HELP YOU FIND ERRORS (IF ANY) IN YOUR PROGRAM!
If there are too many possibilities were you just cant cover them all, then its ok to leave the program in a "state of ignorance".
In the program above, I entered 45 for the first variable and the letter p for the second variable. What happened here is that the program was told to expect an integer for num2 but instead it recieved a letter. It translated the letter into a number and went on to do the comparison. The program though knew that something was not correct and in addition went to the else line and outputed wrong input. In order to give the program the ability to fully recognize a wrong input (like in this case) we would need to place a special function outside the main.
I created this example just to give you an idea on how to use the else command as an error handler. Trust me, on the later topics, you will need this.
Now lets see a more complex program using the if and else commands and lets also introduce what we call error handler.
program 1.4
#include <iostream.h>
int main ()
{
float const Ancient_Libra=1.391,
Old_German=0.9072,
japanese=121;
float pounds, pfund, monnme, podium;
char select;
cout << " Convert your weight from pounds to:\n"; //
line 9
cout << " Ancient Roman Libras -press r -\n";
cout << " Old German pfunds -press g -\n";
cout << " Japanese monnme -press j -\n";
// line 12
cin >> select;
// line 13
if (select == 'r' || select == 'R')
{
cout << " Enter your weight in pounds: ";
cin >> pounds;
podium=Ancient_Libra*pounds;
cout << " Your weight in Ancient Libras is: " << podium << endl;
}
else if (select == 'g' || select == 'G' )
// line 21
{
cout << " enter your weight in pounds: ";
cin >> pounds;
pfund=Old_German*pounds;
cout << " Your weight in old German pfunds is: " << pounds << endl;
}
else if (select == 'j' || select ==
'J')
// line 28
{
cout << " Enter your weight in pounds: ";
cin >> pounds;
monnme=japanese*pounds;
cout << " Your weight in Japanese monnme is: " << monnme << endl;
}
else
cout << " You have entered an invalid letter\n";
// line 36
return 0;
}
few outputs from 1.4
|
Convert your weight from pounds to: please make a selection: q
|
Convert your weight from pounds to: enter your weight in pounds: 220
|
Program 1.4 asks to enter our weight in pounds. It
goes on and asks in what weight system we want to convert our weight. This
program has what we call multiple
cases.
As you can see here we are combining the if and else statement. When dealing with multiple cases it is better to do this way because it makes the program easier to maintain and we can use the else command as an error handler. But lets examine this program from top to bottom.
From line 9 to 12 we have told to the user what keys (r-g-j) correspond to each metric system. Remember though this doesn’t mean that we have set these letters as variables.
In line 13 we have told the program to expect a value cin >> select; , but not what kind of value in specific. Now we have to set the proper conditions.
In line 11 we tell the program that if (select == 'r' || select == 'R') it should convert pounds into Ancient Libras. Pay attention how we phrased that statement. if (select == 'r' || select == 'R') . We need to phrase the r letter like ‘r’ otherwise we will have an error. I also included 'R' to prevent an error from happening in case the user enter a capital R. Remember C++ is case sensitive. The || stands for the OR operator. So if (select == 'r' || select == 'R') translates into: If select is equal to r OR select is equal to R.
Now the program expects the letter r in
order to execute the block of code fallowing that particular if .
On line 21 the condition if(select==’g’) will be met and the
block of code will be executed only if we enter the letter g. On line 28
the condition if(select==’j’) will be met and the block of code will
be executed only if enter j.
Each block of code will be executed only and only if the conditions we set are met. The program will compare the letter we entered and see if it corresponds to the conditions we have set and will execute accordinaly. What happens though if we don’t enter one of the three letters (r-g-j)? If we enter a letter other than the ones that we specified then the program will go to line 36 and execute.
The else statement on line 36 is our error handler. Now you just saw the benefits of using the if/else combination. Utilize this method in your programming style since it is very important. You must realize though that on line 30 the program does not know we have entered an invalid key. The program simply knows that the key we entered did not correspond to any of the letters in the if else conditions. What we have done with the error handler is to prevent the program from canceling out or even worst we have prevented the program by continuing running based on an eronious input. This of course would produce a result that will not be valid.
Notice also the opening and closing brackets for each if/if else statement. When we have more than one line of code after each conditional statement we need to include each block of code of that statement into brackets. Otherwise when we will compile the program we will have errors. To get a more clear picture of what I am talking about compare program 1.3 and program 1.4. In program 1.3 we had only one line of code after each statement so brackets are not needed. In program 1.4 we have more than one lines of code after each statement and brackets are needed.
There is a better way of writing programs with multiple cases by using the switch command.
Lets now go and take a look at the switch selection structure.
Go to: Go to: if - switch - while / for / do - continue
view contents in a pop up window