Synfire's Guide to C++

4. Conditional Statements

A conditional statement allows you to perform an action based on current conditions of the program. Here is an example:

ifstatement.cpp
#include <iostream.h>

unsigned int Age;

int main()
{
    cout << "How old are you?" << endl << endl;
    cout << "I am ";
    cin >> Age;
    if (Age < 21)
    {
      cout << "Sorry son your too young!" << endl;
    }
    else if (Age > 21)
    {
      cout << "Sorry about that sir, We just have to check!" << endl;
      cout << "Here ya go, Drink up!" << endl;
    }
    else
    {
      cout << "Just barely, huh! My mistake!" << endl;
    }
    return 0;
}
Okay here we go, first we create a variable called Age, then we ask the user, as though the program is a bartender, to input there. Once the user inputs the age, the Age variable test to see if they are of legal drinking age in the US. Depending upon the value of Age the program prints out a line of text. Go ahead copy and compile this. When your computer asks your age test out different ages, it works.

Now you may be wondering, where the hell did these > and < than things come from and why haven't you explained them yet? Well the answer is, because I haven't gotten to that yet!

SO SHUT UP AND GIVE ME A DAMN SECOND!

erm sorry. So now we come to the operators used in testing values.

You have already learned about the assignment operator '=' from messing with variables, so here are some more, these just test two values and return either true or false.

Greater than - Checks to see if the left is greater than the right
>   4 > 5 // True
    9 > 3 // False

Less than - Checks to see if the left is less than the right
<   4 < 5 // True
    9 < 3 // False

Greater than or Equal - Checks to see if the left is 
greater than or equal to the right
<=  4 <= 5 // True
    9 <= 3 // False
    2 <= 2 // True

Less than or Equal - Checks to see if the left is 
less than or equal to the right
>=  4 >= 5 // False
    9 >= 3 // True
    2 >= 2 // True

Equal - Checks to see if the two are equal to each other
==  4 == 5 // False
    9 == 3 // False
    2 == 2 // True
(this is two equal signs don't confuse it with '=' a single)

Not Equal - Checks to see if the two are not equal
!=  4 != 5 // True
    9 != 3 // True
    2 != 2 // False
Operators

! - The Not operator makes things evaluate opposite to the truth.

&& - The AND operator makes the program evaluate two conditions, but for the expression to be true they BOTH have to return true!

|| - The OR operator makes the program evaluate two conditions, if EITHER are true then the expression returns true

Summary
In this section you learned about changing a programs movement depending on the current conditions, you also learned how to test multiple expressions for falsehood.

< < < Lesson 3: Variable Basics | Lesson 5: Program Control > > >



Fancy learning C, C++ or Perl? The have a look in our tutorials section.