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.
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)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * *
// Program: Grader.C
// Date:
<today's date>
// Programmer: <your name>
//
// This program converts the numeric grades to letter grades.
// Example:
// Input : Enter a Numeric Grade: 98
// Output: Numeric Grade 98 is an A.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * *
#include <iostream.h>
int main()
{
float grade;
int count = 0;
// Set up a loop to read the 10 grades
while(count < 10)
{
cout <<
"Enter a Numeric Grade:";
cin >>
grade;
cout <<
"\n";
// Go through
the grading scale table to find the letter grade
if( (grade
< 0) || (grade > 100) ){
cout << grade << " was not a reasonable input \n";
cout << "Enter the correct number \n";
}
else if(
grade >= 0 && grade < 60){
cout << grade << " is a F \n";
cout << " Work much harder \n";
}
else if(
grade >= 60 && grade < 70){
cout << grade << " is a D \n";
cout << " Work harder \n";
}
else if( grade
>= 70 && grade < 80){
cout << grade << " is a C \n";
cout << " Work more \n";
}
else if( grade
>= 80 && grade < 90){
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>
// Programmer: <your name>
//
// 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)
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.
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.
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.
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.
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.
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> * Programmer: <your name> * * 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.
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)
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Program: add.C // Date: <today's date> // Programmer: <your name> // // 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.2What happened? Does it make sense to you? Now try
15.25What happened? Strange, huh? Now let's really be bad users and enter a non-digit character. Try
15 dand then try
dWe 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.
15 3257 252456Real 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-3We 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!
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 |
$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
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
Enter a Numeric Grade: 95
Output:
95 is an A
Excellent, your hard work paid off
Input:
Do you wish to compute a letter grade? n
Output:
Thank you for using the grader program.