Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American...

54
Intermediate C++ Programming Summer Camp Teacher’s Guide Copyright American Computer Experience, 2001

Transcript of Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American...

Page 1: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Summer Camp Teacher’s Guide

Copyright American Computer Experience, 2001

Page 2: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 2 of 54

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

Page 3: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 3 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 4: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 4 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. Understand and use the advanced features of iteration statements. 2. Master the use of loops in C++ programs. 3. Define and understand the concept of multidimensional arrays. 4. Use 2 dimensional arrays in C++ programs. 5. Understand the concept of structures and it is translated into a programming concept. 6. Declare and use a structure. 7. Use structures as elements of an array. 8. Understand both concepts and their relationship to structures. 9. Implement unions and enumeration in a C++ program. 10. Define, understand and describe the main function of pointers. 11. Extract the address of any variable. 12. Use arrays as function parameters. 13. Implement functions within structures as data members. 14. Utilize pointers within functions. 15. Define and understand namespaces and their purpose. 16. Declare and implement a namespace in C++. 17. Understand the purpose of the pre-processor. 18. Use preprocessor directives within a C++ program. 19. Comprehend the concept of conditional compilation. 20. Distinguish between the heap and the stack. 21. Understand the purpose for creating dynamic objects 22. Use the new and delete operators to create and destroy a dynamic object. 23. Create dynamic arrays.

Page 5: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 5 of 54

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 Books:

• Practical C++, by Rob McGregor • Computer Science Logic, by Egon Börger, Hans Kleine Büning, Gerhard Jäger • 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

Page 6: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 6 of 54

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++.

Page 7: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 7 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.

• 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.

Page 8: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 8 of 54

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.

Page 9: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 9 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.

• 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.

Page 10: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 10 of 54

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

22..00..11 –– RReevviieeww ooff tthhee tthhrreeee mmaaiinn lloooopp ssttrruuccttuurreess.. Recall the three looping structures learned in Unit 01. These are:

- The for Loop - The while Loop - The do while Loop

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”;

}

int i=0;for(i=0; i<5;i++){

cout << i << “ \n”;}

int i=0;while(i<5){

cout << i << “ \n”;i++;

}

Both the for loop and the while loop check that i < 5

before they execute the cout statement.

Entry-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.

Exit-Condition Loops

Page 11: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 11 of 54

}Output:12345678910

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:54521

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:12345

Page 12: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 12 of 54

22..00..22 –– AAddvvaanncceedd LLoooopp CCoonncceeppttss.. 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: 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 separatorcout << " 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 | 91 | 82 | 73 | 64 | 55 | 46 | 37 | 28 | 19 | 0

Change the step (increment) size

for(declare_expressions ; expressions_upperlimit; increments){

}

expression1, expression2, . Upper_limit1, Upper_limit2, . .

expression1 will be evaluated before expression2.

Page 13: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 13 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:135791113151719

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:

Page 14: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 14 of 54

#include <iostream.h>

int main(){

int charCounter=0;//declare and initialize the character counterchar 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 characterwhile(ch!='@')//use a while loop to record all input before the ‘@’

{cout << ch; //display the recorded characterscharCounter++; //increment the counter by 1cin >> 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!='@')

{

Page 15: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 15 of 54

cout << ch;charCounter++;cin.get(ch); //record the next character

}//this time the spaces are recorded, thus the number of character

will changecout << "\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.

Page 16: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 16 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.

• 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

Page 17: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 17 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 33..00..11 –– RReevviieeww ooff oonnee--ddiimmeennssiioonnaall aarrrraayyss.. 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: eEnter the fourth letter of the word: sEnter the third letter of the word: uEnter the second letter of the word: oEnter the first letter of the word: hThe word you thought of is: house

Page 18: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 18 of 54

33..00..22 –– IInnttrroodduuccttiioonn ttoo mmuullttii--ddiimmeennssiioonnaall aarrrraayyss.. 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.

33..00..33 –– DDeeccllaarriinngg aa 22--ddiimmeennssiioonnaall aarrrraayy Example: #include <iostream.h>

void main(){

int multTable[7][7]; //2d array with 5 rows and 5 columnsint 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 ofthe table

{cout << ""; //insert a blank space

1 2 31 2 3 4

Rows

ColumnsSyntax: data_type array_name[rows_number][columns_number];

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

Page 19: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 19 of 54

}else if(row==0){

cout << "["<< col << "]"; //when row value = 0, listcolumn headers

}else if(col==0){

cout << "[" << row << "]"; //when column value = 0, listrow 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.

Page 20: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 20 of 54

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 columnsint 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]<<" |";

Page 21: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 21 of 54

else if(col==5 && multTable[row][col]>9)cout << "| "<<multTable[row][col]<<" |";

else if (multTable[row][col]<10)cout << "| 0"<<multTable[row][col]<<" ";

elsecout << "| "<<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.

Page 22: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 22 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.

• 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.

Page 23: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 23 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 44..00..11 –– IInnttrroodduuccttiioonn aanndd ddeeffiinniittiioonn 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 student’s (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 student’s 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.

44..00..22 –– DDeeccllaarriinngg SSttrruuccttuurreess 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

Page 24: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 24 of 54

data_type variable2_name; //data member2. . .

}

//both functions can use the structure_namevoid 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 holdstudent 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 typestudent.

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 25: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 25 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: 007Student Name: Bund, J.Age: 17Grade: 11

44..00..33 –– AArrrraayyss ooff SSttrruuccttuurreess.. 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:

Page 26: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 26 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 gameServerstruct 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 arraystrategy[0].name = ”NetPlayers”;strategy[0].playerCapacity = 100;strategy[0].online = true;

//values for the second element of the arraystrategy[1].name = ”MultiP”;strategy[1].playerCapacity = 500;strategy[1].online = true;

//values for the third element of the arraystrategy[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)

Page 27: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 27 of 54

• 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.

Page 28: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 28 of 54

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

Page 29: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 29 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.

5.0 – Unions and Enumerations 55..00..11 –– IInnttrroodduuccttiioonn aanndd ddeeffiinniittiioonn 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.

55..00..22 –– DDeeccllaarriinngg UUnniioonnss.. 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;

Page 30: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 30 of 54

myNumbers.decImal=3.14;cout << myNumbers.decImal;

//note how the two data members were given values, one at a time.}

55..00..33 –– DDeeccllaarriinngg EEnnuummeerraattiioonnss An enumeration is declared as follows:

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.

symbolic constants otherwise known as enumerators separated by commas.

enum new_type_name {sConst1, sConst2, sConst3, . . . };

Page 31: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 31 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

• 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

Page 32: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 32 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 66..00..11 –– IInnttrroodduuccttiioonn aanndd ddeeffiinniittiioonn 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.

66..00..22 –– DDeeccllaarriinngg PPooiinntteerrss Summary: a. The memory address of a variable’s 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;

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

int *pointToAge;

pointToAge = &myAge; therefore *pointToAge=22

Declare and initialize a variable Declare a pointer i bl

Assign values to pointer i bl

Page 33: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 33 of 54

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: 22The variable age has the value: 22The variable *ptrAge has the value: 22

The memory address of the age variable is: 0x0065FDF4The pointer ptrAge has the value: 0x0065FDF4

66..00..33 –– PPooiinntteerr aarriitthhmmeettiicc 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 elementcout << "Score 1 address : " <<ptrS <<"\n";

//display the result of the pointer variable + 1cout << "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+1cout << "Score 2 address : " <<&scores[1] <<"\n\n";

Page 34: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 34 of 54

cout << "Score 1 value : " <<*ptrS <<"\n";cout << "Score 1 value + 1 : " <<*ptrS+1 <<"\n";cout << "Score 2 value : " <<scores[1] <<"\n";

} Output: Score 1 address : 0x0065FDF0Score 1 address + 1 : 0x0065FDF4Score 2 address : 0x0065FDF4

Score 1 value : 124530Score 1 value + 1 : 124531Score 2 value : 124531 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.

ADDRESS

VALUE 0x00665FDF0 0x00665FDF4

124530 124531

Here int = 4 bytes

ADDRESS

VALUE

0x00665FDF4 0x00665FDF6

130 131

Here short=2 bytes

Example using a short type

Page 35: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 35 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 36: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 36 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.

• 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

Page 37: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 37 of 54

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 77..00..11 –– RReevviieeww ooff ssiimmppllee ffuunnccttiioonnss.. 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. Example: #include <iostream.h>

double convert(int feet); //function prototypevoid 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 callcout << " =-= " << feet << " feet converts to " << meters << "

meters!\n";}//function declarationdouble 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!

Syntax: return_type function_name( parameter_list ) { function_statements } Note: for functions that do not return a value, the return_type is “ id”

Function H d

Function Body

Optional

Page 38: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 38 of 54

77..00..22 –– FFuunnccttiioonnss aanndd aarrrraayyss && ppooiinntteerrss Functions are concepts used often when programming. So far, we dealt with simple functions that use basic data types. In this section we’ll 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 twoparameters.//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

Page 39: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 39 of 54

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 array’s 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 prototypevoid main(){

int numbers[5]; //declare an array with five elementscout << "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 array’s elements. However, it should be noticeable that filling the array with values can also be part of a function.

77..00..33 –– FFuunnccttiioonnss aanndd ssttrruuccttuurreess Although structures contain more code than arrays, they are easier to implement with functions as parameters or return values. Example: #include <iostream.h>

Page 40: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 40 of 54

struct rectangle{

int width;int height;

};

int perimeter (rectangle r); //function prototypeint area (rectangle r);

void main(){

rectangle myRect; //declare a variable of type rectangleint 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

perimetercout << "\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 41: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 41 of 54

Please enter the width of your rectangle: 53Please enter the height of your rectangle: 12

The area of the rectangle is 636The 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.

Page 42: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 42 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++.

• 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.

Page 43: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 43 of 54

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 88..00..11 –– IInnttrroodduuccttiioonn aanndd ddeeffiinniittiioonn 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.

88..00..22 –– DDeeccllaarriinngg nnaammeessppaacceess 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;

};

Page 44: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 44 of 54

}void main(){//declare a variable of type car using the Racing

namespaceRacing::Car carRS;

//declare a variable of type car using the Street namespaceStreet::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.

Page 45: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 45 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

• 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

Page 46: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 46 of 54

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 99..00..11 –– IInnttrroodduuccttiioonn aanndd ddeeffiinniittiioonn 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);

Page 47: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 47 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 Description #undef

#undef TOKEN The opposite of the #define directive. It un-defines a token from the program

#if

#if defined(TOKEN)//do something#endif

Similar to the regular if statement. It can be used in conjunction with #define and it must be accompanied by the #endif.

#ifdef

#ifdef TOKEN//true if token hasbeen defined#endif

This directive returns true if the specified token has been defined

#ifndef#ifndef TOKEN#define TOKEN

#endif

This directive returns true if the specified token has not been defined.

#elif

#if defined(TOKEN_1)//your code

#elif defined(TOKEN_2)//more code

Similar to the else if clause of the regular if statement.

Page 48: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 48 of 54

#endif

#else

#ifndef TOKEN#define TOKEN

#else#define TOKEN_1

#endif

This token has the same purpose as the else clause of the C++ if statement.

99..00..22 –– CCoonnddiittiioonnaall CCoommppiillaattiioonn 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_PCtoken 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 well-developed, complex program.

Page 49: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 49 of 54

• 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.

Page 50: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 50 of 54

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.

Page 51: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 51 of 54

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 1100..00..11 –– IInnttrroodduuccttiioonn aanndd ddeeffiinniittiioonn 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.

1100..00..22 –– TThhee nneeww aanndd ddeelleettee ooppeerraattoorrss 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 it’s 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 itint *ptrInt=new int;

//assign a value to the dynamic integer

Page 52: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 52 of 54

*ptrInt=120;

//delete it to free memorydelete 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 a number: 45You entered: 45 @ address: 0x00790D30Please enter a number: 35You entered: 35 @ address: 0x00790D30Please enter a number: 63You entered: 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.

1100..00..33 –– DDyynnaammiicc AArrrraayyss 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 ‘myName’char *newArray = new char[strlen(myName)+1];

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

Page 53: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 53 of 54

strcpy(myName, newArray);//once finished using the newArray, delete it from memorydelete(newArray); Example: #include <iostream.h>#include <string.h>

void main(){

//create a temporary array of 100 characterschar temp[100];cout << "Please enter your first name: ";cin >> temp;

//create a character pointer and assign it a new character arraychar *myName=new char[strlen(temp)+1];

//assign the new array the value of the temporary arraystrcpy(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: ANDREWThe size of the temp array is 100The contents are: ANDREWThe size of the myName array is 7The 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

Page 54: Intermediate C++ Programming - · PDF fileIntermediate C++ Programming Copyright American Computer Experience, 2001 Page 4 of 54 Goals The goals of a course encompass what the student

Intermediate C++ Programming

Copyright American Computer Experience, 2001 Page 54 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.