Back home Next view contents in a pop up window
Go to: if else - switch - while / for / do - <continue
The if command
The <if> statements
sets conditions. The programmer can set specific conditions using the If
statement. If these conditions are met then the program will execute the set of
instructions fallowing.
In sequentel execution the program executes one line after the other. There is only one “path” to fallow.
By using IF statements our code gets more “clever”. It can distinguish a true value from a false one. Of course the extend of this ability depends upon the programmer him self and how many possibilities he wants or can cover. The program will take the aprorpiate course of action based upon the conditions it is given and upon the input of the user. The if command makes choices based on the falacy or validity of a certain condition.
Well lets go ahead and demonstrate how an IF statement is used inside a code of block.
program1.1
int main ()
{
int num1, int num2;
cout << " Please enter 2 numbers:";
cin >> num1 >> num2;
if (num1>num2)
cout << num1 << " is larger than " << num2 <<
endl;
return 0;
}
output.
Please enter 2 numbers:5
2
5 is larger than 2
Press any key to continue
As you can see by using simply the if statement can be very limited. It lucks flexibility because there is only condition specified in the program. Programs are writen to respond into real life conditions and we know that in real life there is always more than one choice.
As you can see the code is unbalanced. Nothing we cannot fix though. There is a way to balance it by using multiple if statements and a new command called
else. These can make a program much more flexible.
Go to: if else - switch - while / for / do - <continue
Back home Next view contents in a pop up window