To gain experience with
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 */ |
| double | identifier | = value; | /* Variable declared and initialized to another value*/ |
Are the following integers and floating point numbers properly declared and/or initialized? If not, supply a correction.
| int 3; | |
| double; | |
| int = 19; | |
| float myten =10.23; | |
| double_sum =2.2; | |
| int that_value 212; |
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 | upper case letters |
| 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 This will also help you when you are trying to maintain the program later on, since a descriptive name will assist you in remembering exactly what a variable is used for.
Complete the following table of (bad) variable names, better names and descriptions.
| Bad Variable Name | Variable Renamed | Description |
| int monthly income | ||
| integer counter | ||
| double %sales; | ||
| double sales of bikes |
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 |
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 . . . */
or
// say what ever you want from the double slashes to the end of the line . . . // the compiler will ignore it // . . .
COINS
#include <iostream>
using namespace std;
int main()
{
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;
double total = pennies * 0.01 + nickels * 0.05
+ dimes * 0.10 + quarters * 0.25;
/* total value of the coins */
cout << "Total value = " << total << "\n";
return 0;
}
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
or
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
l0
(with a letter l) instead of
10
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 double 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 double tenth, eleventh, twelfth; cin >> tenth >> eleventh >> twelfth;
Write a program which includes each of the above declarations and cin statements. When you run the program, supply the suggested values for each variable to see what happens. You will need to make a separate directory from within the lab2 directory. Do not use the coins directory from before.
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 assignment operators of compatible type in the following statements?
| int d = 4; | |
| double a; int c = c * (6 + a); | |
| double q = "3"; |
What error does your compiler give in these cases?:
| Statement | Error message |
| int kq; kq + 2 = 19; | |
| int xz = 20++; |
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,000. What is the largest value your compiler will accept for a signed integer? What is the most negative allowed value?
Recalling what you've learned about integers and floating point values, what value is assigned by each of the following?
| int a = 9 + 2; | |
| int b = 9 - 2; | |
| int c = 5 * 2; | |
| int d = 8 / 4; | |
| int e = 9 / 4; | |
| double f = 9 / 4; | |
| int g = 222 / 300; | |
| double h = 222.0 / 300.0; | |
| int i = 222 / 300.00; | |
| double j = pow(3,6); |
Write a program that checks your answers for each of the above statements. Your program should output each statement followed by the result of the statement. For example, the beginning of the program should look like the following:
#includeusing namespace std; int main() { int a = 9 + 2; cout << "int a = 9 + 2; --> a = " << a << "\n"; int b = 9 - 2; cout << "int b = 9 - 2; --> b = " << b << "\n";
And the beginning of the output would then look like...
int a = 9 + 2; --> a = 11 int b = 9 - 2; --> b = 7
Translate the following algebraic expressions into C++ :
| y = x + 3/4 - 2 | |
| y = x2 + 6x - 2 | |
x y = --- 1-x |
Again, write a program that checks your C++ statements. Have the user enter values for x. Check your program for run-time errors by computing by hand what the result should be and comparing this with your program's actual results.
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 = "Jane Doe";
assigns the 8 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.
Given:
string first_name = "Kenneth"; string last_name = "Cole"; string name;
What value will name contain after
name = first_name + last_name;
Write a program to check your answer. Then rewrite the program to give a better result.
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 = "Robert Sourchie"; string first_name = name.substr(2, 4); |
|
| string name = "Robert Sourchie"; string last_name = name.substr(7, 4); |
|
| string name = "Pamela Sourchie"; string name2 = name.substr(1, 11); |
Using substr and concatenation, write a program containing a sequence of commands that will extract characters from input_string = "Four score and seven years ago our fathers" to make output_string = "carefree and no tears". Then print output_string.
The function getline(cin, s) reads a single input line into the string s. Write a program that uses getline to read input of the following exact form:
FNAME first name MNAME middle name LNAME last name ADDRESS a street name and house number CITY a city name STATE a state abbreviation ZIP a zip code ORDER_DATE the date of the order TOTAL_ITEMS number of items (an integer) ORDER_TOTAL total amount of order (type double) SHIP_DATE date of shipment
Then print out the top part of a shipment manifest in the following form:
John Q. Public 11801 Jones Valley Ct. Pleasant Hills, MN 66504 =====================================================================x Order Date: 10-Oct-2001 Total Items: 10 Order Total: $100.00 Ship Date: 20-Oct-2001
You use the setprecision, setw and fixed manipulators defined in the <iomanip> header to control the formatting of numbers. Write a program that calculates the interest and principal payments on a simple loan. Your program should query the user for a percentage annual interest rate, an initial balance and monthly payment, then print out the following table:
Month Balance Interest Payment 1 $10050.00 $100.50 $500.00 2 $ 9650.50 $ 96.51 $500.00 3 $ 9247.01 $ 92.47 $500.00 4 $ 8839.48 $ 88.39 $500.00
Use setw to set each column width, and use fixed and setprecision to properly show dollars and cents.