If…else Statements

If…else statements, referred to as "conditional statements", allow programs to make decisions based on a certain set of conditions. They involve making a decision between two alternatives. The program will then choose the alternative that matches the conditions set by the user, and executes the statement or statements that follow from that choice. You can create a very simple if statement, or group together a series of nested statements. The value of a conditional statement is always either TRUE or FALSE.

The key components of a conditional statement are known as relational operators. These are an integral part of what makes an if…else statement functional.

The most commonly used relational operators are listed below:

&&and>greater than
||or<less than
!not>=greater than or equal to
= =equal to<=less than or equal to
!=not equal to  

Let’s look at a simple program using just one if statement.

#include <iostream>
using namespace std;
int main ()
   int x = 2;
   if (x == 2)
      x = x + 3;
   cout << x;

Here, we set our variable x to have the value of 2. This matches the condition that we stated in our if clause; thus, the expression x == 2 is TRUE. So, 3 is added to the value of x, which gives the new value of 5.

This next example uses a single if/else statement.

#include <iostream>
using namespace std;
main ()
   float x = 2.5;
   float y;

   if (x != 0) 
      y = 10 / x;
      cout << y << endl;
      cout << "Dividing by zero is not allowed.";

Here, x has a value of 2.5, which is different than 0; hence, our if clause is TRUE, and 4 will be printed for the value of y. If x had been 0, then the if clause would be FALSE, and the program will execute the statement within the else clause instead.

I have included one final example that uses a nested if/else statement. See if you can follow through the program for yourself.

This page has been accessed     times.
Last modified: Sunday, 25-Mar-2012 17:18:27 CST
Copyright 2000 Department of Computer Science, University of Regina.

 CS Dept Home Page

Teaching Material