Tag Archive for if else structure

C++ Tutorial #5 — Simple if conditional, if else structure, variable output


Topics discussed: If statements, simple if syntax, variable output, if else structure.

Source Code available here..


If statements
If statements are the backbone of simple decision making in object oriented programming languages. The if statement checks one or more statements for a boolean(true or false) value. Their basic structure is as follows


if (condition){
    //if the above is true
}

//optional

else{ //or elseif(condition){
     //if the "if" statement above was not true
}

Below are some examples of these statements:

If statement examples:


// Examples
// Example 1

int i=9;
if (i == 9){
     cout<< "This condition is true";
} //this statement should be true

in the above example the if statement compares (using the == operator) the integer value of i, to the number 9. In that case the statement if (i==9) is true, thus the code inside the brackets is executed.


// Example 2

int i=9;
if ( i != 8){
     cout << "This condition is also true"; 
}

In the example above we see that the contents of i (which is 9) is being compared to 8 with != which means “does not equal” or “is not equal to”. Since 9 does not equal 8, the contents of the if statement will execute.


//Example 3
int i=9;
if (i == 8){
     cout << "The if statement here won't be displayed"; 
}
else{
     cout << "This will be displayed";
}


In the final above example we are checking to see if the value of i (9) is equal to 8, in this case it is no. So everything from the bracket after the conditional until the subsequent closing bracket is skipped over. Once the word else is seen, it will execute anything in the brackets after the else, unless there are further if statements to be evaluated inside the if.

Boolean operators
Below is a brief listing of the boolean operators used in testing conditionals and what each of them mean, there will be specific usage examples of each later on in the series.

  • == : Is equal to
  • != : Is not equal to
  • > : Is greater than
  • >= : Is greater than or equal to
  • < : Is less than
  • <= : Is less than or equal to
  • ! : Is not
  • && : And
  • || : Or