# I/O, Variables, Arithmetic Expressions

The goals of this lab are to:
1. learn to use if ... else, if ... else if ... else, while loop
2. learn about variables of types int and double
3. learn about the C++ arithmetic operators

You will need to be logged on to the cs machine to do this lab, so get logged in now. (You will then have both a Netscape window and a telnet window open.)

Now change to your 1440 subdirectory and create a new directory for this lab. Call it "lab3". After you create the lab3 subdirectory, go to that directory. The commands to use to do this entire paragraph are:

```% cd 1440         (This is to change directory)
% mkdir lab3      (This is to make a directory call lab3)
% cd lab3         (This is to change to directory lab3)```
This is the longest lab you have done so far and you will not be able to finish it during the lab hour. Please use the lab hour to work on it today and then finish it on your own.

## A Simple C++ Program

In the previous lab, we used different variables.  We also had an example on if ... else.  Here we talk about if ... else again and we will introduce while loop too.

Suppose you want to write a program that asks users to input the grades for 10 students and in return tells the user the letter grade for each student.  Following is the scheme used in grading.

Less than 0 ---  Not a reasonable grade
Larger than or equal to 0 but less than 60  --- Grade F
Larger than or equal to 60 but less than 70  --- Grade D
Larger than or equal to 70 but less than 80  --- Grade C
Larger than or equal to 80 but less than 90  --- Grade B
Larger than or equal 90 but less than or equal 100 --- Grade A
Larger than 100 --- Not a reasonable grade

Let's first talk about the method and the algorithm that we wish to use.  There are three main things we need to do here.

Step 1) Declare variable(s)  (Let's think about variables that we may need and their types)
List them here:

Step 2) We need to set up a mechanism to ask for 10 grades.  Every time a new grade is entered, the program displays the letter grade, and once the count reached 10, stops the program.

Step 3) This step goes within Step (2), set up a mechanism so that every time that a grade is entered, the grading scale is checked to find the letter grade.

Program (1)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Date:           <today's date>
//
// Example:
// Input :      Enter a Numeric Grade: 98
// Output:    Numeric Grade 98 is an A.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
#include <iostream.h>
int main()
{
int count = 0;

while(count < 10)
{
cout << "Enter a Numeric Grade:";
cout << "\n";

// Go through the grading scale table to find the letter grade
cout << grade << " was not a reasonable input \n";
cout << "Enter the correct number \n";
}
cout << grade << " is a F \n";
cout << " Work much harder \n";
}
cout << grade << " is a D \n";
cout << " Work harder \n";
}
cout << grade << " is a C \n";
cout << " Work more \n";
}
cout << grade << " is a B \n";
cout << " Good Grade \n";
}
else {
cout << grade << " is an A \n";
cout << " Excellent, your hard work paid off  \n";
}
count++;   //increment the count
}//enf of while loop
return 0;
}

Answer these questions before you go to the next program.
1) Considering the above code, what changes do you need to make so that the code works for any number of students?

2) In the above code, when a wrong grade was entered, we count it.  How can you fix the problem so that you do count the unreasonable grades?

Program (2)
Here is a small C++ program that prints the odd and even numbers between an initial number to another number in two different columns. Note that the extension ".C" is used rather than ".c" this is common (and recommended), but not required.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Program:        EveOdd.C
// Date:           <today's date>
//
// This program separate Even and Odd numbers that.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
#include <iostream.h>
int main()
{
int start;    // This is the starting value of the sequence.
int skip;    // This is step size (values that we skip from one number to the next.
int count;  // This is number of values we wish to print in the sequence
int current; // This is a temporary variable

cout << "This program prints out a sequence of numbers\n"
<< "and places each number in a column labeled EVEN if\n"
<< "it is an even number and a column ODD if it is an odd\n"
<< "number.  You are to specify three values:\n"
<< "(1) a starting value for the first number to print\n"
<< "(2) a 'skip' value for the difference between two\n"
<< "    successive numbers, and\n"
<< "(3) a count for the number of items to be printed.\n"
<< "After you have specified these values, the table of\n"
<< "data will be printed\n\n";

cout << "Enter the starting value: ";
cin >> start;

cout << "\nEnter the skip value: ";
cin >> skip;

cout << "\nEnter the number of items to be printed: ";
cin >> count;

cout << "\nEVEN\tODD\n";

current = start;
while (count > 0)
{
if ((current%2)==1)  //To write the odd numbers on a different column
cout << "\t";
cout << current << endl;
count -=1;
current += skip;
}
cout << "\nThanks for visiting this program.\n";
return 0;
}

Save the above program in a file called "EveOdd.C" on the cs machine in your lab3 subdirectory. Compile and run the program.  At the prompt type:
% g++ EveOdd.C   (To cmpile the program)
% a.out   (To execute the program)

At the very top of EveOdd.C program there is a comment called the program header comment. The header contains the name of the file containing the program, the date the program was written, the name of the programmer, and a description of the program. I want you to put such a header at the top of every program you write for this class. We'll say more about comments later in this lab.

#### The main Function

C++ programs are written in pieces called functions. A function has a type, a name, a list of arguments, and a body. Every program must have one function whose name is "main". Our EveOdd.C program has only one function (main) and so will most of the programs we write at the beginning of our class. The line
`int main (void)`
says that the type of value produced by the main function is an integer, that the function's name is main, and that its argument list is empty. Press the space bar and look at the last line of the program
`return 0;`
That zero is the value being produced by main. Zero is an integer and that's why the type of value produced by main is an int. Always start your main function with the line "int main (void)" and make the last line of main be "return 0;". Advanced programmers may change some of those things, but we will not. Note that the author of our text uses "int main( )", omitting the word "void". I prefer the use of void.

#### Comment Styles

The body of any function in C++ is enclosed in curly braces. After the opening brace of main there are three variable declarations. To the right of each one is a C++ comment. A C++ comment begins with a double slash (//) and goes to the end of the line. An older style of comments in C begins with a slash star (/*) and ends with a star slash (*/). You may see this older style in some programs. The older style C comments may run over several lines or they may take up only part of one line, not necessarily the end of a line. You may mix and mingle these comment styles as you like in your programs, but I prefer that you use the newer style (//). The important thing is that you use comments. Every important variable (and for now consider them all important) should have a comment beside its declaration explaining its purpose in your program.

#### Variable Declarations

A variable declaration statement in C++ consists of a data type and a list of identifiers separated by commas. All statements in C++ end with a semicolon. In our EveOdd.C program we have used only integer type variables shown below:

int start;    // This is the starting value of the sequence.
int skip;    // This is step size (values that we skip from one number to the next.
int count;  // This is number of values we wish to print in the sequence
int current; // This is a temporary variable

Note that we could use one line to declare all these variables:
int start, skip, count, current;

Compare the declarations above to the ones in the EveOdd.C program. Above there is only one variable declaration statement containing three variable identifiers in its identifier list. Use whichever style you prefer.

It is very important that we choose variable names so that they have meanings corresponding to their use in the program.

#### Instructions to the User

Every interactive program should contain some instructions to the user of the program. Running an interactive program is something like having a conversation with a computer. Users need to understand what their part of the conversation is expected to consist of. In the EveOdd.C program the following lines tell the user what the program does and how the user is supposed to respond to the program's questions.

cout << "This program prints out a sequence of numbers\n"
<< "and places each number in a column labeled EVEN if\n"
<< "it is an even number and a column ODD if it is an odd\n"
<< "number.  You are to specify three values:\n"
<< "(1) a starting value for the first number to print\n"
<< "(2) a 'skip' value for the difference between two\n"
<< "    successive numbers, and\n"
<< "(3) a count for the number of items to be printed.\n"
<< "After you have specified these values, the table of\n"
<< "data will be printed\n\n";

Note that all the above statements are displayed using only one cout.  These statements may appear
on different lines depending on the "\n" used on each line. These lines can be written in our code as:

cout << "This program prints out a sequence of numbers\n";
cout << "and places each number in a column labeled EVEN if\n";
cout << "it is an even number and a column ODD if it is an odd\n";
cout << "number.  You are to specify three values:\n";
cout << "(1) a starting value for the first number to print\n";
cout << "(2) a 'skip' value for the difference between two\n";
cout << "    successive numbers, and\n";
cout << "(3) a count for the number of items to be printed.\n";
cout << "After you have specified these values, the table of\n";
cout << "data will be printed\n\n";

Note that now we have to have a ";" at the end of each line.

#### Prompts for Input

In the EveOdd.C program, we ask the user to input some information and they place the values typed by the user into the program's variables.  It is very important that we ask the user what type information to enter.  As you may remember in the first lab we had a program sample.C that did not have a comment asking you to enter two values for the input.  Some of you were thinking that the program did not run.  In the EveOdd.C program we have the following lines:

cout << "Enter the starting value: ";
cin >> start;

cout << "\nEnter the skip value: ";
cin >> skip;

cout << "\nEnter the number of items to be printed: ";
cin >> count;

After we prompt a user to enter some data, we have to store the data into a variable. That's what the cin lines in the program are doing. The first one stores the user's entry into the variable called start, and the second one stores input in the variable called skip.

#### Assignment Statement

The line below is used to subtract one from count:
count -=1;  (This is the same as count = count -1)
The following line add one to current:
current += skip;    (This is the same as: current = current + skip;)
Such lines are called assignment statements. An assignment statement has the form
`   variable = expression;`
The equal sign in C++ is called the assignment operator. When C++ comes across an assignment statement, it evaluates the expression to the right of the assignment operator and places the result into the variable on the left of the assignment operator.

## The cout Output Stream

You can use cout in many ways. You can send the value of a variable to the screen like this:

cout << "\t";  (This print a Tab space)
cout << current << endl;  (This print the value of current and move to a new line)

You can also print a string to the screen:

`  cout << "\nThanks for visiting this program.\n";`
Suppose you want to print the values of two variables with only a space between them. Do it like this:
`   cout << value1 << " " << value2;`
Don't leave it up to the compiler to format your output for you. If lines are too long they will probably wrap around to the next line on the screen. Usually they will be broken after the 80th character even if it is right in the middle of a word. (The exact behavior depends on things like your terminal emulator -- you might see something different.)

Suppose you write a program that must output dollar amounts. Dollar amounts should have two digits after the decimal point. Two dollars and fifty cents should print as 2.50, not as 2.5. Yet our cs machine defaults to printing only the digits required to get the value correct. If you want two digits after the decimal point, then put the following lines in your program before any of your dollar amounts are output:

```   cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);```
The first line tells C++ not to use scientific notation. The second line tells C++ to always show the decimal point and the third one tells it to put two digits after the decimal point. You only have to put these lines once in your program, but if you need to change the settings you can do so. See your text for other formatting flags that can be used with cout.setf.

Here is another program to copy to the cs machine. Call this one "ducks.C".
Program (3)

```/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Program:        ducks.C
* Date:           <today's date>
*
* This program multiplies ducks.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <iostream.h>

int main (void)
{
int ducks;           // number of ducks input by user
int total_ducks;     // number of ducks next year
double duck_worth;   // value of one duck

cout << "\n\nDuck Multiplier\n\n"
<< "You will be asked by this program to supply"
<< "the number of ducks you own."
<< "It is assumed that half of your ducks are "
<< "females and half are males and they pair off."
<< "The program will tell you how many"
<< "ducks you will have next year if every pair of"
<< "ducks you own now produces five baby ducks.";

cout << "After you type a number, press the Enter key.";
cout << "How many ducks do you own? ";
cin >> ducks;
cout << "What is the value of one duck? \$";
cin >> duck_worth;

total_ducks = ducks + ducks / 2 * 5;

cout << "\nNext year you will have" << total_ducks << "ducks";
cout << "worth" << (total_ducks * duck_worth);
cout << "Thank you for using Duck Multiplier!";

return 0;
}```
The program ducks.C contains formatting errors. Compile and run the program and you'll see what a mess the output is. Pull the program back into the editor (say "pico ducks.C") and insert some newlines, spaces, and a dollar sign into the output strings (see the next paragraph). Also fix the precision of real numbers so that dollar amounts look right.

After you fix the formatting errors, save the program and recompile it. Run it again to see if you've improved the formatting. Keep working until the output of the program looks nice on the screen. Fixing this program is part of your homework. You do not need to turn in a printout of ducks.C. As long as it is located in your 1440/lab3 subdirectory, I'll be able to run it and see how you've fixed up its output.

## The cin Input Stream

The input stream cin is used to get values for variables from the user. When you use cin, the arrows point rightward.
```   cout << "Enter your weight: ";
cin >> weight;```
When a program reaches a cin statement it pauses and waits for a value to be entered. It waits until the user presses the Enter key before it reads what the user has typed. This gives the user a chance to use backspace to correct any input errors.

You can get values for two or more different variables with one cin.

```   cout << "Enter your height in inches and your weight: ";
cin >> height >> weight;```
When the user is entering the values, he or she must separate them with white space, i.e., spaces, tabs, or newlines. It doesn't matter how many white space characters are used to separate the values.

Copy the following program to the cs machine and call it "add.C".
Program (4)

```//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Date:           <today's date>
//
// This program adds two values input by the user.
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
#include <iostream.h>

int main (void)
{
int num1, num2;      // entered by the user
int sum;             // sum of num1 and num2

cout << "Enter two integers: ";
cin >> num1 >> num2;

sum = num1 + num2;

cout << num1 << " + " << num2 << " = " << sum << endl;
return 0;
}```
Compile the program and run it several times. The first time you are asked to input two integers, put a space between them. The next time try a tab, then try pressing Enter between the two integers. All of these work fine.

Now let's be bad users and not follow directions. We were told to enter integers, but let's enter a real number and then an integer. Try entering

`15 25.2`
What happened? Does it make sense to you? Now try
`15.25`
What happened? Strange, huh? Now let's really be bad users and enter a non-digit character. Try
`15 d`
and then try
`d`
We will not have time in this lab to explore the reasons for the behavior of add.C when the user does not follow directions. For now, we will be satisfied if our programs work when the user follows directions.

## Type Compatibility

The three data types we will use most often when we declare variables are
• int (an integer)
• double (a real number)
• char (a character)
Not only variables have types in C++. So do constants and other arithmetic expressions. Integer constants do not have decimal points. They also do not have commas. They look like this:
```15
3257
252456```
Real constants are considered to be of type double. They may have a decimal point or they may be written in C++'s version of scientific notation. Here are some double constants:
```0.026
19.75
1257.033
18.2e-3```
We won't use the last form very often. The fourth real number above is 18.2 times 10 to the -3 power, or .0182. Note that both integers and reals may be positive or negative.

Arithmetic expressions have types, too. If all the constants and variables in an expression are of type integer, then the expression is also of type integer. But if any constant or variable in an expression is of type float or double, then the expression is of type double. Here are two expressions of type integer and two of type double:

```6 - 3 * 2 % 4
17 * (2485 - 301)
14 - 12 * 1.5
8.2 / (3 + 2 - 0.5)```
We may safely assign an integer constant to a double variable because C++ will convert the constant to a double. Saying the following places 32.0 into the variable called freezing:
```   double freezing;     // temp at which water freezes

freezing = 32;```
If we assign a constant of type double to a variable of type integer, the fractional part of the constant is lost. Saying the following will assign 0 to the variable called half:
```   int half;

half = 0.5;```
Clearly, half should have been declared to be a double. What will be the value of answer after the following?
```   int answer;

answer = 0.5 * 2.5;  // In math, 0.5 * 2.5 = 1.25.```
The expression 0.5 * 2.5 is of type double, but since the variable answer is an integer its value will be 1 after the assignment statement above.

Do you think that 1/2 and 0.5 are interchangeable in a C++ program? They are not. Since 1 and 2 are both integers, the / will do integer division and thus 1/2 is equal to 0!

## Arithmetic Operators

The arithmetic operators in C++ are shown in the following table. The operators in the top row have higher precedence than those in the bottom row. We'll say more about precedence shortly.
 Multiply, divide, modulo *, /, % Add, subtract +, -

The modulo operator is defined for positive integers only. It produces the remainder after division. All the other operators are defined for both integers and reals. The division operator, however, behaves differently on integers than it does on reals. If both of its operands are integers, then / does integer division. If either operand is a float or double, then / does real division. Here are some examples of the use of modulo and division operators:
 Expression Value Comment 6 % 2 0 0 is the remainder after you divide 6 by 2 7 % 2 1 1 is the remainder after you divide 7 by 2 18 % 5 3 3 is the remainder after dividing 18 by 5 5 % 18 5 5 is the remainder after dividing 5 by 18 6 / 3 2 this is integer division 7 / 3 2 this is integer division so the .5 is lost 7 / 3.0 2.5 this is real division 7.0 / 3 2.5 this is real division

We mentioned above that multiply, divide, and modulo have higher precedence than add and subtract. This means that in evaluating an expression that contains more than one operator, C++ makes one pass from left to right evaluating multiplies, divides, and mods. It then makes another pass from left to right evaluating adds and subtracts. We can change this default behavior by enclosing parts of expressions in parentheses. This forces C++ to evaluate the parenthesized portion first. Within the parentheses, C++ follows its rules of precedence.

Here are some examples of expressions and the value C++ would obtain after evaluating them:
 Expression Value 3 + 2 * 5 13 (3 + 2) * 5 25 18 / 4 * 2 8 18 / (4 * 2) 2 25 % 6 - 2 * 3 -5 25 % (6 - 2) * 3 3 8 * 10 - 7 73 8 * (10 - 7) 24

#### Making change

You can use integer division and mod in a coordinated way to make change.
```\$2.73 = 273 pennies
273 / 25 = the number of quarters in \$2.73
273 % 25 = the number of pennies left over after removing the quarters```

## Homework - Due by Midnight Tuesday September 11.

1) Modify the EveOdd.C program so that it takes the following as its input but it generates similar output.
The inputs are :
int start;    // This is the starting value of the sequence.
int skip;    // This is step size (values that we skip from one number to the next.
int end;  // This is the ending value of the sequence

Note that, this time instead of counting some numbers we will end the sequence once we reach the end value.

Example:
start = 1
skip = 3
end = 14

Even       Odd
1
4
7
10
13
Since the next number 13+3 = 16 is larger than 14 we stop the program at this point. Turn in a hard copy of your program next lab (next Wednesday). Submit an electronic copy by the due date:

% ~rt/submit1440_103  lab3    lab31.C

2) Modify Program (1) in this lab, to do two things differently.
1) The new code (lab32.C) uses do...while instead of while ... loop, and
2) The program asks users whether they want to enter a new grade, if the answer is Y or y, it computes the letter grade.  If the answer is N or n, it ends the program. This way you do not need to keep track of how many students and you let the user decide the termination of the code by entering n or N.

Turn in a hard copy of your program (lab32.C) next lab (next Wednesday). Submit an electronic copy by the due date.

% ~rt/submit1440_103  lab3    file.C

Example:
Input:
Do you wish to compute a letter grade? y