cstutoringcenter.com logo





E-mail:    Password:    

Become a premier member today to gain access to exclusive member benefits! Just $10.00 to join FOR LIFE!




NY Web Consulting


<< Tutorial 2
Tutorial 4 >>
C++ tutorial index

C++ Decisions

Tutorial 3


Register or log in today to rate this tutorial!
Current ranking: / 5 stars with 31 votes.


Our YouTube video for this tutorial:

Tutorial Topics:



Topics
Logical Operators
If statements
While statements
Examples
Example 1
Example 2
Example 3
Example 4
Example 5
Comments
Comments

Logical Operators

Here is a useful chart of some of the logical operators of C++. The chart will be brought into account with the program examples:

C++ Symbol Name Definition
&& Logical And ALL inputs must be true in order for the statement to be true
|| Logical Or 1 or more inputs must be true in order for the statement to be true
! Logical Not Will negate any logical statement (True becomes False and False becomes True)
== Logical Equals Will detect if BOTH side of the statement have the same truth value
!= Logical Not Equal Will detect if BOTH side of the statement DO NOT have the same truth value
> Strictly greater than Will detect if one side of the statement is STRICTLY bigger than the other
>= Greater than or equal to Will detect if one side of the statement is bigger than or equal to the other
< Strictly less than Will detect if one side of the statement is STRICTLY less than the other
<= Less than or equal to Will detect if one side of the statement is less than or equal to the other
% Modulo Division The remainder (or residue) when two numbers are divided. As an example, 10 % 3 is 1
++ Incrementer The value of a variable is incremented by 1. This can be short for (using a variable x): x = x + 1; This can also be used as either a "pre" or "post" incrementer.
-- Decrementer The value of a variable is decremented by 1. This can be short for (using a variable x): x = x - 1; This can also be used as either a "pre" or "post" decrementer.

Using this table, each of the above is called an operator. In C++, there are hundreds of definitions for operators. Some that we have already seen are[ =, >>, <<).

Each operator, similar to mathematics, preforms its own set of actions. So in math, the plus sign will add two numbers. In C++, it is the same. So each above operator has a predefined set of instructions or actions when used.

The below example shows how to use some of the increment operators. The comments explain part of the program.

Example 1:
Incrementing/Decrementing

Download source code here (Right click - Save Target As...)

The objective of this program is to show how to use the increment/decrement operators.

//  decides whether input for age is stupid
#include <iostream>
using namespace std;

int main(){
   int num = 0;
   
   //allows user to enter an integer
   cout << "Give me any number: ";
   cin >> num;

   //once entered, use the operators
   
   //"post" increment:
   cout << num++ << endl;

   //"pre" increment:
   cout << ++num << endl;

   //"post" decrement:
   cout << num-- << endl;

   //"pre" decrement:
   cout << --num << endl;

   return 0;
}

Assume with the above program that the user enters the number 5. The output is as follows:

Give me a number: 5
5
7
7
5

Lets see why the output is this way. First, the value of the variable num is 5. The first operator that is used on the variable is the "post" increment operator. This uses the variable first (for output) THEN increments it. So what the output is is 5 BUT THE VARIABLE HOLDS THE VALUE 6.

Next, the variable is "pre" incremented so it is incremented FIRST, THEN outputted. The output is 7 since it was already incremented.

The same applies for the decrementing.

If statements

In all of programming, decisions need to be made. Most can be made with what is called an if statement.

Whether you realize it or not, we use if statements in our daily lives everyday. Say that if it is raining outside, we will stay inside and watch a movie. There are plenty of examples, too numerous to go into them all.

Below is what an if statement would look like:

if( condition(s) ){
   //code for the if
}

where condition(s) is a logical true/false statement.

There may also be an if / else if statement. This kind of structure will check for a condition initially and if and only if that initial condition is FALSE, the else if clause is checked. If the else if clause is FALSE and there are no other statements to check, nothing will happen. There is no limit to how many else if clauses you may have. Here is what that may look like:

if( condition(s) ){
   //code for the if
}else if( condition(s) ){
   //code for the else if
}
.
 .
  .
}else if( condition(s) ){
   //code for the else if
}

To keep a programs logic short and sweet, a more simplistic way of doing things is to make an if / else block. Here, the else clause is a general condition and will handle actions when the initial if is FALSE. Here is what that would look like:

if( condition(s) ){
   //code for the if
}else{
   //code for the else
}

Notice that there is only 1 else clause and that it does not contain any conditions.

In short, the rule about if statements is that the condition(s) inside the if MUST BE TRUE in order for the if statement to work (or be "tripped" as some say). If it is FALSE, the else or else if statements are checked.

Example 2:
Stupid inputs

Download source code here (Right click - Save Target As...)

Below is a program that will detect a stupid input by a user. The objective is to detect whether or not the age that is requested is positive, since a person cannot be a negative age.

//  decides whether input for age is stupid
#include <iostream>
using namespace std;

int main(){
   int age;
   cout << "What is your age: ";
   cin >> age;

   if (age < 0) {
       cout << "Idiot." << endl;
       exit(1);
   }
   else cout << "You passed." << endl;
   return 0;
}

Example 3:
Even / Odd detection

Download source code here (Right click - Save Target As...)

The objective of this program is to detect whether or not a user has entered an odd or even number. This requires a test of modulo division. The definition of an even number is when it's remainder when divided by 2 is 0.

//  checks for an even number
#include <iostream>
using namespace std;

int main(){
   int num;
   cout << "Give me any number: ";
   cin >> num;

   if (num % 2 == 0) {
       cout << "It's even!" << endl;
   }else{
       cout << "It's odd!" << endl;
   }

   return 0;
}

In this program, say the user enters the number 4. We know it is even so the program will print out the message "It's even!" and terminate. If the number entered was 5, it would print out "It's odd!" and terminate. The initial if statement will check for the even number while the else will handle the odd.

While statements

Let's say with example 2, we wanted to give the user a strict rule of entering only an even number. It is simple as it would be an if statement but not quite. Say that a program requires a certain input (a correct one at that) that even with an if statement and some code, only gives the user 1 more chance to enter that data correctly. If the user still doesn't do it right, the program will not run correctly.

This problem can be solved using what's called a while statement. By it definition, while a certain logical condition is TRUE, do something. Example 3 shows a program requiring an even number.

Example 4:
Even numbers

Download source code here (Right click - Save Target As...)

The objective of this program is make a user enter a positive even number. It will use a while statement as some users may try to "break the rules" of this program.

//  checks repeatadly for an even number using while
#include <iostream>
using namespace std;

int main(){
   int num;
   cout << "Give me any positive even number: ";
   cin >> num;

   while(num % 2 == 1){
      cout << "Not even, try again: ";
      cin >> num;
   }

   cout << "Right!  You entered: " << num << endl;

   return 0;
}

In this program, say the user enters the number 5. Because of the while statement logic being true, it will ask the user to enter the number until they enter an even number.

Now let's say that the user enters the number 4. The while statement WILL NOT WORK since the condition is initially false. Remember the rule of if and while statements that the condition MUST BE TRUE or else it will not work. Since the entered number is correct, the ending message is displayed and the program terminates.

Example 5:
Coins and change

Download source code here (Right click - Save Target As...)

The objective of this program is to correctly determine the number of coins to be given out as change. This again requires a test of modulo division. The program will be explained later:

//  program courtesy of Dr. Alex Ryba, Queens College
//  decides correct change for given entry
#include <iostream>
using namespace std;

int main(){
   int x;
   cout << "How much change is needed? ";
   cin >> x;

   // quarters, dimes, nickles and cents wanted:
   int q, d, n, c;

   q = x / 25;
   x = x % 25;
   d = x / 10;
   x = x % 10;
   n = x / 5;
   c = x % 5;

   cout << "Quarters: " << q << "\nDimes: " << d
        << "\nNickels: " << n << "\nCents: " << c
        << endl;
   return 0;

}

Say that the user needs 90 cents worth of change. The first thing that the program needs to do is calculate the quarters. Here, 90 divided by 25 is 3. Note that the int DOES NOT handle decimals and only looks at whole numbers. It then stores 3 into the variable q.

The, the new value of x is calculated by placing the remainder when 90 is divided by 25, here it is 15.

Now, the dimes are calculated by taking 15 (since that is currently x) and dividing it by 10 which produces 1 (again, the int ignores the decimals). Now, the new value of x is 15 mod 10 which is 5.

The program will then calculate the nickels and cents accordingly. The final result will be: q = 3, d = 1, n = 1, c = 0


<< Tutorial 2
Tutorial 4 >>
C++ tutorial index


Comments

Please feel free to leave a comment! Just keep it peaceful is all we ask and try to be as informative as possible to help others. Spam will NOT be tolerated!

Reviewing C++

Reviewing C++

Print: $39.99

Reviewing Java

Reviewing Java

Print: $34.99