C++ Seminar: 1094 Session 3
Handouts: None!
Your goals for today: Quick
review of Days 3 and 4 then work through Day 5 and get started
on Day 6.
Review: Days 3 and 4
We'll briefly step through the C++ features used in Days 3 and 4,
prompting for questions.
- Variable types
- Variable names
- Please get in the habit of choosing names that are self-documenting.
For example, if you have variables that represent the mass of a ball,
a dog, and a cat, don't use Mb, Md, and Mc
or something equally cryptic. Two reasonable choices would be:
double mass_ball, mass_dog, mass_cat;
or
double massBall, massDog, massCat;
These are examples of two common conventions (lowercase with "_"
between words or lowercase first word and capitalize the rest
of the words).
- Incrementing, Decrementing, and all that
- There is really no reason to use the prefix version (++i)
instead of the postfix version (i++), because they should
only be used on a line by themselves (or as part
of a for statement, which we'll see later).
- Here are three ways to add one to the variable count:
int count = 1;
count = count + 1; // count = 2 now
count++; // count = 3 now
count += 1; // count = 4 now
Any of these will work fine, but the last two are easier to read
in most cases (speed is not an issue here nor is the number of
characters in a line). The last version is very versatile:
count += 2; // count = 6 now
count -= 4; // count = 2 now
count *= 5; // count = 10 now
count /= 2; // count = 5 now
Day 5: Organizing into Functions
In this part, we expand on the use of functions (there's lots of stuff
here!).
You can find more information about these things in the
online version of Day 5.
- When you use a function, you should define a prototype,
which tells C++ the name of the function, its return type, and the
number and types of its arguments. Download and take a look at
List0501.cpp for a first example. The prototype for the
Area function appears
at the top, before main, while the actual function definition
comes after main.
- The prototype looks just like the first line of the actual
function, except that it ends with a semicolon.
- The names of the arguments used in the prototype are irrelevant
(they are dummy names), but it is usual practice to use the same
names as in the function definition.
- Change the prototype and function to Volume, which
takes a third argument depth, and has appropriate variables
for calculating the volume of the yard.
- Take a look at List0502.cpp as another example of a function
prototype, with float variables and return type. There's not much to
say here, other than to say again that you should use double's
instead of float's.
- Let's talk about the ``scope'' of variables. Compile and run
List0503.cpp. The variable x is declared as an int
and initialized in three different places. But it is really three different
x's, because they are declared (with an int statement)
in two different functions (main and myFunc) and
the second one in myFunc is delared in a block, which
is any group of statements surrounded by {}'s. Try introducing
a new block into main with a fourth declaration of x,
using a new value and printing it out to check.
- Download List0505.cpp but do not compile and run it yet.
Notice that x and y
are declared before any of the functions. That makes them global
variables, whose value is available to any function. Note also that
a second, local y is declared. Predict the output before compiling
and running, then check against the actual results. The program
will fail to compile at first; where can you move the using namespace
statement to make it work?
- A return statement doesn't have to be at the end of the function
if the function has finished its business before the end. Take a look
(and run) List0506.cpp for a typical example using if
and else.
- The program List0507.cpp illustrates the use of default
parameter values. The function AreaCube calculates the area
of a cube based on the length, width, and height, but is defined so that
you can call it with one, two, or three arguments. If you call it with two
values, to take an example, those will be used for the length and the
width while the height will be equal to the default value
that is given in the function prototype (in this example, height = 1
is the default). Compile and run the program, then modify it so that
length also has a default value. What will happen if you call
AreaCube() (i.e., with no arguments; you have to add the
appropriate lines to the code)? [Note: you can't assign a default value
to an argument without assigning default values to all of the following
arguments.]
- In List0507.cpp, if we called AreaCube with arguments
that were declared as double instead of int, we would
have gotten an error. But suppose we want the option to have a function
that could take either argument. We can do this with what is
called function "polymorphism" or function "overloading".
An example is given in List0508.cpp
with a contrived example of a function that returns twice the passed
argument. Note that a separate function is given for each variable type,
but they all have the same name Double. Extend the code with
an additional Double function that takes a double argument
and returns a double result. If you get stuck, an answer is
in List0508ans.cpp.
- For short functions like Double, it is best to declare them
as inline functions. This just means that the compiler
will try to make it very efficient to call the function. This is all
transparent to you, so all you have to do is put inline in
the function prototype. See List0509.cpp for an example.
(Notice, by the way, that the prototype doesn't need to have names for
its arguments, but we recommend using them anyway.)
If you have time, add an inline function to calculate the square
of a function (call it Sqr). Can you make it work with
either int or double arguments?
- The final topic is recursion, which refers to a function
calling itself (!). The Fibonacci series is defined as
1, 1, 2, 3, 5, 8, ..., where the next number in the series is found
by adding the two previous numbers. To do that in C++, check out
List0510.cpp. Notice that the fib function
calls itself! Can you write a recursive function to calculate
the factorial of an integer?
- Here are
some of the Day 5 Quiz questions to try
(answers are in the handout from Session 1):
- Why not make all variables global?
- What are the differences between the
function prototype and the function definition?
- Do the names of parameters have to agree in
the prototype, definition, and call to the function?
- If a function doesn't return a value, how do you
declare the function? [You'll have to look this one up
in the answers!]
- What is a local variable?
- Exercise: Write a function that takes two unsigned short integer arguments
and returns the result of dividing the first by the second. Do not do the
division if the second number is zero, but do return -1. Then write a main
program that asks the user for two numbers and calls the function you wrote.
Print the answer, or print an error message if you get -1.
[The answer is in Ex0506.cpp.]
- Exercise: Write a program that asks for a number and a power. Write a
recursive function that takes the number to the power. Thus, if the number is
2 and the power is 4, the function will return 16.
[The answer is in Ex0507.cpp.]
Day 6: Understanding Object-Oriented Programming
We'll just get started here, and continue in Session 4.
You can find more information about these things in the
online version of Day 6 (please read this if you get a chance).
- In C++, we can declare our own variable types that are more complex
than int and double and so on. For example, suppose
we wanted to write a program that kept track of information about cats,
such as their age and weight. We could do that with a "structure"
(which is declared with struct) or with a "class". A class
will be more powerful, because we'll also be able to define functions
that are also associated with the cats. Take a look at List0601.cpp
as our first example.
- At the top is something like a function prototype,
but which declares the class Cat. Within this declaration
are the two variables for the age and weight; these are called
"member variables". They are declared as public: variables,
which will mean that they can be accessed by the main function
(and other parts of the program).
- In the main function, we use the Cat class
to declare the cat Frisky. (This is just like declaring
the variable radius to be a double with double radius.)
- To assign a value to a variable in the class, we use the
"dot" notation; look how Frisky's age is assigned and then
used in the output statement. Try adding code to declare the weight
to be 20 and to print it out in main.
- Try adding another public variable for the length of the
cat (declare it as a double). Add code to main to set the
length and then print it out.
- Exercise: Write the code that declares a class called Employee with these
public data members: itsAge, itsYearsOfService, and itsSalary.
Set values in the main
program and check that you can print them out.
(Next time we'll talk about making the data "private", so it is
protected and "encapsulated", and we'll "accessor" functions to set
and get the values.)
C++ Seminar: 1094 Session 3.
Last modified: 12:28 pm, November 08, 2006.
furnstahl.1@osu.edu