What We Will Cover
Continuations
Problem 1: What is output by the following program? (Do not run the code -- work it out by hand)
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 mystery(int param);
int main() {
int num = 2;
cout << "At first, num=" << num << endl;
int result = mystery(num);
cout << "Later, num=" << num << endl;
cout << "And result=" << result << endl;
return 0;
}
int mystery(int param) {
cout << "param=" << param << endl;
param = param * 2;
return param;
}
|
-
At first, num=2
Later, num=2
-
At first, num=2
param=2
Later, num=2
-
At first, num=2
param=2
Later, num=4
- None of these
Problem 2: You have been hired to fix a computer program designed to help in the war on terror. You come across the following code and realize there are two at least errors here. Can you spot the them?
if (person = terrorist) {
punish_severely();
} else {
exit(-1);
}
Solution for one of ther errors and credit for the code.
Homework Questions?
Homework Discussion Questions (Thursday)
- Did the use of functions shorten or lengthen the program? Why?
- Did the use of block comments clarify how to use a function?
- How was the
inputValue() used?
^ top
7.1: void Functions and Tracing Calls
Objectives
At the end of the lesson the student will be able to:
- Describe how
void functions differ from functions that return a value
- Declare and define
void functions
- Decide when to use
void functions
- Trace function calls
|
^ top
7.1.1: void Functions
- Previously we looked at functions that returned one value
- Functions returning a value use the
return statement
return result;
A function that returns no value is called a void function
In C++, void functions are defined like functions that return a value
However, the keyword void replaces the return type
For example, what do you notice that is different about the following?
void showResults(double fDegrees, double cDegrees) {
cout << fDegrees
<< " degrees Fahrenheit is equivalent to "
<< cDegrees << " degrees Celsius." << endl;
return;
}
There are only two differences between definitions for void functions and other functions.
void return type
return statement is optional and does not specify a value if used
If no return type is specified, the function returns after executing the last statement
Why might you code a return statement if its use is optional?
Here is an example program using the void function shown above
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#include <iostream>
using namespace std;
// Converts Fahrenheit to Celsius and shows results
void showFToC(double fDegrees);
int main() {
double fTemperature;
cout << "Enter a temperature in Fahrenheit: ";
cin >> fTemperature;
showFToC(fTemperature);
return 0;
}
void showFToC(double fDegrees) {
double cDegrees = 5.0 / 9 * (fDegrees - 32);
cout << fDegrees
<< " degrees Fahrenheit is equivalent to "
<< cDegrees << " degrees Celsius." << endl;
return;
}
|
^ top
7.1.2: Calling void Functions
- When you call a
void function you must code the call as a separate statement
- A
void function cannot be part of an expression
- For example, look at the following function call:
showResults(32.5, 0.3);
This will cause the following to appear on the screen:
32.5 degrees Fahrenheit is equivalent to
0.3 degrees Celsius.
Note that the void function call does not return a value
If the function call was part of an expression like the following, what would be printed?
cout << showResults(32.5, 0.3); // not allowed
If you tried to compile code like this, you would get a lengthy set of error messages
^ top
7.1.3: Functions Calling Functions
- Functions may call other functions
- Within the body of the function, you can code a function call
- We are already doing this when
main() calls another function
- What does the following program display to the console?
Example of Functions Calling Functions
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
|
#include <iostream>
using namespace std;
// Returns the square of a number
double square(double number);
// Displays a message to the console
void out(string funName, double value);
int main() {
double number = 5;
out("main", number);
double result = square(5);
out("main", result);
return 0;
}
double square(double number) {
out("square", number);
double result = number * number;
out("square", result);
return result;
}
void out(string funName, double value) {
cout << "In " << funName << "() the value is "
<< value << endl;
}
|
^ top
7.1.4: Tracing a Function Call
- When functions call functions, you need to follow the flow of execution
- A function call transfers control to the first statement of the called function
- When a return point is reached, control passes back to the point right after the function call
- If the function call is part of an expression, the returned value is used in the expression
- Let's trace the flow in the following code by line number:
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
|
#include <iostream>
using namespace std;
// Returns the square of a number
double square(double number);
// Displays a message to the console
void out(string funName, double value);
int main() {
double number = 5;
out("main", number);
double result = square(5);
out("main", result);
return 0;
}
double square(double number) {
out("square", number);
double result = number * number;
out("square", result);
return result;
}
void out(string funName, double value) {
cout << "In " << funName << "() the value is "
<< value << endl;
}
|
^ top
7.1.5: Summary
- You code a
void return type when you do not want a function to return a value
- For example:
void showResults(double fDegrees, double cDegrees) {
cout << fDegrees
<< " degrees Fahrenheit is equivalent to "
<< cDegrees << " degrees Celsius." << endl;
return;
}
The return statement is optional for void functions
When a void function executes the last statement, it automatically returns
If a return statement is coded for a void function, it does not include a return value
return;
Functions with a void return type cannot be called as part of an expression
showResults(32.5, 0.3);
NOT:
cout << showResults(32.5, 0.3);
Functions can call other functions, just like main() calls other functions
Check Yourself
- How do
void functions differ from functions that return a value?
- How do you declare and define a void function?
- When do you use a
void function?
- Are you required to have a return statement in a
void function definition?
- What effect would removing the return statement from the following function have on compiling or executing the program?
void showResults(double fDegrees, double cDegrees) {
cout << fDegrees
<< " degrees Fahrenheit is equivalent to "
<< cDegrees << " degrees Celsius." << endl;
return;
}
- Assuming that
showResults() is a void function, what is wrong with:
cout << showResults(32.5, 0.3); // not allowed
- How do you code a function to call another function?
^ top
Exercise 7.1
In this exercise we explore how to trace the flow of code that uses functions.
Specifications
- Create a file named trace.txt
- In the trace.txt file, list the number of each line for the following program in the order the lines are processed.
Do not bother to list lines containing just a closing curly brace (}) of a function definition.
- Submit the trace.txt file as the solution to this exercise.
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
|
#include <iostream>
using namespace std;
// Returns the square of a number
double square(double number);
// Displays a message to the console
void out(string funName, double value);
int main() {
double number = 5;
out("main", number);
double result = square(5);
out("main", result);
return 0;
}
double square(double number) {
out("square", number);
double result = number * number;
out("square", result);
return result;
}
void out(string funName, double value) {
cout << "In " << funName << "() the value is "
<< value << endl;
}
|
^ top
7.2: Call-By-Reference Parameters
Objectives
At the end of the lesson the student will be able to:
- Explain the difference between call-by-value and call-by reference parameter passing
- Return values from functions using call-by-reference
|
^ top
7.2.1: About Parameter Passing
- Two ways to pass arguments to parameters
- Call-by-value
- A copy of the value is passed
- Call-by-reference
- The address of the actual argument is passed
- All our functions so far have used call-by-value parameters
Call-by-Value Parameters
- A copy of the actual argument is passed
- Same as a local variable with special initialization inside the function
- If modified, only the local copy changes
- The function has no access to the actual argument from the caller
- This is the default operation for function calls
- Used in all our examples so far
Example of Call-ByValue Parameters
- What does this program output?
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 mystery(int param);
int main() {
int num = 2;
cout << "At first, num=" << num << endl;
int result = mystery(num);
cout << "Later, num=" << num << endl;
cout << "And result=" << result << endl;
return 0;
}
int mystery(int param) {
cout << "param=" << param << endl;
param = param * 2;
return param;
}
|
^ top
7.2.2: Call-By-Reference Parameters
- C++ has another parameter-passing mechanism known as call-by-reference
- Used to provide access to caller's actual argument inside a function
- Caller's data can be modified by the called function!
- Specified by an ampersand '
&' after the type in the parameter list
For Example
- Here is a program that outputs the same things as the previous example
- What is different?
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 mystery(int& param);
int main() {
int num = 2;
cout << "At first, num=" << num << endl;
int result = mystery(num);
cout << "Later, num=" << num << endl;
cout << "And result=" << result << endl;
return 0;
}
int mystery(int& param) {
cout << "param=" << param << endl;
param = param * 2;
return param;
}
|
Call-By-Reference Details
- What's really passed in?
- A reference back to the caller's original argument!
- Refers to memory location of the original argument
- Called an address, which is a unique number referring to a place in memory
- Note that arguments for call-by-reference parameters must be variables, not constants
^ top
7.2.3: Mixed Parameter Lists
- You can combine parameter-passing mechanisms
- Parameter lists can include pass-by-value and pass-by-reference parameters
- As usual, the order of arguments in the list is critical:
void mixedCall(int& par1, int par2, double& par3);
Function call:
int arg1 = 0, arg2 = 1;
double arg3 = 2.2;
mixedCall(arg1, arg2, arg3);
arg1 must be integer type and is passed by reference
arg2 must be integer type and is passed by value
arg3 must be double type and is passed by reference
^ top
7.2.4: Summary
- A formal parameter is a local variable with special initialization
- The parameter is filled in with the actual argument during the function call
- Call-by-value parameters are local copies of argument in the function body
- The actual argument cannot be modified
- Call-by-reference parameters allow you to change the variable used in the function call
- Actual argument can be modified
'&' symbol (ampersand) identifies call-by-reference variables
- Call-by-reference passes the memory address of actual argument
- Whatever is done to a formal parameter in the function body, is actually done to the value at the memory location of the argument variable
- Makes the parameter an alias for the original argument
- Arguments for call-by-reference parameters must be variables, not constants
- You can mix call-by-value and call-by-reference parameters in a function
void mixedCall(int& par1, int par2, double& par3);
Check Yourself
- What happens in a call when the function is defined for call by value?
- What happens in a call when the function is defined for call by reference?
- How do call-by-value and call-by reference differ?
^ top
Exercise 7.2
In this exercise we explore how call-by-reference values are returned from functions.
Specifications
- Create a file named reference.txt.
- Compile and run the following code.
- Record the answers to these questions in your reference.txt file.
Q1: What does the program do?
Q2: What output do you get if you remove the ampersands '&' from the swapValues() parameter list?
Q3: How do call-by-value and call-by reference differ?
- Submit your reference.txt file as the solution to this exercise.
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;
void swapValues(int& variable1, int& variable2);
int main() {
int num1 = 1, num2 = 2;
cout << "Original values: " << num1
<< " " << num2 << endl;
swapValues(num1, num2);
cout << "Swapped values: " << num1
<< " " << num2 << endl;
return 0;
}
void swapValues(int& variable1, int& variable2) {
int temp = variable1;
variable1 = variable2;
variable2 = temp;
}
|
^ top
7.3: Array Basics
Objectives
At the end of the lesson the student will be able to:
- Declare and allocate memory for arrays
- Generate code to initialize arrays
- Access array elements
|
^ top
7.3.2: Introduction to Arrays
Array: a single name for a collection of identically-typed data values
- Arrays are a type of data structure
-- a way to organize data
- An array is used to process a collection of data of the same type
- Why do we need arrays?
- Imagine keeping track of 5 test scores, or 100, or 1000 in memory
- How would you name all the variables?
- How would you process each of the variables?
- Arrays provide a convenient solution to these problems
- Entire array referred to by a single identifier
- Each element uniquely identified by an index number
For Example
- One-dimensional array is like single row of data in spreadsheet or table
score[0] |
score[1] |
score[2] |
score[3] |
score[4] |
| 90 |
95 |
87 |
89 |
98 |
- Top row shows the indices for an array named "
score"
- Individual items are referenced by the index (a.k.a. subscript)
- All the values are of the same type:
int
- Array size is 5
^ top
7.3.2: Declaring and Allocating Arrays
- Consider an array named
score containing 5 values
- You declare and allocate memory for this array like this:
int score[5];
This is like declaring 5 variables of type int numbered as follows:
score[0], score[1], score[2], score[3], score[4]
The value in brackets is called an index
Individual values in an array are called items or elements
The number of indexed variables in an array is the size of the array
- The largest index is one less than the size
- The first index value is zero
Array declaration syntax:
DataType arrayName[size];
Arrays can be of any data type
All the variables of an array are always of the same data type
- Known as the base type of the array
Once created, you cannot change the number of elements
The best way to specify the size of an array is to use a constant
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];
This allows you to know the size anywhere in your code
If you need to change the size, you change only a single constant and recompile
^ top
7.3.3: Selecting Array Elements
- Each array element is referenced by name and an index inside of square brackets
score[3] is one of the indexed variables of the score array
score[0]++;
The index can be any integer expression
int n = 2;
score[n + 1] = 99;
You can use an indexed array variable like any regular variable
score[0] = score[1] + 1;
score[0]++;
^ top
7.3.4: Initializing Array Values
- You can assign a value to an array element any time after it is declared
const int NUMBER_OF_STUDENTS = 5;
int score[NUMBER_OF_STUDENTS];
score[0] = 90;
score[1] = 95;
score[2] = 87;
score[3] = 89;
score[4] = 98;
Static Initialization
- You can also initialize array elements in the declaration statement
- Called initialization
- Use a comma-separated list inside curly-braces
int score[] = {90, 95, 87, 89, 98};
Produces the same array as the previous example
The size of the array is determine automatically from the list
If you want a longer array with only the first few elements initialized, you can use:
int score[NUMBER_OF_STUDENTS] = {90, 95, 87};
Uninitialized Elements
- Note that if you do not assign a value to an array element, its value is not known
- Just like with regular variables, there are no default values assigned
^ top
7.3.5: Summary
- Arrays are convenient ways to process a list of data
- You declare and allocate space for an array with a single statement:
int score[5];
The best way to specify the size of an array is to use a constant
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];
This allows you to know the size anywhere in your code
If you need to change the size, you change only a single constant
Each array element is referenced by name and an index inside of square brackets
You can use an indexed array variable like any regular variable
score[0] = score[1] + 1;
You can initialize array elements individually with an assignment statement
score[0] = 90;
A more convenient way is to use an initializer list
int score[NUMBER_OF_STUDENTS] = {90, 95, 87, 89, 98};
Check Yourself
- How do you declare and allocate memory for an array?
- If you declare an array with 100 elements, what is the number of the maximum element?
- How do you specify a single array element?
- How many ways are there to initialize the elements of an array? Give an example of each way to initialize arrays.
^ top
Exercise 7.3
In this exercise we explore declaring, allocating and assigning values to arrays containing lists of data.
Specifications
- Save the following code file as
myarrays.cpp.
- Make sure your code compiles after every array that you declare, allocate and print.
- Declare and allocate an array for a list of 100 integer grades and print at least one element of the array to the screen.
- Declare and allocate an array of
char vowels, assigning a value to each array element. After assigning the value, print all the elements of the array.
- Declare and allocate an array of double-precision values holding the temperatures
25, 30 and 40 in order. In addition, print all the elements of the array.
- Declare and allocate a list of strings holding the names:
Able, Baker and Charlie in order. Also, print all the elements of the array.
- Submit your source-code file as the answer to this exercise.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
// A list of 100 integer grades
// A list of chars holding vowels
// A list of doubles holding temperatures
// A list of strings holding names
return 0;
}
|
^ top
7.4: Midterm Preparation
Objectives
At the end of the lesson the student will be able to:
- Discuss how to prepare for the first midterm exam
- Describe how to take the first midterm exam
|
^ top
7.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 WebCT 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 as follows:
- Shift 1: A-K (starts at the regular class time)
- Shift 2: L-Z (starts half way through regular class time)
- You must come to the classroom when your shift is scheduled
- Except you can arrange to switch with another student on the shift you want
- You may have less time if you are late to your scheduled time
- The exam is closed books and closed notes
- However, you may have one 3" x 5" card of handwritten notes for the exam
- You must turn in your 3" x 5" card after the exam
- You may use a computer from the classroom, but only to take the exam in WebCT
- 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
^ top
7.4.2: Recommended Preparation
- Try the Example Midterm in WebCT
- These questions are intended to help you get a "feel" for taking an exam in WebCT
- 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
- 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
- Call-by-value
- Call-by-reference
- More quiz tips: Basic Rules For Taking a Multiple-Choice Test
^ top
7.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
- Use any remaining time to check your work
^ top
7.4.4: Questions and Answers
^ top
Wrap Up
Reminders
Due Next: A6: Clothing Redux (3/22/07)
Exercise 6 and CodeLab Lesson 6 (3/22/07)
A7: Counting the Odds (4/12/07)
Exercise 7 and CodeLab Lesson 7 (4/12/07)
- 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
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: March 20 2007 @13:05:54
|