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. The if command is a single selection structure.

  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 

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

return 0;

}

output.  

Please enter 2 numbers:5
2
5 is larger than 2
Press any key to continue

  In this program we were asked to enter a number for variable num1 and num2. We have told the program that     if (num1>num2)     to     cout << num1 << "  is larger than  " <<  num2  <<  endl;

 

There are two ways this program will work: a) We enter a number that meets the condition if (num1>num2) in which case it will complete the instructions fallowing the if statement. b) We will enter a number that is equal or less than 10 in which case the program will simply end. This will happen because we have not told the program what to do in case num1 is equal and/or less than num2

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

1
Hosted by www.Geocities.ws

1