Welcome to Lesson 7!

Learning Objectives
By the end of today's class, you should know...
  • How to do console input and output with strings.
  • What are the length() and substr() functions and how to do you call them on a string variable?
  • How do you make decisions in a computer program?
  • What is the syntax of an if statement?
  • What are the 6 relational operators and how do you use them in your if statements?

Announcements

  • Midterm 1 on Tuesday
    • Short answer and multiple choice: Study over your old quizzes and review exercises from the start of class
    • Programming portion: Know how to write all in-class activities and homework assignments
    • Will be through Thursday's lesson
  • Quiz 2 returned as usual after the break
  • Quiz 3 on Thursday
    • 3 repeat questions from Quiz 2

Review

With a partner, answer the following questions:
  • What will the following statements output to the console:
char letter1 = 67;
char letter2 = 111;
char letter3 = 108;
char punctuation = 33;
cout << letter1 << letter2 << letter2 << letter3 << punctuation;
  • Is the following statement legal? Why or why not?
cout << "39" + 2;
Now, alter the above statement to make it legal (several possible changes you could make).
  • Using string concatenation and the string variables below, declare a fourth string variable that contains the following:
Thank you for your order, Shinshin!

(Note: pay careful attention to the two punctuation marks in the previous sentence)

string grateful = "Thank you for your order";

string name = "Shinshin";

string punctuation = "!";

string message = ????????


Strings Continued

String Functions

  • Strings are a special type of variable called objects, which you will study in more detail in CIS 22B.
  • 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 function input values, if any
  • Once you create a string variable, you can 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(in): 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
    Hello,
    World!\n
    012345678910111213
  • sub = greeting.substr(7, 5);
    Hello,
    World!\n
    012345678910111213

  • Remember: length() gives you the number characters in the string

    • However: Indexing starts at 0, so the last character is always at index length()-1

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 intials from a person's name
  • What other technique could you use to extract the initials?


Activity 7.1: My Name 2 (10pts) 

  • Find a partner for pair programming.
  • Open up your name.cpp file from the last class and let's add to it.
  • Don't forget to include your partner's name in the block comment at the top of the program.
  • First, let's alter the program so that it prompts the user for his or her first and last names in a single prompt instead of two.
Please enter your first and last name:
  • Now, follow the prompt with two cin statements. One to input the first name and one to input the last name.
  • Alternately, you can write the above with a single cin statement that stores the input in the two separate first_name and last_name variables.
  • Keep the rest of the program the same. We are going to add to it.
  • Let's calculate the length of the user's first and last names and output the result to the console
cout << "The length of your first name is " << first_name.length() << " letters\n";
  • Now add a similar cout statement to display the length of the user's last name AND full name (remember the full_name variable)
  • Take a look at the sample output below. Notice that there is a mistake in the line in purple.
    • What is the cause of this mistake?
    • How can you fix this mistake so that the correct number of letters is displayed?
  • Next, let's return the user's initial's to them.
  • Let's declare a new string variable called initials that you place at the top of your program with the other variable declarations.
string initials;
  • Next, we are going to use the substr() function to extract the initials from the user's first and last names.
  • A person's initials are composed of the first letters of their first and last names.
  • Therefore, we need the letters at position 0 in the first_name and last_name variables.
initials = ??????? + ???????; //How do you call the substr() function to get the initials
  • Next, print the results to the console to display for the user.
cout << "Your initials are: " << initials << endl;

  • Submit your name.cpp program to Catalyst.
  • Remember that both partners need to submit for full credit.

The output of your program should look like this:

Hi! I want to learn your name.
Please enter your first and last name: Jennifer Parrish
Nice to meet you Jennifer Parrish!
The length of your first name is 8 letters
The length of your last name is 7 letters
The length of your full name is 16 letters //Please fix this line before you submit
Your initials are: JP


Output of Hard-to-Print Characters
  • We have been using the << operator to output strings
    string msg = "Hello Mom!";
    cout << msg << endl;
    
  • However, some characters are more difficult to output than others
  • For example, what would the compiler do with the following statement?
    cout << "Say, "Hey!"" << endl;
  • Some characters cannot be output directly in a string
  • Also, the first 32 ASCII characters are not visible on our monitors
    • Known as control characters because they control the output device
  • Even though these characters are not visible, we sometimes need to use them
    • For example, a newline character
  • We need some way to "print" invisible and hard-to-print characters

Escape Sequences

  • C++ can access control codes and hard-to-print characters using escape sequences
  • Backslash (\) directly in front of a certain character tells the compiler to escape from the normal interpretation
  • The following table has some nonprinting and hard-to-print characters:
SequenceMeaning
\aAlert (sound alert noise)
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quote
\"Double quote
\oooASCII character in octal notation
\xhhhASCII character in hexadecimal notation
  • Some examples:
    cout << '\a' << endl; // alert
    cout << '\n' << endl;
    cout << "Left \t Right" << endl;
    cout << "one\ntwo\nthree" << endl; 



Introducing If Statements

  • If statements allow us to have a decision point within a program
    • Based on the outcome of this decision, a certain set of statements may or may not execute
  • To better understand the importance of if statements, let's write a program both with and without if statements to see the difference.
  • We will start by writing the program without if statements
  • Later in the class, we will improve this program dramatically!


Operator Review - Modulus to Find Even and Odd

  • One of the principle uses of the modulus operator is determine whether a number is even or odd.
  • What is the difference between an even and odd number?
  • How can we use division to figure out if a number is even or odd?
  • Let's write a program to test a number to determine whether it is even or odd.
  • Open up CodeBlocks and create a new file called evenOrOdd.cpp.
  • At the top of your program, add a block comment with your name and section information:
/*
* Name 1
* Name 2
* Section Info
*/
  • Create your main function, and include any libraries and the standard namespace.
  • Now, between the curly braces of main declare an integer variable named testNum. Then declare a second integer variable to store the remainder. Call this variable remainder.
int testNum;
int remainder;
  • Next, let's add a cout statement to welcome the user to our program and explain its objective.
cout << "Welcome! Enter a number and I will tell you whether it is even or odd \n by giving you its remainder when I divide by two\n";
  • Run your program to verify it is working properly. If not, ask the instructor or another student for help.
  • Let's prompt the user to enter a whole number.
cout << "Please enter a whole number: ";
  • Next, we need to capture the user input and store it in the testNum variable. Add a cin statement to your program.
cin >> testNum;
  • Now, we will get a chance to try out the modulus operator! Add the following statement to your program.
remainder = testNum % 2; //pronounced testNum "mod" two
  • What does the above statement do?
  • Finally, let's print out the answer. Write a pair of cout statements like the ones below:
cout << "If your remainder is 0 then " << testNum << " is even. If your remainder is not 0, then " << testNum << " is odd." << endl;
cout << "The remainder is: " << remainder << endl;

  • Run your program and see what happens!
  • What do you think of this program? Is it a good program? Why or Why not?
  • It would be better to simply print out whether the number is even or odd.
  • Hold onto this program as we are going to improve it later in the class.

Teaching Computers to Make Decisions

  • Flow of control (or control flow) refers to the order in which programs execute instructions
  • By default, code executes sequentially: one statement after another from top to bottom in a function like main()
  • Sometimes we want to change this sequential flow
  • One change we can make is a using a selection statement, also known as a conditional statement
  • A selection statement contains code that executes statements only if a test condition evaluates to true
  • For example:
    if (7 == guess) {
        cout << "*** Correct! ***" << endl;
    }
    
  • In the above, the (7 == guess) is a test that the 7 is equal to the value of guess

Video: Bill Gates explains If statements


The Value of a Relationship

  • Before we discuss if-statements we need to talk about relationships
  • A relationship is a way to compare two numbers or other entities
  • For example:

  • The above example is called a relational expression
  • A relational expression uses a relational operator to compare two entities like numbers or variables
  • We have used relational operators in algebra, and C++ relationships are similar
  • The following table shows the relational operators of C++

Relational Operators

Math Name C++ Examples   Result Notes
= Equal to == 5 == 10
2 == 2
false
true
Do not confuse with = which is assignment.
Not equal to != 5 != 10
2 != 2
true
false
The ! is like the line that "crosses through" the equal sign.
< Less than < 5 < 10
5 < 5
5 < 2
true
false
false

Less than or equal to <= 5 <= 10
5 <= 5
5 <= 2
true
true
false
Be careful not to write =<. Code the symbols in the order people normally say them.
> Greater than > 5 > 10
5 > 5
5 > 2
false
false
true

Greater than or equal to >= 5 >= 10
5 >= 5
5 >= 2
false
true
true
Be careful not to write =>. Code the symbols in the order people normally say them.

Using if Statements

  • The simplest control-flow statement is an if statement
  • We use an if statement to select whether or not to execute a set of statements
  • An if statement has two parts: a test and a body
  • The body can have zero or more statements
  • The statements in the body execute if and only if the test evaluates to true
  • If the test condition evaluates to false, the computer skips the code
  • Syntax:
    if (test) {
       statement1
       statement2
       ...
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementX: the statements to execute depending on the test


Flow Chart for an "if statement"

If Statement Flowchart
  • For example:
    if (7 == guess) {
        cout << "*** Correct! ***" << endl;
    }
    
  • For clarity:
    • Write the if on a different line than the executed block
    • Indent statements 3-4 spaces within the curly braces
  • You can see an example of an if statement in the following example


Example Program With an if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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! ***" << endl;
    }
    return 0;
}

About those Curly Braces

  • Technically, the if statement affects only the single statement that follows
  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the body
  • Curly braces are not always required, but the best practice is to always include them


Incorrect curly braces:

int main()
{
    int x = 3;
    if(x < 5)
    {
    cout << x; //NO!! You need to indent twice. Statement inside 2 sets of curly braces.
    }
}


Correct curly braces:


int main()
{
    int x = 3;
    if(x < 5)
    {
        cout << x; //Yes!! Indent twice. Statement inside 2 sets of curly braces
    }
}

Activity 7.2: Improving Our Even/Odd Program (10pts)

  • Remember our evenOdd.cpp from earlier in class?
  • We used modulus to divide a number by two and get its remainder
  • However, we weren't able to determine whether the number was even or odd.
  • We had to leave that decision up to the user.
  • Now let's improve our program by adding two if statements.
  • Below the line where you calculate the remainder, add the following if statement to determine whether the number is even, and, if so, report your result to the user.
if (remainder == 0 ) {
    cout << testNum << " is even.\n";
}
  • Below that if statement, add a second if statement to determine whether the number is odd, and, if so, report your result to the user.
if (remainder != 0) {
    cout << testNum << " is odd.\n";
}
  • Submit your program to Catalyst when you are finished. Both partners need to submit for full credit.



Wrap Up

With a partner, answer the following questions:
  • Write a cout statement to print the following message to the console:  Sure! I'll do it. <tab> I "love" boring, repetitive tasks!
  • Find the mistake in the statements below. What will happen when the code is run?
number = 2;
if (number = 7)
    cout << number;


Upcoming Assignments
  • Assignment 7 due Thursday
  • Lab 5 due Friday at midnight
  • Quiz 3 on Thursday
  • Midterm 1 on Tuesday
~See You Thursday!~