Computing Concepts with C++ Essentials
Laboratory Notebook
Chapter 2 - Fundamental Data Types

Cay S. Horstmann
Geof Pawlicki

Your name:
Your email address:
Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.

Lab Objectives

To gain experience with

R1. Number Types

Numbers are essential to computing. In C++ there are two fundamental numeric types: integers and floating point numbers. Integers have no decimal part, whereas floating point numbers do. Variables of either type are represented by user specified names. Space in the computer's memory is associated with the name so that the variable acts like a container for the numeric data.

Declaring a variable reserves space in memory and associates a specified name with it. When a variable is declared, it contains whatever value is leftover from the previous use of the memory space. Initializing a variable sets it to a specific value. If no specific value is known, it's a good idea to initialize new variable to zero in order to avoid having it contain a random value.

type name = value;
int identifier; /* Variable declared but not initialized */
int identifier = 0; /* Variable declared and initialized to zero */
float identifier = value; /* Variable declared and initialized to another value*/

Are the following ints and floats properly declared and/or initialized? If not, supply a correction.

float 3.14159;
float = 314.00
int PI_times = 314.00;
int_value 314;
float working_value 314;

When declaring a variable, take a moment to consider by what name it will be known. A valid name is made up of characters from the set:

abcdefghijklmnopqrstuvwxyz lower case letters
0123456789 digits
_ the underscore character

The only limitation is that a variable name can't begin with a digit. Of course, the name must be unique. Neither you nor the compiler would be able to distinguish between variables with the same name. For some simple cases, using single letters like i, j, k is enough, but as programs grow larger this becomes less informative. Like the name for a product or service, a variable name should do two things:

1) Be unique
2) Express the purpose

Mostly, this will happen if the name selected is descriptive enough to tell a human reader how a variable is being used, for example count_messages, user_preference, customer_name

Complete the following table of (bad) variable names, better names and descriptions.

Bad Variable Name Variable Renamed Description
float current profit;
integer counter
float %above;
float dollars earned in May

R2. Constants

Like variables, any numeric constants used by your program should also have informative names, for example: const int FLASH_POINT_PAPER = 451; or const int BOILING_POINT_WATER = 212. Using named constants transform statements such as int y = 451 - x + 212 into the more intelligible int y = FLASH_POINT_PAPER - x + BOILING_POINT_WATER.

Give definitions for each of the constant descriptions listed below

const definition Description
Number of days in a week
Number of weeks in a year
Minimum wage per hour

P1. Comments

Even carefully named variables are rarely sufficient to fully convey the operation of a program. They do not, for example, provide an explanation of a future feature that could be implemented because of how something is done now, or leave a detailed description of how a variable is computed. You can however place any additional information necessary in a comment. Comments are plain text for humans to read. They are separated from the machine readable code needed by the compiler by either of:

/* say whatever you want in here, between the slash-asterisk boundaries
   the compiler will ignore it
   . . .         


// say what ever you want from the double slashes to the end of the line . . .
// the compiler will ignore it
// . . .

From both design and documentation perspectives, it is a good idea to get in the habit of commenting your code as early as possible. For example, provide a brief description of what the program coins.cpp from Section 2.2 does.

#include "iostream.h"
#include "stdlib.h"

int main()
/* your work goes here--use // or /* as appropriate */
{  cout << "How many pennies do you have? ";
   int pennies;
   cin >> pennies;
   cout << "How many nickels do you have? ";
   int nickels;
   cin >> nickels;

   cout << "How many dimes do you have? ";
   int dimes;
   cin >> dimes;

   cout << "How many quarters do you have? ";
   int quarters;
   cin >> quarters;
   float total = pennies * 0.01 + nickels * 0.05
       + dimes * 0.10 + quarters * 0.25;
       /* total value of the coins */
   cout << "Total value = " << total << "\n";
   return EXIT_SUCCESS;

Now, extend coins.cpp to prompt for and accept the number of Susan B. Anthony $1 coins, placing the finished code here. Add a comment to show when you modified the code, and what change you made.

R3. Input and Output

C++ defines two standard streams that can be used for text mode input and output, respectively cin and cout. Operator >> and << are used to direct input and output to and from the stream.

In coins.cpp, for example, you used cin >> pennies; to get user input. The expression cout << "Total value = "; displays the message "Total value =". It was followed by << total , which places the contents of the variable total into the cout stream.

Items in the input stream are separated by white space - spaces, tabs and newlines. For example, two numbers may be input as

3   4



If there is an error, the stream goes into a failed state rather than plodding ahead with bad data. For example, if the user has typed


(with a letter l) instead of


then the stream fails when trying to read a number.

Do the following lines of input data work properly? Why or why not?

User Input: 24 25 26

int first, second, third;
cin >> first >> second >> third;
User Input: 24.4 25.5 26

float fourth, fifth, sixth;
cin >> fourth >> fifth >> sixth;
User Input: 24.4 25.5 26.6

int seventh, eighth, ninth;
cin >> seventh >> eighth >> ninth;
User Input: 23.4 24.5

float tenth, eleventh, twelfth;
cin >> tenth >> eleventh >> twelfth;

R4. Assignment

There are several primary ways to modify the contents of a variable in C++.

During compilation, values on both sides of the >> and = operators are checked to insure that the data received matches the data type of the variable to which it will be assigned. Are the right and left hand sides of the assigment operators of compatible type in the following statements?

int y = 3;
float y; int x = x * (6 + y);
float y = "3";

What error does your compiler give in these cases?:

Statement Error message
a + 2 = 3;
M_PI = 3;

Because a variable of any given type represents a fixed amount of space in memory, there is a limit to how large a value it can store.

Size limitations are particularly evident with integers. On some computers, integers can only be about 32,000, on others, they can go up to a little more than 2,000,000. What is the largest value your compiler will accept for a signed integer? What is the most negative allowed value?

Floating point numbers don't round to the nearest integer value. Can you explain the values your compiler assigns to f and g in:

float f = pow(10.0, 20.0) - 53;
float g = f;
g = g - 53;
cout << f << "\n" << g << "\n";

R5. Arithmetic

Recalling what you've learned about integers and floating point values, what value is assigned to x by each of the following?

int x = 6 + 3;
int x = 6 - 3;
int x = 6 * 3;
int x = 6 / 3;
int x = 7 / 3;
float x = 7 / 3;
int x = 999 / 1000;
float x = 999.0 / 1000.0;
int x = 999 / 1000.00;
float x = pow(2,10);

Translate the following algebraic expressions into C++ :

y = x + 1/2
y = x2 + 2x + 1
y = ---


Many programs manipulate not just numbers but text. C++ stores text in string variables. They are declared and assigned in a manner similar to a numeric variable, and the sequence may have any length, including being uninitialized or having 0 characters. For example,

string name = "Joan Wilson";

assigns the 11 characters enclosed in quotes to the variable name.

 string temp = name; 

assigns the content of variable name to variable temp

cout << name; 

displays the contents of variable name on the standard output stream.

R6. Concatenation


   string first_name = "John";
   string last_name = "Smith";
   string name;

What value will name contain after

      name = first_name + last_name;

How could the preceding be revised to give a better result?

R7. Substrings

The primary difference between strings and numeric data types is that any portion of the characters in a string variable is itself a string variable. Such a portion is called a substring.

What will be the resulting substring in the following examples? If invalid, give a corrected version of the call to substr.

string name = "John Smith"
string first_name = name.substr(0, 4);
string name = "John Smith"
string last_name = name.substr(5, 6);
string name = "Jane Smith"
string name2 =
name.substr(1, 11);

P2. Extracting Substrings

Using substr and concatenation, give a program containing a sequence of commands that will extract characters from input_string = "The quick brown fox jumped over the lazy sleeping dog" to make output_string = "Tempus fugit". Then print output_string.

P3. Converting from numbers to strings

The number3 and the string "3" are completely different values. But for various purposes, numeric types sometimes need to be used as strings, and for calculation purposes, strings that contain numbers need to be used as numbers.

The conversion functions stringvalue(x), intvalue(s), floatvalue(s) are provided as auxiliary functions. Write a program to convert the contents of the variables int year, float increase and string what into a string sentence of the form "In ..., there was a net increase of ...% in ...". Then print the contents of that string variable.

For example, if the user of this sample program provides the following input:

year: 1996
increase: 14.7
what: net sales

then set sentence to:

"In 1996, there was a 14.7% increase in net sales."

P4. Converting from strings to numbers

The function get_line(cin) read a single input line. Write a program that uses get_line along with the string functions substr and floatvalue to parse two lines of user input containing a statement of the form DEPOSIT amount followed by WITHDRAW amount. For example, the input

DEPOSIT 525.40

will result in account being assigned the value 355.40 . (Since you don't yet know how to implement decisions, you can rely on the fact that the first line is always a deposit and the second line is always a withdrawal.) Then print the output: BALANCE IS 355.40.

Don't forget to send your answers when you're finished.