Advertise here.

Sunday 19 August 2012

C++ Programming Tutorial Lesson #3 - Decisions


if statement

The if statement is used to test the values of variables and do something depending on the result. For example you can check if a value that the user has entered is equal to a certain value.
int age;
cout << "Enter your age: ";
cin >> age;
if (age == 18)
   cout << "\nYou are 18 years old";
In the above example you will see that we used a == instead of a = because == is used for testing equality and = is used to assign a value to a variable. If the age entered by the user equals 18 then it prints "You are 18 years old" on the screen. Here are the operators that can be used in an if statement.
==Equal
!=Not equal
>Greater than
>=Greater than or equal to
<Less than
<=Less than or equal to
If you want to put more than one command in an if statement then you must surround them with curly brackets.
int age;
cout << "Enter your age: ";
cin >> age;
if (age == 18)
{
   cout << "\nYou are ";
   cout << "\n18 years old";
}
Nested if statements are if statements that have if statements inside them.
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "\nEnter second number: ";
cin >> num2;
if (num1 == 1)
   if (num2 == 2)
      cout << "\nYou entered the right values";
The if statement actually tests the condition and then converts it to a true or a false. If the age that was entered equals 18 in our example then it converts it to true and if it is not 18 then it converts it to false. If the condition is true it runs the code immediately after the if statement. The else statement is an optional part of an if statement and the code immediately after it is run if the condition is false.
int age;
cout << "Enter your age: ";
cin >> age;
if (age >= 18)
   cout << "\nYou are an adult";
else
   cout << "\nYou are a child";
You can test 2 conditions at once using the && operator. The || operator tests if one or both of the conditions is true . The ! operator changes the condition to false if it is true and true if it is false.
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "\nEnter second number: ";
cin >> num2;
if (num1 == 1 && num2 == 2)
   cout << "\nYou entered the right values";
if (num1 == 1 || num2 == 2)
   cout << "\nOne of the values is right";
if (!(num1 == 1))
   cout << "\nYou entered the wrong value";

switch statement

The switch statement can be used to test for multiple values for the same variable. For each possible value you can run some code and you must put a break statement after each one except the last. There is a default option for when none of the values are met.
int age;
cout << "What is your age: ";
cin >> age;
switch (age)
{
   case 1: cout << "You are 1 year old";
           break;
   case 2: cout << "You are 2 years old";
           break;
   case 3: cout << "You are 3 years old";
           break;
   default: cout << "You are older than 3 years";
}