You are on page 1of 54

Intermediate C++ Programming

Summer Camp Teachers Guide

Copyright American Computer Experience, 2001

Intermediate C++ Programming

Table of Contents
Course Description

Page 3

Goal of the course

Page 4

Learning Objectives

Page 4

Materials and Resources

Page 5

Pre-Requisite Skills and Knowledge

Page 6

Lesson 1 Introduction

Page 7

Lesson 2 Loops

Page 9

Lesson 3 Arrays

Page 16

Lesson 4 Structures

Page 22

Lesson 5 Unions & Enumerations

Page 28

Lesson 6 Pointers

Page 31

Lesson 7 Functions

Page 36

Lesson 8 Namespaces

Page 42

Lesson 9 Preprocessor

Page 45

Lesson 10 Dynamic Memory Allocation

Page 50

Copyright American Computer Experience, 2001

Page 2 of 54

Intermediate C++ Programming

Course Description
This section provides an overview of Intermediate C++ Programming. Use this section to
become familiar with the course objectives, content and methodology.
In your first session with your students, it is important to cover the objectives in terms they
can understand. Tell them what they are going to learn and what they should be able to do at
the end of the course or lesson. It is also important at this point to set expectations for
learning, individual and group activities and for appropriate behavior.
This course includes in-depth coverage of concepts learned in the Beginner C++ course
(advanced loops, advanced functions, etc.). It also covers new, more advanced topics such as
pointers, structures, etc.

Copyright American Computer Experience, 2001

Page 3 of 54

Intermediate C++ Programming

Goals
The goals of a course encompass what the student will achieve by accomplishing all of the
objectives of the course or lessons.

This course is intended to strengthen the knowledge of basic concepts learned in the ACE
Computer Camp Course Introduction to Programming with C++.
Students should be able to easily combine two or more concepts when solving a problem
using C++.
More advanced topics will be covered, which will allow for more flexibility in problem
solving.
The course will prepare the students for the Advanced C++ Programming course, which
will explore the vast concept of Object Oriented Programming.

Learning Objectives
At the end of this course, the students should be able to:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.

Understand and use the advanced features of iteration statements.


Master the use of loops in C++ programs.
Define and understand the concept of multidimensional arrays.
Use 2 dimensional arrays in C++ programs.
Understand the concept of structures and it is translated into a programming concept.
Declare and use a structure.
Use structures as elements of an array.
Understand both concepts and their relationship to structures.
Implement unions and enumeration in a C++ program.
Define, understand and describe the main function of pointers.
Extract the address of any variable.
Use arrays as function parameters.
Implement functions within structures as data members.
Utilize pointers within functions.
Define and understand namespaces and their purpose.
Declare and implement a namespace in C++.
Understand the purpose of the pre-processor.
Use preprocessor directives within a C++ program.
Comprehend the concept of conditional compilation.
Distinguish between the heap and the stack.
Understand the purpose for creating dynamic objects
Use the new and delete operators to create and destroy a dynamic object.
Create dynamic arrays.

Copyright American Computer Experience, 2001

Page 4 of 54

Intermediate C++ Programming

Materials and Resources


Required and/or recommended instructional materials:
Computer
A C++ compiler

The following is a list of materials and resources that may be available for you to use, if you wish.
You may use these resources to either supplement your own learning, incorporate into your lesson
plans, or both. You may also feel free to create or include any other resources as long as they
contribute to the students learning experience and meet the stated objectives of this course.
C++ Online References:

http://www.cplusplus.com/doc/ - tutorial
http://www.wcug.wwu.edu/~anton/cpp/
http://www.linuxdoc.org/HOWTO/C++Programming-HOWTO.html
http://www.frontsource.com.pk/html/vc.html
http://msdn.microsoft.com/library/default.asp?URL=/library/devprods/vs6/visualc/vcedit
/vcovrvisualcdocumentationmap.htm

Practical C++, by Rob McGregor


Computer Science Logic, by Egon Brger, Hans Kleine Bning, Gerhard Jger
Introduction to Logic Design, by Sajjan G. Shiva
Programming Languages: Implementations, Logics and Programs, by Manuel
Hermenegildo, S.Doaitse Swierstra, G. Goos, J. Hartmanis, J. Van Leeuwen
The C++ Programming Language Special Edition, by Bjarne Stroustrup
Programming and Problem Solving With C++, by Nell Dale, et al

Books:

Copyright American Computer Experience, 2001

Page 5 of 54

Intermediate C++ Programming

Prerequisite Skills and Knowledge


Some courses taught at the ACE Summer camps may require that the students begin the
class having already learned certain topics, either by having previously taken other courses or
through self-study. In your first session with your students, please ensure that they do have, as a
minimum, the skills and knowledge listed below. If they do not, please consult your Academic
Director.

ACE Computer Camp Course Introduction to Programming with C++.

Copyright American Computer Experience, 2001

Page 6 of 54

Intermediate C++ Programming

Lesson 1 Introduction

Learning Objectives
By the end of this lesson the students should be able to:
1. Recall the concepts covered in the Beginning C++ course.
2. Complete one or more basic exercises for a more thorough review of these
concepts.
3. Gain an understanding of the topics covered in this course.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Variables
o Compile
o Built-in Data Types
o Derived data types

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.

Copyright American Computer Experience, 2001

Page 7 of 54

Intermediate C++ Programming

o Present the content


In the Beginner C++ course, the following concepts were covered:

C++ Syntax (curly brackets, semi-colon, case sensitivity,


comments)
Text I/O with cin and cout (basic variables, output text to the
screen, store user input)
C++ Data Types (integer, float, character, Boolean)
Functions (return value and void functions, functions that accept
parameters)
Operators (arithmetic, logical, relational)
Conditional Expressions (if and switch statement)
Iteration Statements (for, while and do while loops)
Arrays (one-dimensional)

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
o During or immediately following the students performance of the new skills,
reinforce what they have learned by providing informative constructive feedback.
It is also important here to take note of whether the student has retained
information presented in prior lessons and record this information in a checklist or
by another appropriate method.

Copyright American Computer Experience, 2001

Page 8 of 54

Intermediate C++ Programming

Lesson 2 Loops

Learning Objectives
By the end of this lesson the students should be able to:
1. Recall iteration statements and their application
2. Understand and use the advanced features of iteration statements.
3. Master or almost master the use of loops in C++ programs.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Comma operator
o Step size

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.
Review briefly the three loops discussed in the Beginner C++ course.
Talk about the comma operator when defining multiple variables of the
same type. Discuss the uses of the comma operator with loops.
Copyright American Computer Experience, 2001

Page 9 of 54

Intermediate C++ Programming

o Present the content


This lesson presents the advanced features of iteration statements. These
features are relatively simple, thus the lesson should be focused on
ensuring that the students have almost mastered the use of loops.
Besides mentioning the importance of loops, specify that throughout the
rest of this course loops will be used frequently.

2.0 Loops
2.0.1 Review of the three main loop structures.
Recall the three looping structures learned in Unit 01. These are:
- The for Loop
- The while Loop
- The do while Loop

Entry-Condition Loops
int i=0;
for(i=0; i<5;i++)
{
cout << i << \n;
}

Both the for loop and the


while loop check that i < 5
before they execute the
cout statement.

Exit-Condition Loops
int i=0;
do
{
cout << i << \n;
}
loop(i<5)

The do while loop will


execute the cout statement
at least once before
checking if i < 5.

Example using the for Loop:


/* This program will output the numbers from 1 to 10 */
#include <iostream.h>
void main()
{
int x;
for(x=1;x<11;x++)
{
cout << x << \n;
}

Copyright American Computer Experience, 2001

Page 10 of 54

int i=0;
while(i<5)
{
cout << i << \n;
i++;
}

Intermediate C++ Programming

}
Output:
1
2
3
4
5
6
7
8
9
10

Example using the while Loop :


/* This program will output the numbers from 5 to 1*/
#include <iostream.h>
void main()
{
int x=5;
while(x>0)
{
cout << x << \n;
x=x-1;
}
}
Output:
5
4
5
2
1

Example using the do while Loop:


/* This program will output the numbers from 1 to 5 */
#include <iostream.h>
void main()
{
int x=1;
do
{
cout << x << \n;
x++;
}
while(x<6);
}
Output:
1
2
3
4
5

Copyright American Computer Experience, 2001

Page 11 of 54

Intermediate C++ Programming

2.0.2 Advanced Loop Concepts.


The comma operator
In order two combine two or more expressions within a for loop, we will use the
comma operator. In C++ the comma is very rarely used as an operator. It is
mostly used as a separator (ie. int x,y ).
For loop syntax using the comma operator:
for(declare_expressions ; expressions_upperlimit; increments)
{
Upper_limit1, Upper_limit2, . .
expression1, expression2, .
}
expression1 will be evaluated before
expression2.

Example:
#include <iostream.h>
int main()
{
//This program illustrates the implementation of the comma operator
int x,y; //note that here the comma is just a separator
cout << " X
Y\n-------\n";
for(x=0, y=9; x<10, y>-1; x++, y--)
{
cout << " " << x << " ";
cout << "| " << y << " \n";
}
return 0;
}
Output:
X
Y
------0 | 9
1 | 8
2 | 7
3 | 6
4 | 5
5 | 4
6 | 3
7 | 2
8 | 1
9 | 0

Change the step (increment) size


Copyright American Computer Experience, 2001

Page 12 of 54

Intermediate C++ Programming

Loop structures have been thoroughly explained and most of their functions
uncovered. However, the for loop has yet another feature that has not been
discussed.
The step size, is the increment expression found in a for loop. So far, the
counter variables have been incremented by 1, such as: x++ or x=x+1, etc.
Changing the step size, means changing the increment value of a counter
variable.
Example:
#include <iostream.h>
int main()
{
//
int x;
cout << " The odd numbers from 1 to 20: \n";
for(x=1; x<20; x=x+2) //increment value is 2.
//alternate statement:
//for(x=0;x<20;x=2*x+1)
{
cout << " " << x << " \n";
}
return 0;
}
Output:
The odd numbers from 1 to 20:
1
3
5
7
9
11
13
15
17
19

Note: For different step sizes, you can use the assignment operators. For
example, x=x+2 will be written as x+=2, etc.
Text input with loops
Loops are useful in reading user-input or text files character by character.
For example:
Copyright American Computer Experience, 2001

Page 13 of 54

Intermediate C++ Programming

#include <iostream.h>
int main()
{
int charCounter=0;//declare and initialize the character counter
char ch;
cout << "==-* 00 Rating Agent Report *-== \n\n;
cout << Please type the report below::\n(..to end type \'@\'
..)\n\n";
cin >> ch; //record the first character
while(ch!='@')//use a while loop to record all input before the @
{
cout << ch; //display the recorded characters
charCounter++; //increment the counter by 1
cin >> ch; //record the next character
}
//the line below displays the number of characters recorded.
cout << "\nYou have entered " << charCounter << " characters!\n";

return 0;
}
Sample Output:
==-* 00 Rating Agent Report *-==
Please type the report below::
(..to end type '@' ..)
This 006&1/2 reporting on yet another successful mission!@
This006&1/2reportingonyetanothersuccessfulmission!
You have entered 50 characters!

Note: In order to read ALL characters, including spaces, you must use the
cin.get(ch) function. This function reads any character and assigns it to the
variable in the parenthesis.
The cin.get version of the above example:
#include <iostream.h>
int main()
{
//
int charCounter=0;
char ch;
cout << "==-* 00 Rating Agent Report *-== \n\n;
cout << Please type the report below::\n(..to end type \'@\'
..)\n\n";
cin.get(ch); //record the first character even if it is a space.
while(ch!='@')
{
Copyright American Computer Experience, 2001

Page 14 of 54

Intermediate C++ Programming

cout << ch;


charCounter++;
cin.get(ch); //record the next character
}
//this time the spaces are recorded, thus the number of character
will change
cout << "\nYou have entered " << charCounter << " characters!\n";
return 0;
}
Sample Output:
==-* 00 Rating Agent Report *-==
Please type the report below::
(..to end type '@' ..)
This 006&1/2 reporting on yet another successful mission!@
This 006&1/2 reporting on yet another successful mission!
You have entered 57 characters!

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
Once again, loops as a concept are very widely used in C++ programs.
The point of the lesson is to provide students with the extra practice
needed to prepare them for the following lessons.

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Create a program similar to the content example that will display the
numbers from 1 to 10 in one column, the even numbers from 1 to 10 in the
second column and the odd numbers from 1 to 10 in the third column. Use
a for loop with a comma operator: (for(x=1,y=2, z=1; x<11,
y<1, z<11; x++, y+=2, z+=2) ). The variables x, y and z
are assumed to be declared.
Have students work in pairs or small groups to create a program that
stores a word in an array and then uses a loop to print out the letters of
the word in a column followed by another column where the letters are
reversed.
o During or immediately following the students performance of the new skills,
reinforce what they have learned by providing informative constructive feedback.
It is also important here to take note of whether the student has retained
information presented in prior lessons and record this information in a checklist or
by another appropriate method.

Copyright American Computer Experience, 2001

Page 15 of 54

Intermediate C++ Programming

Lesson 3 Arrays

Learning Objectives
By the end of this lesson the students should be able to:
1. Recall the concept of arrays as taught in the Beginner C++ course
2. Define and understand the concept of multidimensional arrays.
3. Use 2 dimensional arrays in C++ programs.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Multidimensional structures
o Tables

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.
Talk about the relationship between loops and arrays.
Discuss the purpose of using multidimensional arrays.
o Present the content

Copyright American Computer Experience, 2001

Page 16 of 54

Intermediate C++ Programming

Ensure that students gain more practice with basic arrays, thus are closer
to fully understanding the concept they are dealing with.
Once again, talk about combining loops and arrays and how they are
often used together in a C++ program.
Describe multi dimensional arrays.
Introduce syntax and examples of 2 dimensional arrays.

3.0 Arrays
3.0.1 Review of one-dimensional arrays.
Definition: Arrays are derived data types that store multiple values under the
same name.
Syntax: data_type array_name[number of elements];
Array Example:
#include <iostream.h>
void main()
{
//create an array of five elements of type char.
char letters[5];
cout << Think of a five letter word.\n;
cout << Enter the last letter of the word: ;
cin >> letters[4];
cout << Enter the fourth letter of the word: ;
cin >> letters[3];
cout << Enter the third letter of the word: ;
cin >> letters[2];
cout << Enter the second letter of the word: ;
cin >> letters[1];
cout << Enter the first letter of the word: ;
cin >> letters[0];
cout << The word you thought of is:
for(int x=0;x<5;x++)
{
cout << letters[x];
}
}
Sample Output:
Think of a five letter word.
Enter the last letter of the word: e
Enter the fourth letter of the word: s
Enter the third letter of the word: u
Enter the second letter of the word: o
Enter the first letter of the word: h
The word you thought of is: house

Copyright American Computer Experience, 2001

Page 17 of 54

Intermediate C++ Programming

3.0.2 Introduction to multi-dimensional arrays.


A one-dimensional array can be pictured as the row of a spreadsheet. A two
dimensional array, is very similar to an HTML table or a spreadsheet, having both
rows and columns of data. Thus, multi-dimensional arrays can be visualized as
multiple dimension entities.
Although arrays can have 3, 4 and more dimensions most programmers use
arrays of, at most, 3 dimensions. This chapter will focus on 2 dimensional
arrays.

3.0.3 Declaring a 2-dimensional array


Columns

Syntax:
data_type array_name[rows_number][columns_number];

Rows

Declare and assign value:


int table[3][4];
table[0][0]=1; //assigns 1 to the cell with
//address 0,0 or rows=0, columns=0

1 2 3
1
2
3
4

Example:
#include <iostream.h>
void main()
{
int multTable[7][7]; //2d array with 5 rows and 5 columns
int row, col; //counter variable
// assign values to the array
for(row=0;row<6;row++)
{
for(col=0;col<6;col++)
{
multTable[row][col]=row*col;
}
}
//display the multiplication table:
for(row = 0; row < 6; row++)
{
for(col = 0; col < 6; col++)
{
if( (row==0) && (col == 0)) //check for the top-left corner of
the table
{
cout << ""; //insert a blank space
Copyright American Computer Experience, 2001

Page 18 of 54

Intermediate C++ Programming

}
else if(row==0)
{
cout << "["<< col << "]"; //when row value = 0, list
column headers
}
else if(col==0)
{
cout << "[" << row << "]"; //when column value = 0, list
row headers
}
else
{
cout << " " <<multTable[row][col];
//display array contents, starting @ row=1 and column=1
}
cout <<"\t";
}
cout <<"\n---------------------------------------------\n";
}
}
Output:
[1]
[2]
[3]
[4]
[5]
--------------------------------------------[1]
1
2
3
4
5
--------------------------------------------[2]
2
4
6
8
10
--------------------------------------------[3]
3
6
9
12
15
--------------------------------------------[4]
4
8
12
16
20
--------------------------------------------[5]
5
10
15
20
25
---------------------------------------------

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
Emphasize the need for arrays in dealing with more advanced concepts
that will be introduced later on in the course.
Also, dedicate a significant amount of time to ensure that students have
almost mastered basic array use.

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Copyright American Computer Experience, 2001

Page 19 of 54

Intermediate C++ Programming

Dissect the multiplication table example. Have students re-write it for


different number ranges.
Students should work in pairs or small groups to create a program that will
draw the following table (grid):
,--. ,--. ,--. ,--. ,--. ,--.
| r0 | c1 | c2 | c3 | c4 | c5 |
`--' `--' `--' `--' `--' `--'
,--. ,--. ,--. ,--. ,--. ,--.
| r1 | 01 | 02 | 03 | 04 | 05 |
`--' `--' `--' `--' `--' `--'
,--. ,--. ,--. ,--. ,--. ,--.
| r2 | 02 | 04 | 06 | 08 | 10 |
`--' `--' `--' `--' `--' `--'
,--. ,--. ,--. ,--. ,--. ,--.
| r3 | 03 | 06 | 09 | 12 | 15 |
`--' `--' `--' `--' `--' `--'
,--. ,--. ,--. ,--. ,--. ,--.
| r4 | 04 | 08 | 12 | 16 | 20 |
`--' `--' `--' `--' `--' `--'
,--. ,--. ,--. ,--. ,--. ,--.
| r5 | 05 | 10 | 15 | 20 | 25 |
`--' `--' `--' `--' `--' `--'
Source:
#include <iostream.h>

void main()
{
int multTable[7][7]; //2d array with 5 rows and 5 columns
int row, col; //counter variable
// assign values to the array
for(row=0;row<6;row++)
{
for(col=0;col<6;col++)
{
multTable[row][col]=row*col;
}
}
//display the table:
for(row = 0; row < 6; row++)
{
cout << " ,--. ,--. ,--. ,--. ,--. ,--.\n";
for(col = 0; col < 6; col++)
{
if(col==0)
cout << "| r"<<row<<" ";
else if(row==0)
cout << "| c"<<col<<" ";
else if(col==5 && multTable[row][col]<10)
cout << "| 0"<<multTable[row][col]<<" |";
Copyright American Computer Experience, 2001

Page 20 of 54

Intermediate C++ Programming

else if(col==5 && multTable[row][col]>9)


cout << "| "<<multTable[row][col]<<" |";
else if (multTable[row][col]<10)
cout << "| 0"<<multTable[row][col]<<" ";
else
cout << "| "<<multTable[row][col]<<" ";
}
cout << "\n";
cout << " `--' `--' `--' `--' `--' `--'\n";
}
}

o During or immediately following the students performance of the new skills,


reinforce what they have learned by providing informative constructive feedback.
It is also important here to take note of whether the student has retained
information presented in prior lessons and record this information in a checklist or
by another appropriate method.

Copyright American Computer Experience, 2001

Page 21 of 54

Intermediate C++ Programming

Lesson 4 Structures

Learning Objectives
By the end of this lesson the students should be able to:
1. Understand the concept of structures and it is translated into a programming
concept.
2. Declare and use a structure
3. Use structures as elements of an array.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Structures
o Dot Operator

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers. Structures can be used to emulate a
database(basketball players, multiplayer game server users, etc.). This
may prove to be motivational for your students.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.

Copyright American Computer Experience, 2001

Page 22 of 54

Intermediate C++ Programming

Use a life analogy, as seen in the content. It will make it easier for the
students to relate to the new concept
o Present the content
Explain the purpose of structures in C++ and the terminology (data
members, dot operator, etc)
Point out how structures can contain any C++ element learned so far
(different data types, arrays, etc.)
Outline the uses of arrays of structures (i.e. a team of players)

4.0 Structures
4.0.1 Introduction and definition
When storing information, whether in a computer database or in a paper folder, it
is always accompanied by other related information. For example,
schoolteachers have student file where they store information about the students
(name, age, address, etc). It would make little, to no sense for a student to have
a file containing his/her name, another file with the age, another with the address,
and so on. The reason a students name, age, address are together in the same
file, is because they are related. This file represents a structure. Generally, in
life things are structured or grouped together based on how they relate together.
A C++ Structure is very much like a student file. It is a user-defined data type
that allows the grouping of related data.

4.0.2 Declaring Structures


Much like functions, structures are declared outside the main() function and can
be used in any functions. It is possible to declare a structure within a function,
however its usage is limited to that function.
General Syntax:
struct structure_name
{
data_type variable1_name;
data_type variable2_name;
. . .
}

External Declaration Syntax:


#include <iostream.h>
struct structure_name
{
data_type variable1_name; //data member1

Copyright American Computer Experience, 2001

Page 23 of 54

Intermediate C++ Programming

data_type variable2_name; //data member2


. . .
}

//both functions can use the structure_name


void sampleFunction();
void main()
{
}
void sample Function()
{
//some code. . .
}

Internal Declaration:
The same syntax applies, however; the structure can only be used within the
function where it was declared.
The DOT Operator:
Example:
/* This program will create a structure called student which will hold
student information,
such as name, age, grade. */
#include <iostream.h>
struct student //declare the structure externally
{
char ID[5];
char FirstName[15];
char LastName[15];
short Age;
short Grade;
};
void main()
{
student newStudent; //create a variable named newStudent of type
student.
cout << " ----==- Student Database -==----\n";
cout << " * Data Entry: \n";
cout << "\n [o] Please enter the Student's last name: ";
cin >> newStudent.LastName; // store a value for the student's last
name
cout << "\n [o] Please enter the Student's first name: ";
cin >> newStudent.FirstName; // store a value for the student's first
name
cout << "\n [o] Please enter the Student's Age: ";
cin >> newStudent.Age; // store a value for the student's age

Copyright American Computer Experience, 2001

Page 24 of 54

Intermediate C++ Programming

cout << "\n [o] Please enter the Student's grade: ";
cin >> newStudent.Grade; // store a value for the student's grade
cout << "\n [o] Please enter the Student's ID: ";
cin >>newStudent.ID; // store a value for the student's ID
cout << "\n -- Thank You! --\n";
cout << " The following has been stored in the students database:
\n\n";
// output the information stored in the structure.
cout << " Student ID: " << newStudent.ID;
cout << "\n Student Name: " << newStudent.LastName << ", " <<
newStudent.FirstName;
cout << "\n Age: " << newStudent.Age;
cout << "\n Grade: " << newStudent.Grade << "\n";
}
Output:
----==- Student Database -==---* Data Entry:
[o] Please enter the Student's last name: Bund
[o] Please enter the Student's first name: J.
[o] Please enter the Student's Age: 17
[o] Please enter the Student's grade: 11
[o] Please enter the Student's ID: 007
-- Thank You! -The following information has been stored in the students database:
Student ID: 007
Student Name: Bund, J.
Age: 17
Grade: 11

4.0.3 Arrays of Structures.


Until now, we have talked about arrays of numbers and characters. However,
arrays can have elements of any type, including structures.
Imagine that the student structure will be used to store information about many
students. To be efficient, we will use an array of structures, instead of declaring
a structure for each student.
Declaring an array of structures:
Copyright American Computer Experience, 2001

Page 25 of 54

Intermediate C++ Programming

To declare an array of structures, the array declaration syntax applies, where the
data type is the name of the structure.
For example:
//suppose there is a structure called car
car familySedan[10];
//familySedan is an array of 10 structures of type car
Assigning values to the elements of an array of structures:
Once again, the syntax is not changed. Observe this example:
//declare a structure called gameServer
struct gameServer
{
char name[20];
int playerCapacity;
bool online;
};
void main()
gameServer strategy[3]; //array of 3 structures of type gameServer
//values for the first element of the array
strategy[0].name = NetPlayers;
strategy[0].playerCapacity = 100;
strategy[0].online = true;
//values for the second element of the array
strategy[1].name = MultiP;
strategy[1].playerCapacity = 500;
strategy[1].online = true;
//values for the third element of the array
strategy[2].name = NoName;
strategy[2].playerCapacity = 10;
strategy[2].online = false;

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
Describe how structures are very important in learning the concepts of
Object Oriented Programming.
Emphasize once again the benefits of combining two or more concepts
(arrays and structures)
Copyright American Computer Experience, 2001

Page 26 of 54

Intermediate C++ Programming

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Students should work individually to create structures on different topics.
Since structures can be used for any object, choose topics that would
interest and thus motivate students to complete this exercise.
Students should build up on their structures by creating arrays of
structures and a text interface to allow for data entry.
o During or immediately following the students performance of the new skills,
reinforce what they have learned by providing informative constructive feedback.
It is also important here to take note of whether the student has retained
information presented in prior lessons and record this information in a checklist or
by another appropriate method.

Copyright American Computer Experience, 2001

Page 27 of 54

Intermediate C++ Programming

Lesson 5 Unions and Enumerations

Learning Objectives
By the end of this lesson the students should be able to:
1. Understand both concepts and their relationship to structures
2. Implement unions and enumeration in a C++ program.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Enumerations
o Unions
o Enumerators

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.
Review structures from the previous lesson.
o Present the content

Copyright American Computer Experience, 2001

Page 28 of 54

Intermediate C++ Programming

Since this lesson is very much related to the previous, make use of
comparisons in order to clearly describe the differences and similarities
between structures, unions and enumerations.
Explain the purpose for using unions and/or enumerations.
Initiate a small discussion with your students, asking for their opinion on
which is best to use and when.

5.0 Unions and Enumerations


5.0.1 Introduction and definition
Unions are very similar to structures. However, the members of a union can only
be accessed one at a time. This implies that the union will take as much memory
space as its largest data member. Also, all the data members share the same
memory space. Unions are used often to save memory space.
Enumerations are also similar to structures. They also allow for the definition of
new types (enumerators), but in a very restrictive fashion.

5.0.2 Declaring Unions.


The declaration syntax is virtually identical with that of a structure. The only
difference is the key word union that replaces the key word, struct.
Example:
union numbers
{
int intEger;
double decImal;
}
Assigning values:
The main difference between a structure and a union is that each data member
of a union is accessed one at a time. This characteristic of a union is very visible
when assigning values to its data.
Example:
void main()
{
numbers myNumbers; //declare a variable of type numbers
//notice that the syntax is identical with that of a structure.
myNumbers.intEger = 10;
cout << myNumbers.intEger;
Copyright American Computer Experience, 2001

Page 29 of 54

Intermediate C++ Programming

myNumbers.decImal=3.14;
cout << myNumbers.decImal;
//note how the two data members were given values, one at a time.
}

5.0.3 Declaring Enumerations


An enumeration is declared as follows:
enum new_type_name {sConst1, sConst2, sConst3, . . . };

symbolic constants otherwise known as enumerators separated by


commas.

Example:
enum pets{cat, dog, hamster, rabbit, bird, lizard};
o Provide learning guidance
Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
Given that unions and enumerations (as well as structures) relate to real
life objects, explain the likelihood of using these concepts when creating
complex C++ programs.

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Students should work individually and practice using unions and
enumerations.
Students should use any extra time to exercise creating structures as well.
o During or immediately following the students performance of the new skills,
reinforce what they have learned by providing informative constructive feedback.
It is also important here to take note of whether the student has retained
information presented in prior lessons and record this information in a checklist or
by another appropriate method.

Copyright American Computer Experience, 2001

Page 30 of 54

Intermediate C++ Programming

Lesson 6 Pointers

Learning Objectives
By the end of this lesson the students should be able to:
1. Define and understand pointers as a concept
2. Describe the main function of a pointer.
3. Extract the address of any variable

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Enumerations
o Unions
o Enumerators

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.
Review structures from the previous lesson.
o Present the content
Copyright American Computer Experience, 2001

Page 31 of 54

Intermediate C++ Programming

Since this lesson is very much related to the previous, make use of
comparisons in order to clearly describe the differences and similarities
between structures, unions and enumerations.
Explain the purpose for using unions and/or enumerations.
Initiate a small discussion with your students, asking for their opinion on
which is best to use and when.

6.0 Pointers
6.0.1 Introduction and definition
So far, to store data we have used variables. Once again, a variable will allow
you to describe where data is stored, what value it contains and what type it is.
An alternative to using variables is using pointers. Pointers are special data
types that store the memory address of a data value as opposed to the value
itself. In other words, pointer actually point to the block of memory where a
specific value is stored.

6.0.2 Declaring Pointers


Declare a pointer
i bl *pointToAge;
int

Declare and initialize a variable


int myAge = 22;
&myAge - Represents the memory address where 22 was stored

Assign values to pointer


i bl
pointToAge
= &myAge; therefore *pointToAge=22
Summary:
a. The memory address of a variables value can be obtained by using the
addressing operator (&) in front of the variable name.
b. From pointer declaration, we can notice that *pointerName (where
pointerName is any pointer name) is of type int, whereas
pointerName(without the * operator) is a pointer type( an address)
c. Although pointers represent the memory addresses, when declared you still
need to specify the type of value that they point to.
Example:
#include <iostream.h>
void main()
{
int age;
int *ptrAge=&age;

Copyright American Computer Experience, 2001

Page 32 of 54

Intermediate C++ Programming

cout << "Please enter your age: ";


cin >> age;
cout << "The variable age has the value: " << age;
cout << "\nThe variable *ptrAge has the value: " <<
*ptrAge;
cout << "\n\nThe memory address of the age variable is: "
<< &age;
cout << "\nThe pointer ptrAge has the value: " << ptrAge;
}
Output:
Please enter your age: 22
The variable age has the value: 22
The variable *ptrAge has the value: 22
The memory address of the age variable is: 0x0065FDF4
The pointer ptrAge has the value: 0x0065FDF4

6.0.3 Pointer arithmetic


Performing an arithmetic operation to a number, results in another number.
When performing an arithmetic operation using pointers, the result is a new
address. For example, adding 12 to an integer value, will increase the value by
12. However, adding 1 to a pointer variable will increase its value by the number
of bytes of the variable type it points to.
Example:
#include <iostream.h>
void main()
{
int scores[2]={124530, 124531};
int *ptrS=scores;
//another way to initialize the pointer:
//
int *ptrS=&scores[0];
//display the address of the first array element
cout << "Score 1 address
: " <<ptrS <<"\n";
//display the result of the pointer variable + 1
cout << "Score 1 address + 1 : " <<ptrS+1 <<"\n";
//display the value of the address of the second array element
//because of the size of the int type, the address of scores[1] =
ptrS+1
cout << "Score 2 address

: " <<&scores[1] <<"\n\n";

Copyright American Computer Experience, 2001

Page 33 of 54

Intermediate C++ Programming

cout << "Score 1 value


cout << "Score 1 value + 1
cout << "Score 2 value

: " <<*ptrS <<"\n";


: " <<*ptrS+1 <<"\n";
: " <<scores[1] <<"\n";

Output:
Score 1 address
: 0x0065FDF0
Score 1 address + 1 : 0x0065FDF4
Score 2 address
: 0x0065FDF4
Score 1 value
Score 1 value + 1
Score 2 value

: 124530
: 124531
: 124531

ADDRESS
VALUE

0x00665FDF0

0x00665FDF4

124530

124531

Here int = 4 bytes

Example using a short type


ADDRESS
VALUE

0x00665FDF4

0x00665FDF6

130

131

Here short=2 bytes

The purpose of implementing pointer arithmetic is to be able to jump from one


memory address to any other memory address. This is particularly useful when
searching for a value or when sorting a list of values.

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
Given that unions and enumerations (as well as structures) relate to real
life objects, explain the likelihood of using these concepts when creating
complex C++ programs.

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Students should work individually and practice using unions and
enumerations.
Copyright American Computer Experience, 2001

Page 34 of 54

Intermediate C++ Programming

Students should use any extra time to exercise creating structures as well.
During or immediately following the students performance of the new
skills, reinforce what they have learned by providing informative
constructive feedback. It is also important here to take note of whether
the student has retained information presented in prior lessons and record
this information in a checklist or by another appropriate method.

Copyright American Computer Experience, 2001

Page 35 of 54

Intermediate C++ Programming

Lesson 7 Functions

Learning Objectives
By the end of this lesson the students should be able to:
1. Recall the concept of functions and how to implement it in a C++ program.
2. Use arrays as function parameters
3. Implement functions within structures as data members.
4. Utilize pointers within functions.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.
Review basic function implementation
Students should also recall using arrays, pointer and structures.
o Present the content

Copyright American Computer Experience, 2001

Page 36 of 54

Intermediate C++ Programming

On the premises that complex problem solving is achieved by combining


concepts, discuss functions in relationship with arrays, pointers and
structures.
Also review the relationship between arrays, pointers and structures.

7.0 Functions
7.0.1 Review of simple functions.
Definition: Functions are code structures that help automate tasks used
throughout a C++ program. There are two types of C++ functions: return-value
and void functions.
Syntax:

Optional

return_type function_name( parameter_list )


Function
{
H d
function_statements
Function Body
}
Note: for functions that do not return a value, the return_type is
id
Example:
#include <iostream.h>
double convert(int feet); //function prototype
void main()
{
int feet;
double meters;
cout << " *** The conversion program *** \n";
cout << " >> Enter the amount of feet to convert to meters\n >> ";
cin >> feet;
meters=convert(feet); //function call
cout << " =-= " << feet << " feet converts to " << meters << "
meters!\n";
}
//function declaration
double convert(int feet)
{
double mtr;
mtr=feet*0.3048;
return mtr;
}
Sample Output:
*** The conversion program ***
>> Enter the amount of feet to convert to meters
>> 14400
=-= 14400 feet converts to 4389.12 meters!
Copyright American Computer Experience, 2001

Page 37 of 54

Intermediate C++ Programming

7.0.2 Functions and arrays & pointers


Functions are concepts used often when programming. So far, we dealt with
simple functions that use basic data types. In this section well observe using
function in conjunction with arrays.
Example 1:
#include <iostream.h>
int numSum (int num[], int i); //function prototype
void main()
{
int numbers[5]; //declare an array with five elements
cout << "Enter five numbers: \n";
//automated input... insert values in the array.
for (int x=0;x<5;x++)
{
cout << "Enter a value for number " << x+1 << ": ";
cin >> numbers[x];
cout << "\n";
}
//display the sum of the numbers entered.
cout << "The sum of the numbers you entered is:
"<<numSum(numbers, 5);
}
//define the sum function. Note that the function takes two
parameters.
//One is an array, the other is a regular integer.
int numSum (int num[], int i)
{
int sum=0;
for (int x=0; x<i; x++)
{
sum+=num[x];
}
return sum;
}
Sample Output:
Enter five numbers:
Enter a value for number 1: 321
Enter a value for number 2: 123
Enter a value for number 3: 231
Enter a value for number 4: 1

Copyright American Computer Experience, 2001

Page 38 of 54

Intermediate C++ Programming

Enter a value for number 5: 2


The sum of the numbers you entered is: 678

This example shows how a simple operation (adding the values of all elements in
an array) can be automated using a function that has an array passed as a
parameter.
Side note: The name of an array is interpreted by C++ as the address of the
arrays first element. From the previous chapter, we can conclude that a
statement like int num[] is equivalent to int *num. This means that num is a
pointer.
Example 1 (pointer version)
#include <iostream.h>
int numSum (int *num, int i); //function prototype
void main()
{
int numbers[5]; //declare an array with five elements
cout << "Enter five numbers: \n";
for (int x=0;x<5;x++)
{
cout << "Enter a value for number " << x+1 << ": ";
cin >> numbers[x];
cout << "\n";
}
cout << "The sum of the numbers you entered is:
"<<numSum(numbers, 5);
}
int numSum (int *num, int i)
{
int sum=0;
for (int x=0; x<i; x++)
{
sum+=num[x];
}
return sum;
}

The output will not change.


This example uses the numSum function to add the values of the arrays
elements. However, it should be noticeable that filling the array with values can
also be part of a function.

7.0.3 Functions and structures


Although structures contain more code than arrays, they are easier to implement
with functions as parameters or return values.
Example:
#include <iostream.h>
Copyright American Computer Experience, 2001

Page 39 of 54

Intermediate C++ Programming

struct rectangle
{
int width;
int height;
};
int perimeter (rectangle r); //function prototype
int area (rectangle r);
void main()
{
rectangle myRect; //declare a variable of type rectangle
int rectArea=0;
int rectPerimeter=0;
cout << "Please enter the width of your rectangle: ";
cin >> myRect.width; //get width
cout << "Please enter the height of your rectangle: ";
cin >> myRect.height; //get height
rectArea=area(myRect); //call function that calculates area
cout << "\nThe area of the rectangle is " << rectArea;
rectPerimeter = perimeter(myRect); //call function that calculates
perimeter
cout << "\nThe perimeter of the rectangle is " << rectPerimeter;

}
/*
Define the perimeter and area funcitons.
Note that the functions take a structure type as a parameter.
*/
int perimeter (rectangle r)
{
int sum=0;
sum=(2 * r.width) + (2 * r.height);
return sum;
}
int area (rectangle r)
{
int a=0;
a = r.height * r.width;
return a;
}
Sample Output:

Copyright American Computer Experience, 2001

Page 40 of 54

Intermediate C++ Programming

Please enter the width of your rectangle: 53


Please enter the height of your rectangle: 12
The area of the rectangle is 636
The perimeter of the rectangle is 130

The example uses a simple structure that describes a rectangle. The two
functions make use of the structure as a parameter in order to calculate the area
and the perimeter.
Using structures as function parameters, as arrays, pointers, etc. is not a difficult
process. However, it requires a very good grasp on the concepts being used.

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
Functions will always be part of C++ programs. Thus, it is very important
that students have a good grasp on the concept and its implementations.

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Students should work in pairs to recreate content examples
Based on the same examples they can modify or enhance them with your
supervision.
During or immediately following the students performance of the new
skills, reinforce what they have learned by providing informative
constructive feedback. It is also important here to take note of whether
the student has retained information presented in prior lessons and record
this information in a checklist or by another appropriate method.

Copyright American Computer Experience, 2001

Page 41 of 54

Intermediate C++ Programming

Lesson 8 Namespaces

Learning Objectives
By the end of this lesson the students should be able to:
1. Define and understand namespaces and their purpose.
2. Declare and implement a namespace in C++.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Namespace
o Global identifiers
o Scope resolution operator

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.
o Present the content
Describe scenarios where namespaces would be particularly useful.
Describe the syntax and go through content examples to show how
namespaces are implemented.
Copyright American Computer Experience, 2001

Page 42 of 54

Intermediate C++ Programming

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
With more complex programs namespaces will prove to be very helpful.
Thus you should instruct the students to ensure proper understanding of
this concept.

8.0 Namespaces
8.0.1 Introduction and definition
C++ is a very complex language, which implies that it is likely to encounter two or
more functions, structures, etc. that have the same name. A namespace allows
a programmer to use two or more global identifiers that have the same name.

8.0.2 Declaring namespaces


Syntax:
namespace Name
{
members
}
Example:
#include <iostream.h>
namespace Racing
{
struct Car
{
char *DriverName;
short RacesWon;
floar maxSpeed;
};
}
namespace Street
{
struct Car
{
int price;
double LeaseRate;
};

Copyright American Computer Experience, 2001

Page 43 of 54

Intermediate C++ Programming

}
void main()
{
//declare a variable of type car using the Racing
namespace
Racing::Car carRS;
//declare a variable of type car using the Street namespace
Street::Car carST;
}
In the example above, two namespaces were declared to accommodate the two
structures with the same name. Notice the use of the scope resolution operator
(::)to explicitly identify which Car structure is referred to.

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Students should work individually and practice using namespaces within
their C++ program.
o During or immediately following the students performance of the new skills,
reinforce what they have learned by providing informative constructive feedback.
It is also important here to take note of whether the student has retained
information presented in prior lessons and record this information in a checklist or
by another appropriate method.

Copyright American Computer Experience, 2001

Page 44 of 54

Intermediate C++ Programming

Lesson 9 Preprocessor

Learning Objectives
By the end of this lesson the students should be able to:
1. Understand the pre-processor and its purpose.
2. Use preprocessor directives within a C++ program
3. Comprehend the concept of conditional compilation

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Preprocessor
o Directive

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.
Review the compilation process and header files. Discuss constants and
recall their purpose.
o Present the content
Copyright American Computer Experience, 2001

Page 45 of 54

Intermediate C++ Programming

Discuss the steps of the compilation process as a review from the


previous course.
Explain the role of the preprocessor.
Describe preprocessor directives and their implementation method.
o Provide learning guidance
Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.

9.0 Pre-processor
9.0.1 Introduction and definition
The preprocessor is the part of the compilation process that processes and
manipulates the source code. But as we know, a C++ program can include
commands that are defined in an external header file that needs to be attached
to the C++ program. The #include command is called a pre-processor directive,
which includes an external file in the current program. Another popular
preprocessor directive is the #define. For example:
#include <iostream.h>
#define PI 3.141592654
void main()
{
cout << The Value of pi is: << PI;
}
Output:
The Value of pi is 3.141592654
In the above example, the preprocessor will search for the word PI and will
replace it with the number value of 3.141592654. PI is called a token because
the preprocessor will not replace PI if it is embedded in another word (i.e.
numberPI or PIconst).
Example 2:
#include <iostream.h>
#define CIRCLE_AREA(R) (3.141592654 * (R) * (R))
void main()
{
cout << The area of a circle with radius 5 is: <<
CIRCLE_AREA(5);
Copyright American Computer Experience, 2001

Page 46 of 54

Intermediate C++ Programming

}
Output:
The area of a circle with radius 5 is: 78.5398
In example 2, the #define directive was used much like a function. This
method of automating tasks through a preprocessor directive is called a macro.
The #define directive can be followed by multiple lines of code that will make up
the definition of a token. For example:
#include <iostream.h>
#define MAIN_FUNCTION void main() \
{\
cout << "This is a preprocessor multi-line token
value"; \
}\
//call the MAIN_FUNCTION macro:
MAIN_FUNCTION
Output:
This is a preprocessor multi-line token value
This example demonstrates how to create a macro called MAIN_FUNCTION
using the #define directive. The value of the MAIN_FUNCTION token is
composed of multiple lines of code that are separated by a forward slash (\) and
a hard return.
Other preprocessor directives:
Directive
Syntax
#undef TOKEN
#undef

#if

#ifdef

#ifndef

#elif

#if defined(TOKEN)
//do something
#endif
#ifdef TOKEN
//true if token has
been defined
#endif
#ifndef TOKEN
#define TOKEN
#endif
#if defined(TOKEN_1)
//your code
#elif defined(TOKEN_2)
//more code

Description
The opposite of the #define directive. It
un-defines a token from the program
Similar to the regular if statement. It can
be used in conjunction with #define and
it must be accompanied by the #endif.
This directive returns true if the specified
token has been defined
This directive returns true if the specified
token has not been defined.
Similar to the else if clause of the regular
if statement.

Copyright American Computer Experience, 2001

Page 47 of 54

Intermediate C++ Programming

#else

#endif
#ifndef TOKEN
#define TOKEN
#else
#define TOKEN_1
#endif

This token has the same purpose as the


else clause of the C++ if statement.

9.0.2 Conditional Compilation


Suppose that we are dealing with a large program and several tokens were
defined. Using preprocessor directives, we can ensure that all tokens will be
unique and duplicates will not occur.
For example, suppose a token with the name WINDOWS_PC. This token will
contain information specific to those computers that use the Windows operating
system. To safely define this new token, use:
#ifndef WINDOWS_PC
#define WINDOWS_PC

#endif
Notice how the #ifndef directive was used to check whether the WINDOWS_PC
token was defined.
Consider the following example:
//Game Engine Initialization
#if defined(HI_RES)
// insert code specific to high resolution monitors
#elif defined(REG_RES)
// insert code specific to normal resolution monitors
#elif defined(LOW_RES)
// prompt the user that this highly graphical game cannot be played
// on a low resolution monitor.
#endif

The above illustrates a scenario very often encountered, where issues like
screen resolution are handled explicitly. Such techniques characterize a welldeveloped, complex program.
Copyright American Computer Experience, 2001

Page 48 of 54

Intermediate C++ Programming

Extension and Performance Assessment


Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Students can work individually on defining tokens and using them in a
suggested C++ program. They can use previous examples that can be
modified to facilitate the preprocessor tokens.
Students should work in pairs and/or small groups to create programs
where they practice different directives.

During or immediately following the students performance of the new skills, reinforce what they
have learned by providing informative constructive feedback. It is also important here to take note
of whether the student has retained information presented in prior lessons and record this
information in a checklist or by another appropriate method.

Copyright American Computer Experience, 2001

Page 49 of 54

Intermediate C++ Programming

Lesson 10 Dynamic Memory Allocation

Learning Objectives
By the end of this lesson the students should be able to:
1. Distinguish between the heap and the stack.
2. Understand the purpose for creating dynamic objects
3. Use the new and delete operators to create and destroy a dynamic object.
4. Create dynamic arrays.

Suggested Time Frame:


1 class or 45 minutes
This value is meant as a guideline and can be adjusted according to the particular needs
of your students.

Keywords and Vocabulary


The following is a list of new keywords, vocabulary and terms that your students will
encounter during this lesson. It is recommended that you prepare definitions or
explanations in advance and reinforce them with the students when they come up.
o Heap (Free store)
o Stack
o Dynamic object

Lesson Presentation
The following is a suggested presentation layout for this lesson. This is provided in detail
to assist you in your preparation for teaching your class. It is also recommended that
before class you ensure that you have read all relevant materials, your classroom is
prepared, all student resources have been assembled and all software, hardware and
other equipment is ready for use.
o Gain students attention
Use an abrupt stimulus change to gain the attention of your students.
This will vary based on their age and is especially important for the
younger campers.
o Inform the students of the objectives
Use the objectives list at the beginning of this lesson to explain to the
students what they will learn during your presentation. You may also
briefly describe how the lesson will proceed.
o Stimulate recall of prior learning.
Ask for a recall of previously learned relevant skills and knowledge,
especially anything considered prerequisite to this lesson.
Where appropriate, indicate how this knowledge is important for what they
are about to do.

Copyright American Computer Experience, 2001

Page 50 of 54

Intermediate C++ Programming

Discuss the memory requirements of a C++ program and emphasize the


importance of efficient code that implies using the least amount of
memory.
o Present the content
Explore the potential of an imaginary C++ program that is not restricted by
memory usage. Arrive at a conclusion regarding conserving memory
usage.
Describe the syntax and implementation of the new and delete operators.
Talk about dynamic arrays.

10 Dynamic memory allocation


10.0.1 Introduction and definition
The part of the computer memory available to programmers, is divided into two
areas: The Stack and The Heap (or Free Store).
The Stack is used for those items that have a definite size and lifetime, for
example, variables, arrays, etc. All the elements of a program where they are
explicitly defined before compilation are stored statically.
The Heap represents the remaining unused memory. This part of memory is
generally used during the execution of the program. Any object that is created at
run time is a dynamic object. Such an object has an unknown size and lifetime.
Creating dynamic objects is very useful in creating highly interactive programs.

10.0.2 The new and delete operators


The new and delete operators are tools for creating and destroying dynamic
objects. The new operator allocates memory for the new dynamic object to be
created. Since the heap is limited, regardless of how much RAM a computer
has, the delete operator will be used to destroy an object once its not needed
any longer.
Note: It is very important to keep track of dynamic objects to avoid running out of
memory and thus crashing your program. Memory management is one of the
crucial factors that commercial programs are faced with.
New and Delete Syntax:
//create a new integer and return a pointer to it
int *ptrInt=new int;
//assign a value to the dynamic integer

Copyright American Computer Experience, 2001

Page 51 of 54

Intermediate C++ Programming

*ptrInt=120;
//delete it to free memory
delete ptrInt;
To create a dynamic object, such as the integer above, a pointer should be
created to that data type. This pointer will be assigned a new object of the same
type. In the above example, a pointer variable of type int was created and to it
a new int object was assigned.
Example:
#include <iostream.h>
void main()
{
int *ptrC=0;
int x=0;
while (x<3) {
ptrC=new int;
cout <<"Please enter a number: ";
cin >>*ptrC;
cout << "You entered: " << *ptrC;
cout << " @ address: " <<ptrC <<"\n";
delete ptrC;
x++;
} }

Output:
Please enter
You entered:
Please enter
You entered:
Please enter
You entered:

a number: 45
45 @ address: 0x00790D30
a number: 35
35 @ address: 0x00790D30
a number: 63
63 @ address: 0x00790D30

The example above demonstrates creating a dynamic object of type int. Once
again to achieve this, a pointer variable of type int is used.

10.0.3 Dynamic Arrays


Creating dynamic arrays is done using the procedure outlined above.
//create a pointer of the same type as the array type:
char myName[]=Andrew;
//create a new array object based on the size of
char *newArray = new char[strlen(myName)+1];

myName

//copy the value of myName to the location of newArray.


Copyright American Computer Experience, 2001

Page 52 of 54

Intermediate C++ Programming

strcpy(myName, newArray);
//once finished using the newArray, delete it from memory
delete(newArray);
Example:
#include <iostream.h>
#include <string.h>
void main()
{
//create a temporary array of 100 characters
char temp[100];
cout << "Please enter your first name: ";
cin >> temp;
//create a character pointer and assign it a new character array
char *myName=new char[strlen(temp)+1];
//assign the new array the value of the temporary array
strcpy(myName, temp);
cout << "The size of the temp array is 100\nThe contents are: " <<
temp;
cout << "\nThe size of the myName array is " << strlen(temp)+1;
cout << "\nThe contents are: " << myName;
delete(myName);
}

Output:
Please enter your first name: ANDREW
The size of the temp array is 100
The contents are: ANDREW
The size of the myName array is 7
The contents are: ANDREW

Creating dynamic objects is once again very useful and often used in highly
interactive, commercial C++ programs.

o Provide learning guidance


Suggest a meaningful organization for the content that has just been
presented. Where appropriate, point out how this information can be
applied and where it fits into a larger skill set.
Again, dynamic memory allocation should be seen as an advanced
technique of applying already learned concepts (pointers, arrays, etc.)
Thus the content can be organized starting with a quick review of certain
concepts and ending with using these concepts in a dynamic environment.

Extension and Performance Assessment

Copyright American Computer Experience, 2001

Page 53 of 54

Intermediate C++ Programming

Extension is the process by which students learn how newly acquired skills and knowledge
are applied and how they are transferred
o Elicit performance by asking students to complete an activity based on the skills
and knowledge that have been presented.
Students should practice the examples provided in the content.
You, the instructor, should suggest minor changes the students need to
implement in their programs. This will ensure a better understanding of
the concepts involved.
During or immediately following the students performance of the new skills, reinforce what they
have learned by providing informative constructive feedback. It is also important here to take note
of whether the student has retained information presented in prior lessons and record this
information in a checklist or by another appropriate method.

Copyright American Computer Experience, 2001

Page 54 of 54

You might also like