C++ Programming Tutorial Lesson 05: Relational and Equality Operators

In the previous lesson, it was shown that the switch statement can be used in place of a series of if, else if, and else equality tests. So, why then would anybody use the if, else if, and else statements, when they can just use the switch statement instead? Well, the if statement can test for conditions other than equality, i.e. inequalities. Let's look at an if else example using inequalities that builds off of If Else Example #2 from Lesson 02.

If Else Example #3

#include <stdlib.h>
#include <stdio.h>

int main(void) {
   int n;
   printf("Please enter a number: ");
   scanf("%d", &n);
   if (n > 1) {
      printf("n is greater than 1!\n");
   }
   else {
      printf("n is not greater than 1.\n");
   }
   system("PAUSE");
   return 0;
}
Feel free to download the If Else Example #3 source code directly. This example builds off of the If Else Example #2 source code from Lesson 02: If and Else Statements. The program's end functionality has not changed, only the method of implementation in the C++ source code. The program reads user input from the keyboard until the return key is pressed. After the user inputs a number, that value is stored into the integer variable "n". The variable "n" is then tested by an if statement. If the user inputs a number greater than 1, then "n is greater than 1!" is printed as shown below.



If instead the user inputs a number less than or equal to 1, then "n is not greater than 1." is printed as shown below.



The table below describes the if else C++ code presented in the above example.

Source Code Description & Explanation
if (n > 1) {
   printf("n is greater than 1!\n");
}
This is an if statement that tests to see if n is greater than 1. The printf() function will be run to print on the screen "n is greater than 1!" if n turns out to be greater than 1.
else {
   printf("n is not greater than 1.\n");
}
Here is the associated else statement that goes with the above if statement. It encapsulates code that will be run in the case where the condition of the if statement evaluates to false. In this case, if variable "n" is not greater than 1, then the program will run the printf() function to print out "n is not greater than 1.".


Of course, there are other conditional expressions that can be used in an if statement. The table below shows the relational and equality operators available in C++.

Relational / Equality Operator Description & Explanation
>
Greater than operator.
<
Less than operator.
>=
Greater than or equal to operator.
<=
Less than or equal to operator.
==
Equal to operator.
!=
Not equal to operator.

Copyright © 2008 Pierre Dufilie IV. All Rights Reserved.