The expression on the right is evaluated (computed) before assignment to the variable on the left
Assignment causes the value in a variable to change
Assigning Initial Values to Variables
Initial values may or may not be assigned when variables are declared:
// Not initialized when declared and have unknown values
int sum;
double amount;
// Initialized when declared with assigned values
int sum = 0;
double amount = 42 * 2;
Good programming practice: initialize variables when declared
Variable Assignment Flow
A computer is a machine with a memory that follows a set of instructions
For a computer, or anyone, to follow a set of instructions it must know two things
the actions to be taken
the order of the actions
A computer always follows a set of instructions in order from first to last
When working with variables, we must keeps this property of computers in mind
First, a variable must be declared
Next a variable must be assigned a value with an assignment statement
To change the value of a variable we can reassign a value with another assignment statement
The original value is overwritten and replaced by the new value
The equals (=) sign does not express equality as it does in math
Understanding variables and assignment is critical to being able to
program but is an easy thing to be confused about. Get over this hurdle and
programming will be far easier.
In this exercise we complete a series of dry run exercises where we step through short fragments of code. This is an important activity to reinforce your understanding of variables. The instructor will step through the first exercise with you.
Specifications
Use your paper from the last Solo Activity to record your answers, making sure to put the exercise name and your name on the paper.
Strings are a special type of variable called objects, which we will study in more detail later in the course
An object is a data type that can have functions associated with it
These functions are called member functions and are called using dot notation
The syntax for calling a member function of a string object is:
stringName.functionName(arguments)
Where:
stringName: the name of the string variable
functionName: the name of the member function
arguments: the input values, if any
Once we create a string variable, we call (invoke) its member functions
Some Commonly-Used Functions
length(): Returns the number of characters in a string
string str = "Hello";
cout << "The number of characters is " << str.length()
<< ".\n";
substr(i, n): Returns a substring of length n starting at index i
string greeting = "Hello, World!\n";
string sub = greeting.substr(0, 4);
cout << sub << endl;
The position numbers in a string start at 0. The last character is always one less than the length of the string
H
e
l
l
o
,
W
o
r
l
d
!
0
1
2
3
4
5
6
7
8
9
10
11
12
string w = greeting.substr(7, 5);
H
e
l
l
o
,
W
o
r
l
d
!
0
1
2
3
4
5
6
7
8
9
10
11
12
Example Using String Functions
Consider the problem of extracting the initials from a person's name
What would be an algorithm for solving this problem?
To implement this algorithm, we can use the string function substr()
The following program implements an algorithm for extracting the initials from a person's name
What other technique could we use to extract the initials?
Program to Create Initials
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;
int main() {
string first;
string middle;
string last;
cout << "Enter your full name (first middle last): ";
cin >> first >> middle >> last;
string initials = first.substr(0, 1)
+ middle.substr(0, 1) + last.substr(0, 1);
cout << "Your initials are " << initials << "\n";
return 0;
}
Extracting the Last Characters
Note that we can extract the last few letters of a string without knowing its length ahead of time
string word;
cout << "Enter a word: ";
cin >> word;
int lastLetter = word.length() - 1;
cout << "The last letter of the word is "
<< word.substr(lastLetter) << endl;
If we call substr() with just the starting index, it returns the trailing characters
This technique can be adjusted to extract the last few characters instead of just one character
Check Yourself
True or false: an object is a data type that can have functions associated with it.
To call a function that is part of an object, between the object name and the function name we code a ________.
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 an 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";
}
Diagram of if-else Statement Operation
Notice that there is no test condition for the else clause
if (7 == guess)
{
cout << "*** Correct! ***\n";
}
else
{
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
The decision on which set of statements to use depends on only one condition
As an option we 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
For clarity, write the if and else parts on different lines than the other statements
Also, indent the other statements
We 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
As an alternative we could format the if-else as follows:
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
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.1: Making Decisions with 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 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 << "Rerun and 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.4: 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.
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.
Submit your source code file as part of the next assignment.
#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 style 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
Optionally, we may put the opening curly brace on the same line as the test condition
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";
}
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 style for your code's structure.
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 divide into 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 coding knowledge like HTML or calculator programming
Can program satisfactorily in another programming language
Can program satisfactorily 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 Canvas as part of assignment 3.