Conditions

Basic If Statement Syntax

The structure of an if statement is as follows:if ( TRUE ) Execute the next statement

Here is a simple example that shows the syntax:

if ( 5 < 10 ) cout<<"Five is now less than ten, that's a big surprise";

Here, we're just evaluating the statement, "is five less than ten", to see if it is true or not; with any luck, it is! If you want, you can write your own full program including iostream and put this in the main function and run it to test.

Else

Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some code instead of the code executed when the statement evaluates to true. The "else" statement effectively says that whatever code after it (whether a single line or code between brackets) is executed if the if statement is FALSE. 

It can look like this:

if ( TRUE ) {
  // Execute these statements if TRUE
}
else {
  // Execute these statements if FALSE
}

Else If

Another use of else is when there are multiple conditional statements that may all evaluate to true, yet you want only one if statement's body to execute. You can use an "else if" statement following an if statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if the if statement is false, it will then check the condition for the else if statement. If the if statement was true the else statement will not be checked. It is possible to use numerous else if statements to ensure that only one block of code is executed.

if ( <condition> ) {
  // Execute these statements if <condition> is TRUE
}
else if ( <another condition> ) {
  // Execute these statements if <another condition> is TRUE and
  // <condition> is FALSE
}


Let's look at a simple program for you to try out on your own.

#include <iostream> 

using namespace std;
  
int main()                            // Most important part of the program!
{
  int age;                            // Need a variable...
  
  cout<<"Please input your age: ";    // Asks for age
  cin>> age;                          // The input is put in age
  cin.ignore();                       // Throw away enter
  if ( age < 100 ) {                  // If the age is less than 100
     cout<<"You are pretty young!\n"; // Just to show you it works...
  }
  else if ( age == 100 ) {            // I use else just to show an example 
     cout<<"You are old\n";           // Just to show you it works...
  }
  else {
    cout<<"You are really old\n";     // Executed if no other statement is
  }
  cin.get();
}





No comments:

Post a Comment