What We Will Cover
Continuations
What will be output after the following C++ statements have executed?
int count = 1;
while (count <= 3) {
cout << count << " ";
count++;
}
1 2
1 2 3
2 3
1 2 3 4
Homework Questions?
Homework Discussion Questions (Thursday)
- Can you suggest a different algorithm than shown in exercise P4.6?
^ top
6.1: More About Strings and Characters
Learner Outcomes
At the end of the lesson the student will be able to:
- Iterate through a string and extract each character
- Convert characters to digits
- Use string functions
|
^ top
6.1.1: Strings Versus Characters
- Remember that a string is a series of characters enclosed in double quotes such as:
"Hello" "b" "3.14159" "$3.95" "My name is Ed"
- We can store text in a variable of type
string, like:
string firstName; // declaration
firstName = "Edward"; // assignment
string lastName = "Parrish"; // declaration + assignment
cout << firstName << " " << lastName << endl;
- On the other hand, a character is a single letter, number or special symbol
- We enclose characters in a single quote, rather than a double quote, like:
'a' 'b' 'Z' '3' 'q' '$' '*'
- Also, you can store a a single character using a variable of type
char, such as:
char letterA = 'A';
char letterB = 'B';
- Each character is stored as a number, using its ASCII Table
- By declaring a
char variable or using single quotes, C++ knows to treat the number as a character
- Thus, when you print a character, you see a letter rather than a number:
char letter = 'A';
cout << letter << 'B' << endl;
- As you can see, a string is made up of characters and characters are numerical codes
- We can use this information to work with characters and strings
^ top
6.1.2: Indexing a String
^ top
6.1.3: Iterating Strings
Using unsigned
^ top
6.1.4: Converting Characters to Digits
- Recall that a character is stored by the computer as a number using its ASCII code
- In the ASCII table, notice the ASCII codes for the digit characters:
| Decimal | char |
| 48 | '0' |
| 49 | '1' |
| 50 | '2' |
| 51 | '3' |
| 52 | '4' |
| 53 | '5' |
| 54 | '6' |
| 55 | '7' |
| 56 | '8' |
| 57 | '9' |
- Since each character is a numerical code, we can convert a
char to a number
- For example:
char digit = '9';
int num = digit - 48;
cout << num << endl;
num = num * 4 + 6;
cout << num << endl;
- Since a string is a series of characters, and each character is number, we can convert a string to anumber as well
- For example:
string str = "123";
char ch0 = str[0];
char ch1 = str[1];
char ch2 = str[2];
int digit1 = ch0 - 48;
int digit2 = ch1 - 48;
int digit3 = ch2 - 48;
int num = digit1 * 100 + digit2 * 10 + digit3;
cout << num << endl;
- Since the algorithm for converting a string to a number is repetitious, we can use a loop
- We will explore converting strings to numbers in the next exercise
^ top
Exercise 6.1
In this exercise we convert strings to character and characters to numbers.
Specifications
- Copy the following program into a text editor, save it as
stringdigits.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;
}
- Add code to get user input into an
string variable named str. When you run the program after adding this code, the output should look like:
Enter an integer number: 12345
Note that the underlined numbers above shows what the user enters. Also, we do NOT want to allow spaces in user input. For more information see section 3.2.2: String Variables and Simple I/O.
- After the input statement, add another line of code that displays the length of the
string variable str. When you run the program after adding this code, the output should look like:
Enter an integer number: 12345
The number of characters is 5.
Note that the number 5 in the above example may change depending on the number entered. For more information see section 6.1.3: String Functions.
- After the other statements, add the following code to convert the first character of the string to a number:
char ch = str[0];
int digit = ch - 48;
cout << "Digit: " << digit << endl;
- Enclose the above code that converts a character to a string inside a loop that iterates through each character, as explained in section 6.1.3: Iterating Strings. IMPORTANT: change the number 0 in square brackets to the index variable of the counting loop. When finished, your code should look like:

- In this step, we add the code to display the sum of the digits as follows:
- Before the loop, declare a variable named sum and initialize the variable to 0.
int sum = 0;
- At the end of the loop, before the closing curly brace (
}), add the statement:
sum = sum + digit;
- After the closing curly brace of the loop, add a statement to display the sum of the digits, like:
cout << "The sum of the digits is: "
<< sum << endl;
- Compile and run your modified program to make sure you made the changes correctly. When you run the program, the output should look like:
Enter an integer number: 12345
The number of characters is 5.
Digit: 1
Digit: 2
Digit: 3
Digit: 4
Digit: 5
The sum of the digits is: 15
Debug any problems you see and ask your neighbor or the instructor for help as needed.
- In this step, we add the code to convert the digits into a single number as follows:
- At the top of the file, include the cmath library:
#include <cmath>
- Before the loop, declare a variable named
num and initialize the variable to 0:
int num = 0;
- At the end of the loop, before the closing curly brace (
}), add the statements:
int exp = str.length() - (int) i - 1;
num = num + (int) (digit * pow(10.0, exp));
- After the closing curly brace of the loop, add a statement to display the entire number :
cout << "The number is: " << num << endl;
- Compile and run your modified program to make sure you made the changes correctly. When you run the program, the output should look like:
Enter an integer number: 12345
The number of characters is 5.
Digit: 1
Digit: 2
Digit: 3
Digit: 4
Digit: 5
The sum of the digits is: 15
The number is: 12345
Debug any problems you see and ask your neighbor or the instructor for help as needed.
- Submit your program source code to Blackboard as part of assignment 6.
Program that Processes Strings with Loops
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 6.1.7: Summary.
^ top
6.1.5: String Input With Spaces
Input Using getline()
- To read an entire line we use function
getline()
- Syntax:
getline(cin, stringVariable);
- Where:
- stringVariable: the name of the string variable
- For example:
string line;
cout << "Enter a line of input:\n";
getline(cin, line);
cout << line << "END OF OUTPUT\n";
- Note that
getline() stops reading when it encounters a '\n'
The Problem with Newlines
- When you press the Enter key, a newline character (
'\n') is inserted as part of the input
- The newline character can cause problems when you mix
cin >> with getline()
- Recall that
cin >> s1:
- Skips whitespace
- Reads non-whitespace characters into the variable
- Stops reading when whitespace is found
- Since whitespace includes newline characters, using
cin >> will leave a newline character in the input stream
- However,
getline() just stops reading when it first finds a newline character
- This can lead to mysterious results in code like the following:
cout << "Enter your age: ";
int age;
cin >> age;
cout << "Enter your full name: ";
string name;
getline(cin, name);
cout << "Your age: " << age << endl
<< "Your full name: " << name << endl;
- To get around this problem you can use
cin >> ws just before getline()
cin >> ws; // clear whitespace from buffer
- You can see how to use this fix in the following example
Example Using cin >> ws
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
cout << "Enter your age: ";
int age;
cin >> age;
cout << "Enter your full name: ";
string name;
cin >> ws; // clear whitespace from buffer
getline(cin, name);
cout << "Your age: " << age << endl
<< "Your full name: " << name << endl;
}
|
^ top
6.1.6: Processing Text Input
- Sometimes we need to read input as words and sometimes as lines
- To input a sequence of words, use the loop:
string word;
while (cin >> word) {
// process word
}
cin >> word is the same test as cin.good() (see lesson 5.3.6)
- To process input one line at a time, use the
getline() function
string line;
while (getline(cin, line)) {
// process line
}
getline(cin, line) returns true as long as there is input
- The following example processes text input by counting words
- When reading input in the
while test, you need to close the stream using:
- Ctrl + Z in Windows
- Ctrl + D in UNIX or Max OS X
- Closing the stream acts as a sentinel value for the loop
- When the stream fails the loop exits
Example Program that Reverses a Sentence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter a phrase followed by the Enter"
<< " key and Ctrl-Z/D.\n";
string reversed;
string word;
while (cin >> word) {
reversed = word + " " + reversed;
}
cout << reversed << endl;
return 0;
}
|
Redirection of Input and Output
^ top
6.1.7: Summary
- A string is a series of characters enclosed in double quotes
- We can store text in a variable of type
string, like:
string s1 = "Hello Mom!";
- A character is a single letter, number or special symbol
- We can store a a single character using a variable of type
char, such as:
char letterA = 'A';
char letterB = 'B';
- Each character is stored as a number, using its ASCII code
- Strings are stored in a character sequence starting at 0 (zero)

- You can access individual characters of a
string using []
- Strings are a special type of variable called objects, just like a Turtle
- Because a string is an object, it has member functions
- We can iterate through a string using a loop and the
length() member function:
string s = "abcdef";
for (unsigned i = 0; i < s.length(); i++) {
cout << "Char[" << i << "]: " << s.at(i) << endl;
}
- Also, we looked at how to convert a
char to a number
- Since each character has a numerical code, we can convert a
char to a number
- For example:
char digit = '9';
int num = digit - 48;
cout << num << endl;
- Since a string is a series of characters, and each character is number, we can convert a string to anumber as well
- We looked at an example of converting strings to numbers as well
- To read an entire line, you need to use the
getline() function:
getline(cin, line);
- Sometimes
cin >> can leave a '\n' character in the input stream
- To get around this problem you can use
cin >> ws before getline()
cin >> ws; // clear whitespace from buffer
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- String are enclosed in double quotes. What type of quote marks enclose characters? (6.1.1)
- The characters of a string variable can be accessed using what brackets? (6.1.2)
- The leftmost character of a string is accessed using which index number? (6.1.2)
- To print the following string vertically down the page, what code do you write? (6.1.3)
string str = "Hi mom!";
- To convert the following
char variable to a number, what code do you write? (6.1.4)
char ch = '7';
- What is the value of the expression: 'd' - 'a' + 'A'? (6.1.4)
- To convert the following string variable to a number, what code do you write? (6.1.4)
string str = "7";
- How many words can you enter with the following code? (6.1.5)
string something;
cout << "Enter something: ";
cin >> something;
cout << "You entered: " << something << endl;
- How can you change the previous code to read a string that includes spaces? (6.1.5)
- What code can you use to clear newlines and other whitespace from the input stream? (6.1.5)
^ top
6.2: Predefined Functions
Objectives
At the end of the lesson the student will be able to:
- Create code that calls predefined functions
- Describe the flow of control of a function call
- Write code that generates random numbers
|
^ top
6.2.1: About Functions
Function -- a subprogram (method, procedure or subroutine) that executes a block of code when called.
- Most popular programs are large, containing thousands to millions of lines of code
- When programs are this large, the best way to develop and maintain them is to construct them from smaller pieces or modules
- In C++, these smaller pieces are called functions
- Later on we will look at another way to create larger modules called Classes
- You may have noticed that we have been using functions already
- For instance,
main() is a function that we use in every program
1
2
3
4
5
6
7
|
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
}
|
- Function are often collected into libraries so they can be reused by many different programs
- C++ comes with many common libraries such as
<cmath> which contains functions like sqrt()
- We have used many of these library functions and will use more as the course progresses
- Functions such as these are known as predefined functions
- A predefined functions is simply a function that someone else wrote
- Our use of predefined functions shows one of the benefits of functions: reusable code
- Later on we will learn to define our own functions so that we can create reusable code as well
- For now, we are going to focus on how to use functions
^ top
6.2.2: Calling a Function
- When a function is defined or included in a program, C++ ignores the statements at first
- In order to run the statements, you must call the function
- Function call: an instruction that passes control to a function; after completing the function, control returns to the next instruction in the calling function.
- Calling a function is like a boss asking a worker to do something
- The "boss" (calling function) asks the "worker" (called function) to complete a task
Flow of Control for a Function Call
- To understand how a function works, you need to trace its flow of control
- The programs we write in this course have a single flow of control
- All the statements in our programs execute in sequence, which can be modified by conditional statements or loops
- A function call is another way to change the flow of control
- When we call the function, the caller function stops and waits for the called function to finish
- You can see this flow in the following diagram:

Arguments and Returned Values
- When we call a function we can send the function data called arguments
- For example, to calculate the square root of a number, we call the
sqrt() function with a particular value:
sqrt(9.0);
- In this case the argument is the numerical value
9.0
- When the called function finishes executing, it may return a value
- In this case our function returns the value
3.0
Example Program with a Function Call
1
2
3
4
5
6
7
8
9
10
|
#include <cmath>
#include <iostream>
using namespace std;
int main() {
double result = 1 + sqrt(9.0);
cout << result << endl;
return 0;
}
|
^ top
6.2.3: Generating Random Numbers
- Random numbers are a series of numbers whose order cannot be predicted
- The C++ library has a random number generator, which produces numbers that appear to be random
- Many computational problems need to use random numbers
rand() is a library function that produces a series of psuedorandom numbers:
- Range is
0 up to and including RAND_MAX
- Returns an "random"
int value
- Random numbers actual come from a a very long sequence of numbers computed from fairly simple formulas; they just behave like random numbers
- For that reason they are often called psuedorandom numbers
- The following program uses rand to produce the same output every time it runs
- The reason that the numbers are the same is because the numbers are generated with formulas
Example Program Using rand()
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int i;
for (i = 0; i < 10; i++) {
int num = rand();
cout << num << "\n";
}
return 0;
}
|
Another Random Number Generator
Random Number: a less useful random number generator from xkcd
^ top
6.2.4: Seeding the Random Generator
- When running programs we do not always want the same sequence of numbers every time
- For instance, if we run a dice simulation for a game we want different numbers every time the program runs
- To get a different number, we must seed the random number generator
- We set the seed with the
srand() function
- If we change the seed value, we will get different numbers every time
- One common strategy for changing the seed value is to use time
- Since the time changes every second, we get a new random number sequence every time we run our program
- To generate a number from time, we can use the time() function from the C time library:
srand(time(0));
- The expression
time(0) returns the number of seconds since January 1, 1970
^ top
Exercise 6.2
In this exercise we look at how to call functions and learn how to generate random numbers.
Specifications
- Copy the following program into a text editor, save it as
dice.cpp, and then compile the starter code to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
- Random numbers are generated by using the
rand() function. Declare two integer variables, die1 and die2, and assign them values returned by the rand() function using code like the following:
int die1 = rand();
int die2 = rand();
cout << "You rolled a " << die1
<< " and a " << die2 << endl;
For more information, see section: 6.2.3: Generating Random Numbers.
- Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 0 and a 1481765933
Notice the size of the numbers displayed. We want to limit the size of the random numbers generated by rand() to only six numbers. We limit the range by using the modulus (%) operator.
- Change the two assignment statements with the following code:
int die1 = rand() % 6;
int die2 = rand() % 6;
The number 6 in the above code is known as the scaling factor since it limits the scale of the numbers produced by the rand() function.
- Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 0 and a 5
- Seeing just one roll of the dice is not very useful. Add a counting loop to roll and display the dice 10 times. For more information, see section: 5.1.1: Using Loops to Count. You may want to use a
for loop for counting as described in section 5.1.2: for Statements.
- Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 0 and a 5
You rolled a 3 and a 2
You rolled a 5 and a 0
You rolled a 0 and a 4
You rolled a 0 and a 2
You rolled a 1 and a 3
You rolled a 5 and a 3
You rolled a 5 and a 0
You rolled a 5 and a 0
You rolled a 0 and a 5
Notice that we get numbers in the range of 0 to 5 when we want 1 to 6. To correct this problem, we must add one to each of the statements generating the random numbers. Go ahead and make this change now. For more information, see section: 6.2.5: Simulating Dice.
- Rerun your code two or more times and check the numbers rolled. Do you see any patterns? To correct the problem we must "seed" the random number generator. Add the following code after the start of main and before your counting coop:
srand(time(0));
For more information, see section: 6.2.4: Seeding the Random Generator.
- Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 1 and a 1
You rolled a 4 and a 5
You rolled a 5 and a 6
You rolled a 3 and a 6
You rolled a 2 and a 4
You rolled a 4 and a 6
You rolled a 3 and a 4
You rolled a 1 and a 5
You rolled a 4 and a 5
You rolled a 4 and a 6
- Submit your final program source code to Blackboard as part of assignment 6.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 6.2.7: Summary.
^ top
6.2.5: Simulating Dice
Example Program Simulating the Rolling of a Pair of Dice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <iostream>
using namespace std;
int main() {
srand(time(0));
for (int i = 0; i < 10; i++) {
int die1 = 1 + rand() % 6;
int die2 = 1 + rand() % 6;
cout << "You rolled a " << die1
<< " and a " << die2 << endl;
}
return 0;
}
|
^ top
6.2.6: Flotaing-Point Random Numbers
- Sometimes we want random numbers that are of data type
double
- For example, we may want a random number for simulations
- However, the
rand() function returns an int and we need to convert the int to a double
- For this we can use the formula:
double r = rand() / (RAND_MAX + 1.0);
- This produces a number between 0 (inclusive) and 1 (exclusive), often written as [0, 1)
- One we have this random
double, we multiply it by the scaling factor
- Also, we can shift the range using addition or subtraction
double num = r * SCALING_FACTOR + SHIFTING_VALUE;
- For example, we can get a random floating-point number between -10 and +10 (not including +10) using:
double r = rand() / (RAND_MAX + 1.0);
double y = r * 20 - 10;
- If we want to include +10 then we use the simpler:
double r = rand() / RAND_MAX;
double y = r * 20 - 10;
^ top
6.2.7: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- What is a function? (6.2.1)
- Why do we use functions? (6.2.2)
- Where does the control flow during a function call? (6.2.2)
- What is an argument? (6.2.2)
- What is a returned value? (6.2.2)
- What is a random number? (6.2.3)
- What is the value of
RAND_MAX on our classroom computers? (6.2.3)
- How do you make the
rand() function return a different random sequence when you run your program again? (6.2.4)
- How do you code a random number that simulates rolling a die? (6.2.5)
- What statement do we use to limit the range of the values returned by the
rand() function to the values 1 through 10? (6.2.5)
^ top
6.3: Coding Functions
Learner Outcomes
At the end of the lesson the student will be able to:
- Define functions with and without parameters
- Pass arguments to functions
|
^ top
6.3.1: Repeated Code
- Recall our test code to validate user input:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#include <iostream>
using namespace std;
int main() {
double input = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
cout << "You entered: " << input << endl;
return 0;
}
|
- What if we need to enter two validated numbers into a program?
- We want to process the first number after input and then input the second number
- Doing so, we would end up with code like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
#include <iostream>
using namespace std;
int main() {
double input = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
// Process the input
cout << "You entered: " << input << endl;
double input2 = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input2;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input2 = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
// Process the second input
cout << "You entered: " << input2 << endl;
return 0;
}
|
- Our program would be easier to write if we could get the second input without repeating the code
- Ideally, we would give the list of commands a name and then run the list using the name
- We can do this in C++ by writing a function
Programming Style: Avoid Duplicating Code
- Duplicate code is the mark of a poor or lazy programming style
- It can lead to problems such as:
- Long repeated sections that are more difficult to understand than shorter sequences
- Repetition of largely identical code within which it is difficult to see the different purposes of each section
- Update anomalies where you make changes in some sections but overlook making changes in other sections
- If you find yourself writing similar code of three or more lines multiple times, then consider writing a function
- For more information see the textbook page 192
^ top
6.3.2: Defining a Function
Function -- a named block of code.
- In other languages, a function is known as a method or subroutine.
- Once you define a function, you can execute the block of code using the function's name
- We have used functions already, such as:
sqrt(x) -- computes the square root of a floating point number
pow(x, y) -- computes the power of xy
- Many functions have input values (a.k.a. arguments or parameters) that are transferred or passed into the function
- For example:
- The
x in: y = sqrt(x);
- Both the
x and the y in: z = pow(x, y);
- An expression as in:
sqrt(b * b - 4 * a * c);
- Many functions have output or return values
- For example the
y in: y = sqrt(x);
- Both parameters and return values are a particular type
- For instance:
- You cannot compute:
sqrt("Ed Parrish");
- You cannot assign:
string thing = sqrt(5.5);
Function Syntax
- The general syntax for defining a function is:
returnType functionName(parameter1, ..., parametern) {
statements
}
- Where:
- returnType: the data type of the value returned
- functionName: the name you make up for the function
- parameterx: the input values, if any
- statements: the statements to execute when the function is called
- As an example, we can define our function to draw a square like this:
double readPosNum(String prompt) {
// Statements to read and validate the input
}
- Lets look more details of the syntax in order from left to right
Return Type
- Sometimes you will want a function to return a value
- If you do, then you need to specify the type of data it will return
- If you do not want a function to return a value, then you use the keyword
void
- In our example the return type is a
double
Function Name
- Technically, you can use any valid identifier for a function name
- However, you should use a name that suggests the action the function performs
- For instance,
readPosNum suggests that the function will get a positive number from the user
Parameter List
- You must have parenthesis after the function name
- Inside the parenthesis, you define a list of zero or more parameters
- Parameters are like variables except they are declared inside the function parenthesis
- Each parameter must have both a type and a name, just like a variable
- If you have more than one parameter, you separate each one with commas
- A parameter type can be any primitive type or class type, like a variable
- A class type is usually followed by an ampersand "
&" (we will discuss why later)
- Any parameter that you declare must be given a value when you call the function
Code Block
- After the parenthesis, you define the block of code that you want to execute
- The block starts with an opening curly brace: {
- The block ends with a closing curly brace: }
- Between the curly braces, you place all the statements you want the function to execute
- For readability, you indent the statements within the curly braces
^ top
6.3.3: Example Function Definition
- Let us define a function for reading positive numbers
- We are taking our previous repeated code and packaging it inside a function
- You can see the entire function in the following program
Example Program with a Function for Reading Input
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include <iostream>
using namespace std;
double readPosNum(string prompt) {
double input = 0.0;
do {
cout << prompt;
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
return input;
}
int main() {
double input = readPosNum("Enter a positive number: ");
// Process the input
cout << "You entered: " << input << endl;
double input2 = readPosNum("Enter another number: ");
// Process the second input
cout << "You entered: " << input2 << endl;
return 0;
}
|
- Note that the function
readPosNum() comes before main()
- In C++, the compiler requires us to declare a function before we call the function
- Since we call function
readPosNum() from main(), we must put the function before main()
- Also notice that the function
readPosNum() is outside of main()
- You cannot nest functions
- Instead, each function is separate from every other function
Variable Scope, Parameters and Return Statements
- A variable declared inside a function can only be used within that function
Local variable: a variable that can only be accessed within a function or block.
- For example, we declared
input inside the readPosNum() function:
double input = 0.0;
- In addition, we declared another variable named
input inside main():
double input = readPosNum("Enter a positive number: ");
- These are not the same variable even though the have the same name
- The area of code that a variable can operate within is known as it's scope
Scope: the enclosing area within which a variable exists
- To send information to a function we must use a parameter:
double readPosNum(string prompt)
- Within
main() we send the information to the parameter as part of the function call:
readPosNum("Enter a positive number: ")
- The string, "Enter a positive number: ", is passed to the parameter variable:
prompt
- To return information from a function, we use a return statement:
return input;
- We must save the returned information if we want to it for processing:
double input = readPosNum("Enter a positive number: ");
- This is the same process we used for calling
sqrt():
y = sqrt(x);
Flow of Control for a Function Call
^ top
Exercise 6.3
In this exercise we define our own function.
Specifications
- Copy the following program into a text editor, save it as
absvalue.cpp, and then compile the starter code to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
- Inside the
main() function, enter these statements:
cout << "This program calculates absolute values\n";
cout << "Number to calculate: ";
double num = 0.0;
cin >> num;
double absnum = calcAbs(num);
cout << "Absolute value is: " << absnum << endl;
The fifth line contains the function call. For more information on function calls, see section: 6.2.2: Calling a Function.
- Try to compile your code. You should see an error message like:
absvalue.cpp:9: error: `calcAbs' undeclared
The reason is that the we have not yet written the calcAbs() function. We must define a function before we can call the function.
- Before the
main() function, define a function named calcAbs() as shown below:
double calcAbs(double value) {
// Insert statements here
return value;
}
Your code should compile at this time. Even though the function is not complete, we have supplied enough information to the compiler to define the calcAbs() function.
- Inside the curly braces of the
calcAbs() function, write the statements to calculate the absolute value using the following psuedocode:
if value is less than zero return -1 * value
return value
- Compile and run your modified program and verify the output looks like:
This program calculates absolute values
Number to calculate: -42
Absolute value is: 42
Also, verify that a positive number works correctly:
This program calculates absolute values
Number to calculate: 42
Absolute value is: 42
- In addition to completing the programming code, prepare a second file named
trace.txt.
- In the
trace.txt file, list the line numbers of each statement of your program in the order the lines are executed. For example, if main() starts on line 11, statements are executed as follows:
11, 12, 13, 14, ...
Do not bother to list blank lines or lines containing only the closing curly brace (}) of a function definition.
- Review the hand trace 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 trace with Fred George.
- Submit both files absvalue.cpp and trace.txt to Blackboard as part of assignment 6.
Completed Program
When finished, your application should look like the following.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 6.3.7: Summary.
^ top
6.3.4: Passing Arguments to a Function
Arguments and Parameters
^ top
6.3.5: Returning a Value
- Functions that return a value must execute a
return statement
return result;
- For instance, in our example, function
readPosNum() had a return statement
double readPosNum(string prompt) {
double input = 0.0;
do {
cout << prompt;
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
return input;
}
Returning Early
- Sometimes you do not want to execute all the code in a function
- You can use a
return statement to stop execution and return from anywhere
- Control returns immediately from a function whenever a
return is reached
^ top
6.3.6: Some Style Requirements for Functions
- Consider again our example function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include <iostream>
using namespace std;
double readPosNum(string prompt) {
double input = 0.0;
do {
cout << prompt;
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
return input;
}
int main() {
double input = readPosNum("Enter a positive number: ");
// Process the input
cout << "You entered: " << input << endl;
double input2 = readPosNum("Enter another number: ");
// Process the second input
cout << "You entered: " << input2 << endl;
return 0;
}
|
- Note the placement of the curly braces
- There are two common styles of curly brace placement for functions:
- Place the opening brace on the same line as the function heading:
void myFunction() {
// statements of the function
}
- Place the opening brace under and lined up with the first letter of the return type:
void myFunction()
{
// statements of the function
}
- You can use either style as long as you are consistent
- Also notice the indentation of the statements inside the function
- As before, you always indent 3-4 more spaces after an opening curly brace
- After the closing curly brace, you no longer indent the extra 3-4 spaces
- Indenting makes it easier to see the block of code
^ top
6.3.7: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- Why do programmers write functions? (6.3.1)
- What is a function? (6.3.2)
- What are the four main parts of a function? (6.3.2)
- How can you tell the difference between a function name and a variable name? (6.3.2)
- How many parameters can you declare for a function? (6.3.2)
- How is a variable declaration different than a parameter? (6.3.2)
- If you declare a variable inside main() can you access that variable inside another function? (6.3.3)
- Why do functions need parameters? (6.3.3)
- If you call a function in
main(), do you place the function definition before or after main()? (6.3.3)
- What happens to the flow of control when a function call is reached? (6.3.3)
- If you declare three parameters, how many arguments must you include in a function call? (6.3.4)
- Which of the following is a function definition and which is a function call? (6.3.4)
void drawSquare(Turtle& turtle, double side) { }
drawSquare(myrtle, 7.5);
- What is the difference between an argument and a parameter? (6.3.4)
- What statement is used to return values from functions? (6.3.5)
- True or false? You should indent code within a function. (6.3.6)
^ top
6.4: Midterm Preparation
Learner Outcomes
At the end of the lesson the student will be able to:
- Discuss how to prepare for the midterm exam
- Describe how to take the midterm exam
|
^ top
6.4.1: About the Exam
- You must attend the exam or you will receive a score of zero (0)
- Except by prior arrangement with the instructor
- I am using Blackboard to administer the test
- Since there are more students than computers, we must take the exams in shifts
- Shifts are determined by your last name and section as follows:
| Last Name |
Section |
Start Time |
| A-L |
Day |
10:20 AM |
| M-Z |
Day |
11:20 AM |
| A-K |
Evening |
6:00 PM |
| L-Z |
Evening |
8:00 PM |
- If you want to change shifts then make arrangements to switch with another student who is on the other shift
- The exam is closed books and closed notes
- However, you may have one 3" x 5" card of handwritten notes for the exam
- You may use a computer from the classroom, but only to take the exam in Blackboard
- You may have a sheet of blank scratch paper
- You may NOT use the computer to compile or run programs
- You may NOT use the computer to view documents on the Internet
- You may NOT use a calculator or other electronic device
- Thus, you may NOT use your own computer to take the exam
- If you have a cell phone visible or in use during the exam, you will automatically fail
- You may NOT communicate with anyone but the instructor during the exam
3"x5" Card Requirements
- Put your name on your card
- Maximum card or paper size is 3 inches by 5 inches
- You may use both sides of the card
- Notes must be handwritten and NOT photocopied
- Notes cannot have any complete functions -- only code snippets
- Any 3" x 5" cards violating these rules will be confiscated before the test
- You must turn in your 3" x 5" card after the exam in any case
^ top
6.4.2: Recommended Preparation
- Try the Example Midterm in Blackboard
- These questions are intended to help you get a "feel" for taking an exam in Blackboard
- The questions are NOT intended to tell you everything that is on the exam
- Review the instructor's notes and make sure you can answer the Check Yourself questions, making notes about anything that you have difficulty answering
- Review your notes and prepare your 3" x 5" card
- Review your homework assignments and solutions
- Review your CodeLab exercises
- You should be prepared to write short programs using:
- Mathematical expressions
- User I/O
- Conditional statements
- Testing multiple conditions
- "main" loops
- Counting loop algorithms such as accumulating values in a loop
- Using library functions (
pow(), rand(), sqrt(), etc.)
- Declaring and defining functions
- More quiz tips: Basic Rules For Taking a Multiple-Choice Test
^ top
6.4.3: Exam Taking Tips
- Save after every answer -- you can change your mind and choose another
- If you get stuck on a question, make your best guess and return later
- If you are equally uncertain between two choices, go with first impression
- When writing code, do NOT add more than the problem asks for
- You do not need to comment code for tests and exams
- Unless specifically instructed to in the exam question
- Use the full time available
- Check your work if you finish early
^ top
6.4.4: Questions and Answers
^ top
Wrap Up
Due Next: A5-Loopy Programs (3/18/10)
A6-Programs With Functions (4/8/10)
- When class is over, please shut down your computer
- You may complete unfinished exercises at the end of the class or at any time before the next class.
^ top
Home
| Blackboard
| Day Schedule
| Eve Schedule
Syllabus
| Help
| FAQ's
| HowTo's
| Links
Last Updated: March 20 2010 @20:09:42
|