Back up to Programming Main Site
C++ Programming Examples and Exercises
Part 0: Hello, World!
- Hello World Example: Use this simple example to
ensure that you are able to compile and run programs with the development
environment. To compile and run with DevC++:
- Download the program (right-click, save link target as...)
- Save to your computer - It is recommended that you make a new
folder (directory) for each example.
- Open the file in DevC++.
- Go to the "Execute" menu. Click "Compile and Run".
Part 1: Program Basics, Variable Declaration, Arithmatic Operators, and Comments
Part 2: Conditions and Loops
Part 3: Functions and Arrays
- Functions and Arrays Example:
This example illustrates the use of functions and arrays.
- Functions: Functions are a way to enclose a commonly used part
of a progam into something that can be re-used many times. Functions also
give us one way to solve a small part of a very large problem. Functions
should be:
- Simple: A function should perform one simple task that can
be easily described.
- Well documented: A function should include good
documenting comments about what it does and what value(s) it operates on.
- Function structure: A function takes arguments to operate on
and returns one value. In C++, functions have two distinct components:
- Function Prototype: The prototype is a brief description
of what the function does. It tells what the function name
is, what argument types it expects, and what type of value
the function returns. It tells us what the function is
and what it does, without actually having the code that does
it! See the top of the example for the "distance" function's
prototype.
- Function Definition: The definition of a function
contains the actual code that performs the work of the
function. The beginning of the definition matches the
prototype exactly. See the example for the definition of
"distance".
- Function arguments: The function arguments let the user of
the function (the caller) pass specific values for the
function to work with. Each time the caller uses the function,
different values can be given in the arguments. Inside the function,
the arguments can be used just like any other variable.
Note: The functions we are doing now are called pass-by-value.
This means that if the function modifies (assigns to) the arguments,
the modifications are not visible to the caller. The function
is effectively working on a copy of the argument!
- Function return: A function can return a value to the code using
the function (the caller) by using the return keyword.
See the example and the next item for how a caller uses the returned
value.
- Using a function: Once you have a function, you use it by
"calling" it. You call a function in code by using the name of the
function, followed by the arguments you want to call it with in
parenthesis. The return value can be saved by assigning to
a variable! See the example. Here's another example:
/* Prototype for a function to compute x to the second power */
int square(int x);
// ... somewhere else in the file, perhaps in main function ...
int squareme = 30;
int squared = square(squareme); // Call square with value of
// squareme. Assuming square
// works like it says it does,
// squared will be 30 * 30
squared = square(10); // Example of calling with a literal
- Arrays: Arrays are simply a set of variables held together
in the computers memory. We can use arrays as an easy way to hold
a series of related numbers. In the example, the array "points"
holds a series of points we want to move between.
- Array Declaration: We declare arrays just like variables, except
that we add to the end the size (number of elements). In the
example, we make an array that has 8 integers.
Just like with variables, we can chose to initialize the array
immediately (as in the example) or to wait until later. Again, like
with variables, the value of the array elements are undefined
until they are given a value!
To give an array all its values at once, we can use the notation in
the example; a series of comma-separated values in braces.
- Array Indexing: We use or assign to one element of an
array by indexing the array. This is done by using the array name
followed by an index in brackets []. Array elements are numbered starting at
zero, and continue up to the size of the array minus one. For
example, a 10-element array has indexes 0 through 9. Here are a few
examples:
int example[5] = { 10, 20, 30, 40, 50 };
x = example[0] + example[2]; // x = 10 + 30
example[2] = 6; // Change 3rd element to 6
y = example[1] + example[2]; // y = 20 + 6
z = example[5]; // PROBLEM! This will compile but
// run unpredictably! There is no
// 6th element!
- Functions and Arrays Exercises:
This exercise starts with you writing a function to raise a
number to a power. It continues to have you change the values
used to test the function from those provided to a different set.
Do these in order!
The places to insert code for each part are noted in the comments!
- Part A, Functions: The exercise has an empty function for
Raising a number to a power. You need to create this function.
Don't forget to return your result!
Hint for those reading directions!
Use a loop!
When completed, you should get output like this:
1 raised to the 1 is 1
2 raised to the 2 is 4
3 raised to the 3 is 27
...
9 raised to the 9 is 387420489
- Part B, Arrays: Right now, your main function tests
using numbers 1 to 9, raising each to itself (as above).
Change it to compute and print the following:
10 raised to the 3 is 1000
7 raised to the 2 is 49
2 raised to the 6 is 64
1 raised to the 70 is 1
5 raised to the 3 is 125
6 raised to the 4 is 1296
Hint again! Use two arrays and a loop!
Part 4: If-Else
- If-Else Example:
This example illustrates the use of if and else by telling you if a number
is even or odd!
- If-Else: We use 'if' and 'else' in a program to make decisions
about what the program should do next. The general structure of an if-else
is shown below:
if (test) {
/* all the code here gets executed if 'test' was true! */
...
} else {
/* all the code here gets executed if 'test' was false! */
...
}
/*
* Either way, we end doing code here after doing either the 'if' block
* or the else block!
*/
...
The "test" is any of the tests we used for loops, such as all the numeric
comparisons we talked about.
The "else" section is optional! If you leave it out and the test is
false, the if block is just skipped and execution continues after the if
block!
Short Version: If you do only one statement in the body of the if
or else, you can leave out the braces {}!
See the example above for a working program, and here's a shortened
concrete example. This basically says "if the money I have is more than 10,
then go out and buy some lunch and feel full. Otherwise, fell hungry! If I
feel really hungry, then my stomach grumbles!"
int money = check_wallet();
if (money > 10) {
money -= buy_lunch();
stomach += 20;
} else {
stomach -= 20;
}
if (stomach < 15) {
grumble();
}
- If-Else Exercise: This exercise requires
you to make a function to compute absolute value. Numbers for test code
in the main function have been provided for you. Comments show where
to insert your code. You need to do the
following (easiest if you do these in order!!!):
- Create a function prototype for your absolute value function.
Put the prototype near the comment at the top of the file.
- Create the definition of your function. Do this near the comment
at the bottom of the file.
- Finish the test code in the main function to call your
function using the provided array of test values.
Part 5: Data Types
Part 6: Multiple File Programs, Classes and Objects
- Classes and Objects Example: This is our
first example of a multi-file program. It is a ZIP file. Open the zip file
and extract everything to a new folder. Then open Dev C++ and make a new
C++ project. Add all the files to the project and save the project. It
should then compile and run.
- Classes: A class is a way to group together,
logically, program data (variables) and operations (functions) into one
unit or module. Classes enable us to separate out related parts of a
program, and to think about the program as a set of operations on various
objects. Classes:
- Are a way to define our own data type. Up until now, we've only used
the basic, primitive data types in C++ (int, long, float, etc). By
defining a class, we can make our own, more complex types to represent
different things.
- Enforce the "Object Oriented" approach to programming. This means
we take the problem our program is seeking to tackle and break it
into distinct modules to handle various aspects of the problem.
Our program manipulates these modules, or "objects", in a meaningful
way to solve the problem at hand. Before "Object Oriented"
programming, the main model was procedural programming, where you
basically write a bunch of functions and pass around data to operate
on.
- Give us one more way to split up a difficult task into pieces that can
be worked on by multiple people in a larger group. Each person or
small group can be writing well-defined modules that can be hooked
together at a later time.
- Objects: A class is just a plan or blueprint. It tells the
compiler what your new user-defined type will do and how it does it. When a
part of your program wants to use a class, it creates an object, or instance of
the class. For any given class you could create hundreds of objects and be
using them all in various parts of your program.
- Class Definitions: A class definition provides the overall
interface of a class, without defining how each of the classes
operations actually perform their work. This is like a prototype for a
function - the function prototype gives us the interface to call the
function, but doesn't actually contain the code that does the work of the
function.
Class definitions are typically placed in a ".h", or header, file. This
file can be referenced by any part of the program that uses the class. The
actual programming code that implements the functions of a class are
usually defined separately in a ".cpp" file.
The example has one .h file to define a class, a .cpp file containing the
actual code that implements the class's functions, and a .cpp file with a
main method that uses the class in various ways.
- Structure: Classes are made up of these parts - refer to the
example program to see each of these:
- Data Members: These are variables the class uses over the life of the
object - they are usually important properties or state information about
the object. The data can be labelled private, which means that the only code
that can modify it is functions that are a part of the class, or public,
which means any code in the program can "reach into" the object and modify
the data.
Best practice is usually to use private variables to limit the way that your
object can have its data modified.
- Member Functions: Member functions are the functions that are
defined as part of the class. They can operate on all the classes data.
Other than that, they are just like the functions we have been writing!
Sometimes these are called methods. You prefix the name of your member
function with the class name and two colons to say that this function is a
member of your class, not just an ordinary function:
int ordinaryFunction(int someArgument) {
// ...
}
int MyClass::memberFunctionName(int someArgument) {
// ...
}
- Constructor: This is a special function that is called when you
make an object of the class. The constructor gives you a place to set
the data members to meaningful initial values. This function always
has the same name as the class, and has no return value. (see example)
- Destructor: Another special function, this is called when
an object of the class is destroyed. This lets you clean-up any
data members that need special attention. Like the constructor, the
destructor has no return value. It is named the same as the class with a
tilde (~) character in front (~MyClassName) and takes no arguments.
- Creating Objects of a Class: You create objects
of a class by declaring them, just like the integer or float type, except
that you can pass arguments to the constructor of the class in
parathesis:
int someInteger;
// Assuming I have a class named "Speaker" somewhere, with a constructor
// that takes a single float argument ( Speaker(float volume) )
Speaker leftSpeaker(10.5);
You do not need to call the destructor for a class - it gets run
automatically when your object is destroyed (at the end of the function or
code block that is using it, for example).
- Calling member functions of a class: You can call any member
function of a class by using the member operator, which is a single period
(.). If my Speaker class from above has member function to change volume
called setVolume taking a single float as an argument, then I can call it
with:
leftSpeaker.setVolume(3.2);
- Documentation: Class definitions should be well documented using
comments to allow other programmers to use your class without having to read
all the code. There are many tools on the internet that will produce nice
documentation from specially formatted comments. One such tool is Doxygen.
- Classes Exercise:
We will work together to come up with a class definition of a cube. You
will implement the class using the class definition as a guide.
Based on the class we developed, here is a main function which will test
your class. You should get output like this:
My cube of side 30 has surface area of 5400 and volume of 27000
My other cube of side 11 has surface area of 726 and volume of 1331
Part 7: Multiple File Programs, Classes and Objects
- Class Heirarchy: Sometimes our program will need several modules
which can share some common data, functionality, or other traits. We can
make several classes build on or share their implementation code or a common
interface to achieve this. You can have several classes that "derive from"
or "inherit from" a common parent class (also called a super-class). All
the child classes can share the common interface (member functions) of the
parent class, and even benefit from any common code in the parent class.
Sub-classes can also extend the functionality of a basic parent class in
meaningful ways.
Sub-classes can then, in turn, be subclassed further as needed to build
a whole tree of more and more specialized or refined classes. The
- Sub-Classing/Inheritance: To create a sub-class of a class, you
specify the name of the super-class you are inheriting from after a colon in
the class definition:
class MySubClass : public MySuperClass {
...
};
- Virtual member functions: A "virtual" member function is a
member function that can be changed or extended in a sub-class. Non-virtual
functions of a class are fixed operations that cannot be changed or
extended. Generally, when you write a class that will eventually be
extended, you will make all the functions virtual.
class MySuperClass {
virtual int myMemberFunction(int someArgument);
};
- "Pure" Virtual member functions: A "pure" virtual function is a
way to have a super-class give an interface to a function without actually
making a function. This makes the super-class be "abstract" since it is no
longer fully defined, but still, it lets other parts of a program work
with a common interface regardless of the subclass that the object is an
instance of. The subclass(es) provide their implementations of these
otherwise empty functions. To declare a function as "pure" you add "= 0" to
the end of its prototype in the class definition:
class MyAbstractClass {
virtual int myPureFunction(int someArgument) = 0;
};
Back up to Programming Main Site