Number Types

Other Number Types (page 60)

Various types allow for different size numbers and for more or less precision.

e.g: long double big_number;

Note: long big_integer; and long int big_integer; are equivalent.

 

Type char

C++ also has non-numeric types. The type char is intended for characters (i.e. single symbols such as a letter or a digit or a punctuation mark).

e.g: char letter = 'a', symbol = '+';

Note:

e.g.: 'a' = 97, 'b' = 98, 'A' = 65, ‘B’ = 66, etc.

e.g.: "Enter the number of candy bars:\n"

i.e.: 'a' is not the same as "a"

Consider the following:

#include <iostream.h>
int main()
{

char symbol1, symbol2, symbol3;
cout << "Enter two initials, without any periods:\n";
cin >> symbol1 >> symbol2;
cout << "The two initials are: \n";
cout << symbol1 << symbol2 << endl;
cout << "Once more with a space:\n";
symbol3 = ' ';
cout << symbol1 << symbol3 << symbol2 << endl;
cout << "That's all!\n";
return 0;
}

 

Type Compatibilities

As a general rule you cannot store a value of one type into a variable of another type. An attempt to do so is called a type mismatch.

e.g.: The following would cause a type mismatch:

int int_var;
int_var = 7.9;

However, variables of type double can be assigned int values

e.g.:

double float_var;
float_var = 16;

The above will assign float_var the value 16.0

Note: The general principle is, even if your compiler allows it, do not mix types!

 

Arithmetic Operators and Expressions

The arithmetic operators in C++ are:

+ (sum)
- (subtraction)
* (multiplication)
/ (division)

e.g.:

total_peas = pods * peas_per_pod;
count = count + 1;

If types are mixed in an expression then the compiler will promote the type. Consider the following, where oprt represents one of ‘+’, ‘-‘, ‘*’ or ‘/’ and int, double represents a variable of type int or double:

int oprt int evaluates to int
double oprt int
evaluates to double
double oprt double
evaluates to double

In other words, using double promotes the result to a double.

e.g.:
7.0 / 2.0 = 3.5 7 / 2 = 3
7.0 / 2.0 = 3.5 8.0 / 2 = 4.0
7.0 / 2 = 3.5 8 / 2 = 4

Note that integer division produces a result that has only the whole part of the number; the number has been truncated.

Other Arithmetic Operators

The mod operator (%) may be used in integer expressions to recover the remainder of the division.

e.g: 7 % 2 = 1

That is, since 2 goes into 7 three times (i.e. 7 / 2 = 3) with a remainder of 1, then 7 % 2 = 1

e.g.:
11 % 3 = 2
18 % 5 = 3
13 % 4 = 1

 

Caution: The mod operator (%) can behave differently for different implementations of C++ if used on negative numbers. Because of this it is advisable to use this operator only when you know that the operands will be positive integers.

 

Precedence

The arithmetic operators follow precedence rules that tell the compiler which operator should be first evaluated. See the following precedence hierarchy:

  1. ( )
  2. *, /, %
  3. +, -

That is, parentheses will be evaluated first followed by *, /, % and then +, -.

 

Assignment operator

Assignment operators allow us to code certain assignment statements in a compact form: Consider the following:

e.g: count = count + 2; may be coded more compactly as count += 2;

In general: variable = variable operator expression may be coded more compactly as: variable operator= expression

 

Increment and Decrement Operators

The following expressions may be written even more compactly using increment and decrement operators.

count += 1; count++;
sum -= 1; sum--;

The increment and decrement operators are unary operators; that is, they take a single argument. They are usually used on operators of type int.

e.g:

int n = 0;
cout << "n's value is: " << n << endl;
n++;
cout << "n's value is now: " << n << endl;
n--;
cout << "And now n is: " << n << endl;

Simple Flow of Control

So far the programs that we've seen have a series of statements that we execute. However, we often want to perform a sequence of statements repeatedly based on some condition. The ability to vary the order in which statements are executed is called changing the flow of control.

Logical Expressions, Comparison Operators

Before we can write code that chooses between two options, we need to talk about logical expressions. A logical expression is any expression that can be tested to see if it is true or false.

The simplest form of a logical expression is an expression that involves two variables and a comparison operator. The comparison operators are:

== (equality. Note the use of two equal signs)
!= (not equal)
< (less than)
<= (less than or equal)
> (greater than)
>= (greater than or equal)

e.g.: The following logical expressions are all false:

'a' == 'b' 3 > 7 'a' < 'A'

Note: In the last case, we see that symbols are really just small numbers

We can also put several logical expressions together using the logical operators, which are:

&& (logical AND) && is true if both its arguments are true
|| (logical OR) || is true if one of its arguments is true
! (logical NOT) ! is true if its argument is false

e.g.:

(1 < 2) && (4 > 7) ® false
(1 < 2) || (4 > 7) ® true
!(1 == 1) ® false

 

Note: Be particularly careful when writing expressions that check whether a number is within an interval. For example, the expression 1 < x < 5 is perfectly legal in C++. However, it does not evaluate to what you think! Say, for example, that x = 7. The computer first asks, "what is the truth value of 1 < x?" Since x=7, this part evaluates to true. For the computer, evaluating to true means return "1". This "1" is then compared with 5: is 1 < 5? Yes, so the computer returns true. Clearly, this is not what we meant!

A Simple Branching Mechanism

Sometimes we need to choose between one of two alternatives depending on the value of the input. Consider the following problem:

Problem: Write a program that asks the user whether he/she wants to compute the volume of a cube or a sphere. Given the answer, the program asks for either the length of the sides of the cube or the radius of a sphere and gives the correct volume.

So we need a way to determine from the input if the shape we're dealing with is a cube or a sphere. We may ask the user to input a character to tell us that the shape is a sphere or cube. Our variable for this input will be:

char shape;

Suppose that shape = 'c' means we are dealing with a cube and shape = 's' means we are dealing with a sphere. Then there is a C++ statement that will perform the branching based on this test; it is called an if-else statement

if (shape == 'c')

volume = r * r * r; else volume = 4.0/3.0 * pi * r * r * r;

The completed program is:

#include <iostream.h>
int main ()
{

char shape;
double side, radius, volume;
const double pi = 3.14159;
cout << "This program will compute the volume of a cube or a sphere.\n"
<< "Which do you prefer?\n"
<< "Enter s for sphere or c for cube: ";
cin >> shape;
if (shape == 's')
{ cout << "\nEnter the radius: ";
cin >> radius;
volume = 4.0/3.0 * pi * radius * radius * radius;
cout << "\nThe volume of a sphere with radius " << radius
<< " is " << volume << endl;
}
else
{ cout << "\nEnter the side length: ";
cin >> side;
volume = side * side * side;
cout << "\nThe volume of a cube with side length " << side
<< " is " << volume << endl;
}
cout << endl;
return 0;
}

Note the form of the if…else… statement. In general the syntax for an if-else statement is:

if (logical_expression)

Yes_statement; else No_statement;

or more generally:

if (logical_expression)
{

Yes_statement_1;
...
Yes_statement_n;
}
else
{
No_statement_1;
...
No_statement_n;
}

Nested if-else statements

Sometimes we need to distinguish between more than two cases. One way to do this is to nest if-else statements. We can do this because an if-else statement is simply another statement and thus can go inside another if-else statement.

e.g.: if we wanted to compute the volume of three shapes, say a sphere, a cube and a box, we could write

if (shape == 'c')

volume = side * side * side; else if (shape == 'b') volume = length * height * width; else volume = 4.0/3.0 * pi * radius * radius * radius;

Note that the rule for determining which else statement belong to which if is that the else belongs to the if statement closest to it.

 

Using == instead of =

When writing if-else statements with equality in the logical expression, be careful when using == instead of =.

e.g.:

if (x = 12)

do_this; else do_that;

Notice that the assignment statement will return the value 12; this is non-zero so it will be evaluated as true and do_this will always be evaluated. This is a very common mistake.

 

Omitting the else clause

If want to write an if-else statement where the else part does nothing at all, then you can use what is called an if-statement:

e.g.:

if (sales >= minimum_for_bonus)

salary = salary + bonus;

The general form is:

if (Logical_expression)

Statement;

or:

if (Logical_expression)
{


Statement_1;
…
Statement_n;

}

 
 

Simple Loop Mechanisms

Often we want to repeat some portion of code a large number of times. For example, we may want to calculate the volume for a large number of shapes or calculate the salary for all of a company's employees. Programming languages have looping constructs to allow us to do this.

The while loop.

Consider the following program:

#include <iostream.h>
int main ()
{
int count_to, count = 0;
cout << "How high do you want me to count? ";
cin >> count_to;
cout << endl;
cout << "Before the loop: count = " << count
<< " and count_to = " << count_to << "\n\n";
while (count <= count_to)
{
cout << "count = " << count
<< ", count_to = " << count_to << endl;
count++;
}
cout << "\nAfter the loop, count = " << count
<< " and count_to = " << count_to << "\n\n";

return 0;
}

The general form of a while-loop is:

while (Logical_expression)
{
Statement_1;
..
Statement_n;
}

That is, while the logical expression is true, execute the statements belonging to the while. In other words execution is accomplished thus:

  1. Evaluate the logical_expression.
  2. If it's true, execute all the statements.
  3. Until the logical_expression becomes false, continue executing the statements in the body of the while-loop.

Note:

The do while loop.

An alternative repetition construct allows the execution of the statements in the body of the loop at least once. The general form is:

do
{ Statement_1;
...
Statement_n;
} while (Logical_expression);

or

do
Statement;
while (Logical_expression);

 

e.g.: (see page 85)

#include <iostream.h>
int main()
{
char answer;
do
{
cout << "\n\tHello!\n\n";
cout << "Do you want another greeting?\n"
<< "Press y for yes, n for no,\n"
<< "and then press return: ";
cin >> answer;
} while (answer == 'y' || answer == 'Y');
cout << "\nGoodbye!\n\n";
return 0;
}

 

You will need to understand the difference between these two loops for the homework.

Consider another example of code containing a while loop. Suppose that we want to compute the sum of the number from 1 to some input value of n.

e.g.: Compute the sum from 1 to n. That is, for n=6, compute 1 + 2 + 3 + 4 + 5 + 6 = 21. A program to accomplish this follows:

#include <iostream.h>
int main ()
{
int sum = 0;
int count = 1, n;
cout << "This program will compute the sum of numbers\n"
<< "from 1 to n. Which value of n should be used? ";
cin >> n;
while (count <= n)
{
sum += count;
count++;
}
cout << "\nThe sum of the integers from 1 to " << n
<< " is " << sum << endl;
return 0;
}

 

Exercise: what gets printed for n = 3, 5?

Exercise: Can you modify the above program such that it will not proceed to compute the sum until the user has entered a positive value for n?

 

Infinite loops

Because the while (or do-while) loop keeps executing the statement(s) in its body until the logical expression is false, you need to be careful in designing your logical expressions.