#include <iostream>
using namespace std;
const double PI = 3.14159265;
double circleArea(double radius) {
double area = PI * radius * radius;
return area;
}
int main() {
cout << "Enter the radius of a circle: ";
double radius = 0.0;
cin >> radius;
double area = circleArea(radius);
cout << "The circle area is " << area << endl;
return 0;
}
Global Variables and Constants
Notice the constant variable PI in the above example:
const double PI = 3.14159265;
C++ lets you define variables and constants with global scope
Global variables and constants are declared outside of any function and can be accessed in any function
Because they have the same value everywhere, global constants are considered good programming practice
Programming Style: No Global Variables
Global variables are variables that are defined outside functions
They are declared just like a global constant but without the const keyword
Unlike global constants, global variables are considered poor programming practice
A global variable can be modified anywhere in your program, so it is hard to trace where it is changed
Global variables make programs more difficult to understand and maintain
Do not use global variables in your programs for this course
Instead, use function parameters and return statements to transfer data from one function to another
#include <iostream>
using namespace std;
// Returns the square of a number
double square(double number);
// Displays a message to the console
void log(string funName, double value);
int main() {
double number = 5;
log("main", number);
double result = square(5);
log("main", result);
return 0;
}
double square(double number) {
log("square", number);
double result = number * number;
log("square", result);
return result;
}
void log(string funName, double value) {
cout << "In " << funName << "() the value is ";
cout << value << endl;
}
Check Yourself
A function ________ is a declaration of a function before it is defined.
True or false: one reason for function prototypes is to allow the programmer to write the function definition after the main() function.
True or false: the main difference between a function prototype and a function definition is that the function body is missing in a function prototype.
Of the following, ________ would be a valid function prototype.
#include <iostream>
using namespace std;
/**
Returns the square of a number
@param number The number to square
@return the square of number
*/
double square(double number);
/**
Displays a message to the console
@param funName The name of the function
@param value The value to display
*/
void log(string funName, double value);
int main() {
double number = 5;
log("main", number);
double result = square(5);
log("main", result);
return 0;
}
double square(double number) {
log("square", number);
double result = number * number;
log("square", result);
return result;
}
void log(string funName, double value) {
cout << "In " << funName << "() the value is ";
cout << value << endl;
}
Using Doxygen
The purpose of the comment layout is to produce hyperlinked web pages describing your program
The program we use to produce the web pages is called Doxygen
We can run Doxygen from TextPad in the classroom and CTC
You can install Doxygen at home by following my instructions
Running Doxygen produces a folder named "html"
Inside the folder, we open the index.html file in a Web browser
Of the following, ________ is an acceptable curly-brace placement and statement indentation style for function definitions.
int fun() { /* C++ statements */ }
int fun() { /* C++ statements */ }
int fun() { /* C++ statements */ }
int fun() { /* C++ statements */ }
True or false: functions names should start with lower-case letters.
True or false: comments should be placed before function prototypes instead of function definitions.
By starting block comments with ________ instead of /*, you tell Doxygen to include your comments in the hyperlinked web page documentation it produces.
True or false: the first line of a function block comment explains the idea of the function, not the implementation.
For every function parameter, you include a(n) ________ tag in the function block comment.
If the function returns a value, you include a(n) ________ tag in the function block comment.
#include <iostream>
using namespace std;
// Returns the square of a number
double square(double number);
// Displays a message to the console
void log(string funName, double value);
int main() {
double number = 5;
log("main", number);
double result = square(5);
log("main", result);
return 0;
}
double square(double number) {
log("square", number);
double result = number * number;
log("square", result);
return result;
}
void log(string funName, double value) {
cout << "In " << funName << "() the value is ";
cout << value << endl;
}
In this exercise we trace the flow of control in a program where functions call other functions, both void and non-void functions.
Specifications
Create a file named trace.txt.
In the trace.txt file, list the line numbers of each statement of the program shown below in the order the lines are executed. For example, the following are the first few line numbers of the program flow (assuming main() starts on line 20):
20, 21, 22, 36, 37, ...
Do not bother to list blank lines or lines containing only the closing curly brace (}) of a function definition. For more information on tracing, see section 7.1.6: Tracing Code.
Save the trace.txt file to submit to Blackboard as part of assignment 7.
#include <iostream>
using namespace std;
/**
Returns the square of a number
@param number The number to square
@return the square of number
*/
double square(double number);
/**
Displays a message to the console
@param funName The name of the function
@param value The value to display
*/
void log(string funName, double value);
int main() {
double number = 5;
log("main", number);
double result = square(5);
log("main", result);
return 0;
}
double square(double number) {
log("square", number);
double result = number * number;
log("square", result);
return result;
}
void log(string funName, double value) {
cout << "In " << funName << "() the value is ";
cout << value << endl;
}
As time permits, review the summary below and be prepared to answer the Check Yourself questions.
In this exercise we explore how call-by-reference parameters differ from call-by-value parameters.
Specifications
Type the following program into a text editor and save it as swap.cpp:
Compile and run the starter program to make sure you entered it correctly. When you run the program, the output should look like this:
Enter two integers: 1 2
After calling function: 1 2
Notice that num1 and num2 have the same values before and after calling the function swap(). Any value assigned to var1 and var2 have no effect on num1 and num2. For more information, see section: 7.2.1: Parameter Passing and Value Parameters.
Change your program by adding the four ampersands (&) circled below:
The ampersands tell C++ to use call-by-reference when passing parameter values. For more information, see section: 7.2.2: Using Reference Parameters.
Compile and run the modified program to make sure you made the changes correctly. When you run the program, the output should look like this:
Enter two integers: 1 2
After calling function: 2 1
Notice that num1 and num2 have different values before and after calling the function swap(). Any value assigned to var1 and var2 change num1 and num2 respectively. For more information, see section: 7.2.2: Using Reference Parameters.
Submit your final program source code to Blackboard as part of assignment 7.
Check Yourself
As time permits, be prepared to answer these questions. You can find additional information by following the links after the question.
When an argument is passed to a value parameter, what gets copied? (7.2.1)
When an argument is passed to a reference parameter, what gets copied? (7.2.2)
How do call-by-value and call-by reference differ? (7.2.1 and 7.2.2)
Can you mix call-by-value and call-by-reference in the same parameter list? (7.2.3)
We use top-down design to list the initial steps or tasks
One such list of steps is:
Get the size and cost of both pizzas
Compute the price per inch for smaller pizza
Compute the price per inch for larger pizza
Determine which size is the better buy
Output the size of the better buy
Is any step too complex to solve easily?
If so they we break the step down into subtasks
When the breakdown is complete, we look for ways to simplify the design
We notice that tasks 2 and 3 are the same:
radius = diameter / 2
area = PI * radius ^ 2
pricePerSquareInch = price / area
Both of these tasks take the same type of input and return the same type of result
Whenever two or more subtasks make the same computation, you should make a function out of them
Rule of thumb: If you reuse the same sequence of 3 or more statements in various parts of your program, you should write a function to perform the task.
For instance, we could make a function named calcUnitPrice()
When writing a function, you start with comments and the function prototype:
/**
Calculates the price per square inch of a pizza
@param diameter The diameter of the pizza in inches.
@param price The price of the pizza in dollars.
@return The price per square inch of a pizza.
*/
double calcUnitPrice(int diameter, double price);
Notice how our function is specified
A programmer knows what values can be sent to the function and what to expect back from the function without needing to see the function code
This is known as designing a function as a black box
1. Get the size and cost of both pizzas
2. Compute the price per inch for smaller pizza
3. Compute the price per inch for larger pizza
4. Determine which size is the better buy
5. Output the size of the better buy
/**
Calculates the price per square inch of a pizza
@param diameter The diameter of the pizza in inches.
@param price The price of the pizza in dollars.
@return The price per square inch of a pizza.
*/
double calcUnitPrice(int diameter, double price);
radius = diameter / 2
area = PI * radius ^ 2
pricePerSquareInch = price / area
Before translating our design into code, we should test it or do a walkthrough (a.k.a. desktop testing)
walkthrough a process of checking the algorithm step-by-step
For out walkthrough, we use example numbers to test our algorithm
If the walkthrough yields the correct result, we have confidence our algorithm is correct
Take two minutes to read the following questions and answer "yes" or "no" according to how you currently prepare for exams.
Do you begin planning and studying for exams from the first week of the semester?
Do you attend all classes and use effective note-taking strategies?
Do you review your reading and lecture notes the day after and on a weekly basis?
Do you analyze your homework, quizzes, and exams throughout the semester for pattern and error?
Do you identify possible exam questions while reading and taking notes?
Do you study with a partner or a group?
Do you use your instructors' office hours to ask questions about material you don't understand?
Do you use study strategies appropriate for the type of exam (like flashcards to memorize facts, completion of example problems to understand processes)?
Do you use small portions of time for review rather than cramming?
Do you learn course material in-depth enough that you could explain it to one of your classmates?
Discussions Questions
What are your practices when preparing for tests or exams?
How much time do you dedicate to preparation?
What are your successful strategies for exam preparation?
No one can ace a test without studying and understanding the material
To get an "A" you need to thoroughly prepare for the test well in advance
With the midterm approaching, you have a choice:
Study and do well, or
Not study and do less than your best
Victims are people who let their lives control them, like a pawn on a chessboard
Creators are people who controls their own life, like a person playing chess
You can take responsibility for studying and do well on a test
Or you can make excuses and do less than you are capable of on a test
Boosting Your Performance
Here are some steps you can take to improve your test results:
Compile a list of topics you might be tested on.
Look over your assignments, exercises, and lecture notes to determine what you covered. Write a list of topics from these sources.
Make sure you understand all the topics on your list.
Correct any mistakes you may have made in your assignments or exercises.
Identify the most probable exam topics for thorough study.
To do well, you need deep understanding of the test topics. Oftentimes, you can tell what is on a test simply by which topics the instructor spends the most time talking about.
Create a list of test questions.
Turn headings from the textbook and lecture notes into questions. Look at the section summaries in the lectures and read the Check Yourself questions.
Study your questions over and over until you know them perfectly.
Make flash cards with questions on one side and answers on the other. Carry the cards with you and review them when you have a few minutes available. Have other people ask you questions from your flash cards.
Prepare your 3"x5" card of test notes.
Since the instructor allows a 3"x5" card, make use of it. For the topics you had the most trouble with, write down a short note or summary. If the pressure of the test causes you to forget something, you can refer to your card.
Use the next 10 minutes to complete the following.
Join a group of 4-5 people and introduce yourself to each other.
As a group, develop a list of topics for one of the lessons of the lecture notes
Write your list of topics on the board.
As a homework, prepare a list of 5 questions on one of the topics. Post the questions you develop in the indicated Discussions area of Blackboard before the first test day. Your posts will be graded.