C++ Programming Exercises
C++ Programming Exercises
C++ Programming Exercises
Summary
Try to work through the exercises on each lesson before moving onto the next. You may find the
following web resource helpful:
http://www.cplusplus.com
Provides tutorials, a users forum and documentation on the most widely used libraries including
strings, I/O and the STL.
Lesson 2 - Functions
1. Not every function we may write has to return a value. Write a function called product which
accepts two integers as arguments (like add and minus) but returns no value. In the function
body the product function should use cout to print the product directly to screen.
2. Write a function called quotient which should take a double argument and an integer argument.
This function should also return a double data type. Now if you provide the quotient function
with the values 5 and 3 say, it should return the value 1.66667 or there-abouts. Test this by
calling the function within a cout statement. Once this works change the double argument to
an integer and notice the result; why does quotient no longer return a double?
3. Write a calculator program which asks for two numbers and a mathematical operator (represented as a char type. Depending on the operator (+, -, * or /) call the appropriate function
and display the result. Use a switch statement to filter the choices.
2. Write another function that continuously asks for numbers (use cin), until the user provides a
negative number. Youll need some kind of loop and you should make use of the function you
created in Exercise 1.
3. Recursion is an alternative to writing loops where a function calls itself. Write another version
of the factorial function that uses Recursion instead of loops. What is one advantage and one
disadvantage of using Recursion as an alternative to loops?
Lesson 4 - Pointers
1. Given that a pointer holds the value of a memory address, why is it permitted to add an integer
data type value to a pointer variable but not a double data type?
2. Suppose we have a pointer to float data type which contains the memory address value 100.
If we add the integer value 3 to this pointer, what will be the value of the pointer if float data
types are 4 bytes in length?
3. Write a function called swap that takes two pointers to integer arguments and returns void.
Inside the function, swap the values of the integers. Write a main function that calls this
function and verify that the value of the integers has indeed been swapped after this function
call.
4. Pointer arithmetic can be used to access specific values when a sequence of such values exist.
Create an array of 10 integers numbered 1 to 10 with the syntax:
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
Now create a function which accepts a integer pointer as its argument and returns void. Implement the function to print out the even numbers of the array using pointer arithmetic.
Lesson 5 - Memory
1. What is Stack Overflow and why might a Recursive method be susceptible to this kind of
problem?
2. Memory Leaks are a problem associated with which type of memory? What must you do to try
and avoid causing Memory Leaks in your programs?
3. Amend the code to create a char variable on the stack and a string variable on the heap.
4. Examine some of the other options provided when calling new and delete. Amend the code to
create an array of 10 integers on the heap. Ensure that you release the memory you created
using the correct form of delete.
5. Tree structures are a widely used data construct in programming (including games programming). One such tree structure is a Binary Search Tree which stores data in a manner that
allows fast searching. Familiarise yourself with this technique and write your own Binary Search
Tree using the code below to help you:
1
2
3
4
5
6
7
8
9
10
11
12
13
struct node {
int value ;
struct node * left ;
struct node * right ;
};
struct node * root = NULL ;
// i m p l e m e n t the f u n c t i o n s d e s c r i b e d by these h e a d e r s
void i n s e r t _ i n t e g e r ( struct node ** tree , int value );
void p r i n t _ t r e e( struct node * tree );
void t e r m i n a t e _ t r e e ( struct node * tree );
14
15
16
17
18
19
20
21
/* *
* Main f u n c t i o n
*/
int main () {
// call your i m p l e m e n t e d f u n c t i o n s here to test
// the binary search tree
return 0;
}
memory.cpp
A Tree can be considered as a collection of nodes, linked to one another via pointers. You have
been given the definition of a node in the Binary Search Tree. This is in the form of a struct;
a record for holding together related variables.
You build the tree recursively using the insert integer function. You will need to find the
correct place to insert a node to hold the new value, then create a node on the heap.
The print tree function should print out the values in the tree in ascending order, and the
terminate tree function should reclaim all the memory used in the tree.
Lesson 7 - References
1. What is wrong with these lines of code...
1 int & e m p t y _ r e f e r e n c e ;
2 int & u n n a m e d _ r e f e r e n c e = 5;
references.cpp
2. what is the value of x ref after these lines of code execute...
3 int x = 3 , y = 4;
4 int & x_ref = x ;
5 x_ref = y ;
references.cpp
3. Why should you never return a reference type from a function, if the return value is local
variable of that function?
3
4. Create another function called swap which swaps two characters and returns void. Ensure that
your function swaps the original variables and does not create copies. Call this function from
the main function to make sure it works.
5. Create a global variable in the form of an array of 10 integers, i.e:
int nums[10] = {7,3,5,2,1,4,6,9,10,8};
and create a new function which sorts the numbers of the array into ascending order; use the
swap ref function to help you.
Lesson 8 - Arrays
1. Amend the code to create an array of characters on the stack, which contains your full name
(including room for a space between your first and last names). Now create a function which
prints to screen your name using the array you just created.
2. Create two arrays on the heap called first and last. Copy your first name into the first
array and your last name into the last array.
3. Create a battleship game using a 2-dimension array of booleans to represent the battle-ground.
Use appropriate dimensions (say 5 by 5) and denote the presence of your battleship by setting
the boolean values to true in array indices where your battleship is situated. Provide the user
with a certain number of guesses to pick coordinates within the 2-D array. Your program should
keep track of the number of guesses made and inform the user whether a guess is successful or
not.
Lesson 9 - Classes
1. Modify the Enemy constructor so that the score field is set to an inital supplied value like
hit points.
2. Create a new class called player which possesses the same fields and methods as enemy. In
addtion, give the player a string field called name, use the std::string class. Create name
on the heap and provide methods to get and set the name of player.
3. Re-write the Binary Search Tree code from Lesson 5 to create a Binary Search Tree class.
Implement a Constructor, Destructor in addition to methods which allow an integer to be
inserted and the tree to be printed to screen. Implement a search method which returns true if
a supplied value is present in the tree, false otherwise.
4. Modify the battleship game in the previous exercise to use classes. Create a battleship class
which possess a hit-points and score field. When the user lands a shot, the score field should
be increased until hit-points is reached. This should denote that your battleship has been sunk.
How you represent the battleground is your choice.
Lesson 10 - Inheritance
1. If we did not make the Enemy Class Destructor virtual, how might a memory leak be
introduced into our program when the ArmedEnemy class Destructor is called?
2. How does giving a class one or more virtual methods, affect the memory requirements for the
C++ compiler compared to a class which possesses no virtual methods?
3. Create a Boss class which inherits from the Armed Enemy class. Implement an additional
armour level field for the Boss class and provide suitable getter and setter methods. Create a
Boss Object in the main function to test the functionality of your Boss class.
4. By taking advantage of inheritance and polymorphism we can group together objects of
different classes and perform common operations on them. Make the Enemy class abstract.
Create an array of 10 ArmedEnemy objects and a Boss object. With the help of polymorphism, create a single array of references to the ArmedEnemy and Boss objects. Iterate
4
through the array decrementing the hit point value of each reference; use a single function for
decrementing which accepts a Enemy reference as its argument.
5. Create an abstract Comparable class. Any class which inherits from Comparable should
implement a compare to method which has the following header:
1
2
3
4
Lesson 11 - Templates
1. When does the Compiler usually perform compilation of a Template class?
2. Given how the compilation process is different for Templates, why might you place the Templates
class method definitions in the header file with the class declaration?
3. Create a Matrix of characters using the template class in this lesson. Populate the matrix so it
contains the characters:
a, b, c,
d, e, f,
g, h, i
I.E. the character at index [2][2] should contain e.
4. Re-implement The Binary Search Tree class as a template type.
5. Create your own stack container as a template. Provide methods to push, pop, get the size
and check if the stack is empty.
Lesson 15 - Threads
1. Create a hello world thread which executes a loop, printing to screen the message Hello from
Thread (handle) 10 times. Extend the Thread class provided.
2. Create a thread-safe Binary Search Tree class which uses a single lock to ensure only one thread
at a time can insert comparable objects (this is coarse-grained locking).
3. Create a thread-safe Binary Search Tree class which uses a lock-per-node so that threads can
insert comparable objects concurrently (this is fine-grained locking).