Through the miracles of computer science, we will now convert your $1000 computer into a $10 calculator! Along the way, we learn how to work with arithmetic using C++.
Specifications
Type the following program into a text editor, save it as arithmetic.cpp, and then compile and run the starter program to make sure you typed it correctly.
In main(), declare two double variables named a and b, and assign them a value of 7 and 2 respectively. For instance:
double a = 7, b = 2;
Add a line of code to display the arithmetic expression (a + b) and then recompile and run the program.
cout << "a + b = " << a + b << endl;
The output when you run the program should look like this:
a + b = 9
If you do not see this output, please ask a classmate or the instructor for help.
Add three more lines of code like the previous one that computes the expressions: a - b, a * b and a / b. Compile and run your program again and make sure your program now displays the following output:
a + b = 9
a - b = 5
a * b = 14
a / b = 3.5
The order of operations matters in C++ just like it does in algebra. Multiplication and division are performed before addition and subtraction. Add the following two statements to your program:
cout << "a + b / 2 = " << a + b / 2 << endl;
cout << "(a + b) / 2 = " << (a + b) / 2 << endl;
Compile and run your program again and compare the output. Your program should now display the following output:
a + b = 9
a - b = 5
a * b = 14
a / b = 3.5
a + b / 2 = 8
(a + b) / 2 = 4.5
Note how the output of the two statements is different. You can change the order of operation using parenthesis, just like in algebra. For more information on the order of operations see section: 3.1.2: Arithmetic.
As you can see, arithmetic in C++ works much like you would expect. However, there are some mysteries when working with integer variables which we will now explore:
Truncation in integer division
Modulus (%) operator
Truncation in integer division: Change the data type of the two variables from double to int, like this:
int a = 7, b = 2;
Compile and run your program again and compare the output. Note how the result of the division operation changed. What happened to the decimal part of the result?
In programming terms, we say that the decimal part is truncated (cut short). You have to watch out for this in C++ programming or you may get unexpected results in your calculations. For more information see section: 3.1.4: Integer Division and Modulus.
Modulus (%) operator: Sometimes we want the integer remainder from an integer division. To see the integer remainder, we use the modulus (%) operator. Add the following statement to your program:
cout << "a % b = " << a % b << endl;
Compile and run your program again with this added statement. Your program should now display the following output:
a + b = 9
a - b = 5
a * b = 14
a / b = 3
a + b / 2 = 8
(a + b) / 2 = 4
a % b = 1
Mathematical functions: More complex mathematical operations require the use of a function in C++. one such function is sqrt(number) which calculates the square root of the number inside the parenthesis. Add the following statement to your program:
cout << "sqrt(a + b) = " << sqrt(a + b) << endl;
You program will not compile with this new statement because you must include a library of the mathematical functions. Add the statement: #include <cmath> to the top of your program like this:
#include <iostream>
#include <cmath> // math function library
using namespace std;
Compile and run your program again with this added statement. Your program should now compile and display the following output when run:
a + b = 9
a - b = 5
a * b = 14
a / b = 3
a + b / 2 = 8
(a + b) / 2 = 4
a % b = 1
sqrt(a + b) = 3
In this exercise we write an interactive program using strings that runs like this:
First name: Ed
Last name: Parrish
Welcome "Ed Parrish"!
Your initials: EP
Note that the underlined font shows what is typed by the user. As you work through the exercise, I suggest that you compile after each step so you know where the error is located if you make a mistake. Also, if you get stuck then ask a classmate or the instructor for help.
Specifications
Copy the following program into a text editor, save it as nameapp.cpp, and then compile and run the starter program to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
In main(), declare three string variables, firstName, lastName, fullName, like this:
Add two statements: (1) to prompt the user for the data they should enter and (2) to collect the user input and store it in the firstName variable. For instance:
cout << "First name: ";
cin >> firstName;
Add two more statements like these to collect the last name and store the input in the lastName variable.
Write a line of code to concatenate (join) the first and last names and assign them to the variable fullName like this:
Finally, add code to your program to output the fullName variable using cout:
cout << "Full name: " << fullName << "!\n";
Compile and run your program to make sure it works correctly like this:
First name: Ed
Last name: Parrish
Full name: Ed Parrish!
Some text characters are hard to print, like a double quote ("). To print these we must escape them from their special meaning by putting a backslash (\) in front of them. Put a double quote mark around the full name by changing the line printing the full name to:
You can extract parts of a string variable using the substr() function. Extract the first letter from the first and last name to create initials with the following code:
To make this type of selection we use an if...else statement
Syntax:
if (test) {
statements1
} else {
statements2
}
Where:
test: the test condition to evaluate
statementsX: the statements to execute depending on the test
For example:
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
Note that there is no test condition for the else clause
The decision on which set of statements to use depends on only one condition
Note that you could write an if-else as a pair of complementary if statements instead, like:
if (7 == guess) {
cout << "*** Correct! ***\n";
}
if (7 != guess) {
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
However, it is easier and clearer to write an if-else statement instead
For clarity, write the if and else parts on different lines than the other statements
Also, indent the other statements
You can see an example of an if-else statement in the following example
Example Program With an if-else Statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
return 0;
}
Formatting the if Statement
It is important to format the if statement professionally
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
Note how the conditional code is indented inside both the if and else portions
This lets us easily see which code is conditional and which is not
Also note the placement of curly braces
Different groups have different practices for placing curly braces for placing curly braces of if and if-else statements
In practice, you should use the style dictated by your group's policy
Or your professor's instructions
For the acceptable styles for this course see my instructions on: Curly Braces
Check Yourself
True or false: an if-else statement allows the programmer to select between two alternatives.
What is wrong with the following if-else statement? (answer)
if (7 == guess) {
msg = "*** Correct! ***";
} else (7 != guess) {
msg = "Sorry, that is not correct.";
}
What is the value of x after the following code segment? (answer)
int x = 5;
if (x > 3) {
x = x - 2;
} else {
x = x + 2;
}
True or false: always indent inside the curly braces of an if-else-statement.
In this exercise we explore the use of relational operators with if statements to create a simple game.
Specifications
Copy the following program into a text editor, save it as selection.cpp, and then compile and run the starter program to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
cout << "You entered: " << guess << endl;
// Insert new statements here
return 0;
}
We want to let the user know if they entered a correct value. For this we need to add an if statement such as:
Statements inside the curly braces only execute if the test condition in the parenthesis, (7 == guess), evaluates to true. For more information, see section: 3.3.2: Using if Statements.
Compile and run your program again and verify the output looks like:
I'm thinking of a number between 1 and 10.
Can you guess it?
Enter your guess: 7
You entered: 7
*** Correct! ***
If you rerun the program and enter a number different than 7 (like 9) then the message saying correct will NOT appear.
For a friendlier game output, we should give a message when the user enters an incorrect value. For this we need to replace our if statement with an if-else statement like:
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Please try again.\n";
}
Statements inside the curly braces of the else clause only execute if the test condition in the parenthesis, (7 == guess), evaluates to false. For more information, see section: 3.3.3: Using if-else Statements.
Compile and run your program again and verify the output looks like:
I'm thinking of a number between 1 and 10.
Can you guess it?
Enter your guess: 9
You entered: 9
Sorry, that is not correct.
Rerun and try again.
The error message should appear for any number other than the correct guess.
One problem with our program is that a user may enter numbers outside the range of 1 through 10. We can test for this condition with one or more if statements. Add this code to your program after the input statement and before the other if statements:
if (guess < 1) {
cout << "Error: guess must be >= 1\n";
return 1;
}
Checking user input is a common use of if statements. This type of code is known as input validation or input verification.
Compile and run your program again and verify the output looks like:
I'm thinking of a number between 1 and 10.
Can you guess it?
Enter your guess: 0
You entered: 0
Error: guess must be >= 1
The error message should appear for any number that is less than one.
You can nest if statements inside either the if or else clause. We can use this when we have a series of tests to make. Replace all the if and if-else statements with the following code:
if (guess < 1) {
cout << "Error: guess must be >= 1\n";
} else if (guess > 10) {
cout << "Error: guess must be <= 10\n";
} else if (guess != 7) {
cout << "Sorry, that is not correct.\n";
} else {
cout << "*** Correct! ***\n";
}
Conditions are checked in order until the one of the conditions evaluates to true. Once one condition evaluates to true, the rest of the tests are skipped. If no test condition evaluates to true then the else clause executes as the default case. For more information, see section: 3.3.6: Nested if Statements.
Compile your program and run it several times to see what message you get when you enter each of the following as a guess:
0
7
9
Review the purpose of each line of code with another student in the class. Then add a comment to the top of the file that contains the name of the person with whom you reviewed the code, like:
// Reviewed with Jane Programmer
Save your source code file so you can submit it to Blackboard as part of assignment 3.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 3.3.7: Summary.
#include <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
return 0;
}
Programming Style: Indentation of if-else-if Statements
Note the alignment of the nested statements below:
if (guess < 7) {
cout << "Your guess is too low.\n";
} else {
if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
}
The above style is WRONG
Instead, we use:
if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
This shows more clearly that we are making a single choice among multiple alternatives
Also, it prevents indentations from cascading to the right as we add more selections
Check Yourself
True or false: you can nest if statements in the if clause, the else clause, or both.
In the following code snippet, the if (guess < 7) is nested in the ________
the outer if-statement
the outer else clause
the inner if-statement
the inner else clause
if (guess != 7) {
if (guess < 7) {
cout << "Your guess is too low.\n";
} else {
cout << "Your guess is too high.\n";
}
} else {
cout << "*** Correct! ***\n";
}
In the following code snippet, the if (guess > 7) is nested in the ________
the outer if-statement
the outer else clause
the inner if-statement
the inner else clause
if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
True or false: in the above sequence of if-else statements, the final else clause belongs to the first if-statement.
True or false: if you have a series of test conditions, and only one can be correct, the following is a good structure for your code.
if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
In this exercise we see who might be a compatible pair-programming partner for the next homework assignment.
Specifications
We will count off and divide into separate groups
Within your group, exchange names and email addresses, and then write down everyone's information.
Next to each name, write the amount of programming knowledge and experience for that student using the following scale:
Absolute beginner
Some programming knowledge
Can program in another programming language
Can program in C++
Save all the information you collect in a file named students.txt.
Note that you can choose to have one person in your group record the information and email it to all the students in the group. However, every student must submit the same list of students.
Save the students.txt file so you can submit it to Blackboard as part of assignment 3.