Professional Documents
Culture Documents
Intermediate C Programming
Intermediate C Programming
Table of Contents
Course Description
Page 3
Page 4
Learning Objectives
Page 4
Page 5
Page 6
Lesson 1 Introduction
Page 7
Lesson 2 Loops
Page 9
Lesson 3 Arrays
Page 16
Lesson 4 Structures
Page 22
Page 28
Lesson 6 Pointers
Page 31
Lesson 7 Functions
Page 36
Lesson 8 Namespaces
Page 42
Lesson 9 Preprocessor
Page 45
Page 50
Page 2 of 54
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.
Page 3 of 54
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.
Page 4 of 54
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
Books:
Page 5 of 54
Page 6 of 54
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.
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.
Page 7 of 54
Page 8 of 54
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.
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
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;
}
Exit-Condition Loops
int i=0;
do
{
cout << i << \n;
}
loop(i<5)
Page 10 of 54
int i=0;
while(i<5)
{
cout << i << \n;
i++;
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Page 11 of 54
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
Page 12 of 54
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
#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
Page 15 of 54
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.
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
Page 16 of 54
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
Page 17 of 54
Syntax:
data_type array_name[rows_number][columns_number];
Rows
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
}
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
---------------------------------------------
Page 19 of 54
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
Page 21 of 54
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.
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.
Page 22 of 54
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.
Page 23 of 54
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
Page 24 of 54
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
Page 25 of 54
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;
Page 26 of 54
Page 27 of 54
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.
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
Page 28 of 54
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.
Page 29 of 54
myNumbers.decImal=3.14;
cout << myNumbers.decImal;
//note how the two data members were given values, one at a time.
}
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.
Page 30 of 54
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
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
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.
Page 32 of 54
Page 33 of 54
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
0x00665FDF4
0x00665FDF6
130
131
Page 34 of 54
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.
Page 35 of 54
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.
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
Page 36 of 54
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
Page 37 of 54
Page 38 of 54
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;
}
Page 39 of 54
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:
Page 40 of 54
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.
Page 41 of 54
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++.
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
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.
Page 43 of 54
}
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.
Page 44 of 54
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
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
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
}
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.
Page 47 of 54
#else
#endif
#ifndef TOKEN
#define TOKEN
#else
#define TOKEN_1
#endif
#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
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.
Page 49 of 54
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.
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.
Page 50 of 54
Page 51 of 54
*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.
myName
Page 52 of 54
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.
Page 53 of 54
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.
Page 54 of 54