Lecture Notes Introduction To Programming Semester 2 2022
Lecture Notes Introduction To Programming Semester 2 2022
&
Computer Sciences
Module Title:
Introduction to
Programming and
Problem Solving
Module Aim:
Accessing Files in the
computer system.
The different user defined
complex type of data:
structures, arrays, classes.
Pointers and linked lists
1
Introduction to Programming
and Problem Solving
Module Title:
Introduction to Programming and Problem Solving
Module Regulation:
This module is not condonable, means that students pass the module only if the mark is
greater than 40.
The pass of this module is a must to progress to next year.
Module Code:
20CSCI02P
Assessment:
1. In-Lab test 1 carries 25% of the total mark and aims to develop and assess learning
outcomes 1 - 3. It covers lectures 1, 2 and 3 in Week 7.
2. In-Lab test 2 carries 25% of the total mark and aims to develop and assess learning
outcomes 4 - 6. It covers lectures 4, 5 and 6 in Week 11.
3. Final examination carries 50% of the total mark and assesses learning outcomes 1 - 6.
Text Book:
Tony Gaddis, "Starting Out with C++: From control structures through objects", 7th
Edition, Pearson, 2012.
Nell Dale, Charles C. Weems, "Programming and Problem Solving with C++, 4th Edition",
Jones and Bartlett Publishers, Sudbury, MA, 2004, 1100 pp.
2
2
Introduction to Programming
and Problem Solving
Weekly Plan:
Week Lecture Lab Assessment
1 Files (1) ---
2 Files – Part (2) Files (1)
3 1D arrays Files – Part (2)
4 2D Arrays 1D arrays
5 Structure 2D Arrays
6 Revision Revision
7 Pointers Structure In lab test (1)
8 Classes Pointers
9 Revision Classes
10 Revision
11 --- In lab test (2)
12 ---
3
Introduction to Programming
and Problem Solving
4
Introduction to Programming
and Problem Solving
Contact List:
Module Leader :"Mostafa Salama" mostafa.salama@bue.edu.eg
Senior Teaching Assistant: "Basma.Hathout" Basma.Hathout@bue.edu.eg
Senior Teaching Assistant: "Lobna.Hesham" Lobna.Hesham@bue.edu.eg
Teaching Assistant: "aya.Hesham" ayah.hesham@bue.edu.eg
Teaching Assistant: "Eslam.Hesham" eslam.hesham@bue.edu.eg
5
So far learned in C++
char
Data Types int
bool
Complex Primitive
double
Data Types Data Types
String float
Libraries cmath
iostream
Functions
Conditional if
Control statements
Statements switch
Loops for
while 6
So far learned in C++
int x;
This line is a variable definition, x is of a simple data type int. A place in
the memory is reserved for the integer x. The data type of this variable is
integer, which means that this place in the memory is prepared to save
integers only.
string str = "BUE"; //string is a class, and str is object of this class.
str.at(1); //function at() in the class string is applied on text "BUE".
The datatype of the object str is the class “string” in the string library. A
class is a complex datatype that does not contains data only, but
contains functions also. The class string contains a data text and contains
functions to operate on the data, like substr(), at(), and find(). Any
object of type class string contains a text and the same functions in the
class string.
Characters, integer, double, float and bool variables holds only one data
value, that is why called simple. While objects holds various data values
like string, it contains various characters, that is why called complex.
7
Introduction to Programming
and Problem Solving
Lecture 1
Files and File Streaming
9
Program 1 : files
5. #include <fstream>
A C++ program can create, edit and delete files within the file system of
the computer. C++ provides a built-in library fstream to allow programs
to access files. The library contains three classes ofstream, ifstream, and
fstream.
To create a file for writing, define an object of type ofstream. The
letters o in the term ofstream stands for output, and f for file, and
stream refers to the data. This object allows the creation of a file for
writing data, e.g. demofile.txt.
To access an existing file for reading, define an object of type
ifstream. The letters i in the term ifstream stands for input. This
object allows reading of the text in the file only without adding any
text.
To access an existing file for reading and writing, define an object of
type fstream. This object allows openning files for reading, writing, or
both.
10
Program 1 : files
8. ofstream outputFile;
9. outputFile.open("demofile.txt");
11. outputFile << "British \n";
Line 8 defines an object outputFile
of type class ofstream. This object
allows the creation of a file for
writing.
Line 9 uses the object outputFile
to open a file of name
“demofile.txt”. If the file dose not
exist, the object outputFile creates
an empty file of this name. Line 9
creates the file on the same path of
the C++ code project. To specify a
different path of the file, the new
path is added as follows: “c:\\
data\\demofile.txt”.
9. outputFile.open("c:\\data\\demofile.txt");
11
Program 1 : files
8. ofstream outputFile;
9. outputFile.open("demofile.txt");
11. outputFile << "British \n";
12. outputFile << "University \n";
13. outputFile << "In Egypt \n";
14. outputFile.close();
Lines 11, 12 and 13 use the object outputFile to write a text, e.g. “In
Egypt \n”, in the file “demofile.txt”. The object outputFile uses the
stream insertion operator (<<) to write text in the file. C++ uses the same
syntax to write data in the command prompt and the file. The term “cout”
is replaced by the object name outputFile to write on the file instead of
the command prompt. Each string that was written to the file ends with a
newline escape sequence (\n).
Line 14 uses the object outputFile to close the access to the file. Closing
a file causes any unsaved data that may still be held in a buffer to be
saved to its file. This frees unnecessary resources for better performance,
like removing the buffered file contents that is allocated in the memory.
12
Program 2 : Writing to files
1 outputFile
1. #include <iostream>
2.
3.
#include <fstream>
using namespace std;
2
4. int main() { 4
5. //1-Define object outputFile for writing
6. ofstream outputFile;
15. return 0;
16.}
13
Program 2 : Writing to files
6. ofstream outputFile; 1-Define
8. outputFile.open("file1test.txt"); 2-Open
11. outputFile << "User "<< i << " : \n"; 3-Write (access)
14. outputFile.close(); 4-Close
14
Program 3 : Reading from files
1. #include <iostream>
2. #include <string>
3. #include <fstream>
4. using namespace std;
5. int main() {
6. ifstream inputFile;//For reading
7. inputFile.open("file2test.txt");
8.
9. for (int i = 1; i <= 9; i++) {
10. string temp, name;
11. //input1File >> temp; // do not work correct, because of the space
12. getline(inputFile, temp);
13. int nameStart = temp.find(':')+2;
14. int nameLength = temp.size() - nameStart;
15. name = temp.substr(nameStart, nameLength);
16. cout << name << endl;
17. }
18. inputFile.close();
19. return 0;
20. }
15
Program 3 : Reading from files
6. ifstream inputFile; 1-Define
7. inputFile.open("file2test.txt"); 2-Open
11. getline(inputFile, temp); 3-Read (access)
14. inputFile.close(); 4-Close
1. #include <iostream>
2. #include <fstream>
3. #include <string>
4. using namespace std;
5. int main(){
6. ifstream inputFile;
7. string text;
8. inputFile.open("file2test.txt"); //Open the file for reading.
9. if (inputFile){ //Check that the file opens correctly.
10. while (inputFile >> text){ //Check that end of file is not reached yet.
11. cout << text << endl;
12. }
13. inputFile.close();//close the file
14. }
15. else{
16. cout << "Error opening the file.\n";
17. }
18. cin >> text;
19. return 0;
20. }
17
Program 4 : Reading from files
8. inputFile.open("file2test.txt"); //Open the file for reading
9. if (inputFile){ //Check that file opens correctly
10. while (inputFile >> text){ //Check that end of file is not reached yet
11. cout << text << endl;
12. }
13. inputFile.close(); //close the file
14. }
This program tests if the file is opened for reading successfully. Then the
program keeps reading terms from the file until its end.
Step 1: Defining an object of type ifstream for reading from a file.
Step 2: Opening the file existing in the file system for reading. In the case that this
file does not exist, the if condition in line 9 is going to be false. An in the case that
this file exists and opened successfully.
Step 3: Quite often a program must read the contents of a file without knowing the
number of terms that are stored in the file. Lines 10 keeps getting a term from the
file until no more terms are remained to get. A term is a word or a number without
spaces, a “User” word, “1” is number term, and “:” is special character term. In
the case that the statement of “inputFile >> text” get a term successfully from
the file, then the statement has the value true. And in case that the file ends and
no more term exists to be retrieved.
Step 4: When the loop for reading ends, line 13 closes the file to free the allocated
resources for this file.
18
Program 5 : Reading & Writing
7. void main() {
8. string FullNames = " ", name;
9. fstream rwFile;
18. }
19
Program 5 : Reading & Writing
9. fstream rwFile;
10. rwFile.open("Friends.txt", ios::in); //==> rwFile >> name
14. rwFile.close();
15. rwFile.open("Friends.txt", ios::app); //==> rwFile << FullNames
17. rwFile.close();
The datatype of object “rwFile” is the class fstream. This type of objects allows
the program to do both, reading from a file and writing into a file.
Line 9 defines an object of type fstream for accessing (read/write) a file in the system.
Line 10 uses the fstream object to open a file for reading. The open() function in thie
fstream object has two parameters, the first parameter is the file name, and the second
parameter is the purpose of the opening the file. If the purpose of opening that file is
reading, then the second parameter is ios::in. This fstream object use the operator (>>)
to read text terms from the file, and uses the close() function to close the file.
Line 15 uses the same fstream object to open a file for writing. If the purpose of opening
that file is adding text to the end of the file (appending), then the second parameter in the
open function is ios::app. This fstream object use the operator (<<) to write text into
the file, and uses the close() function to close the file.
Note that after reading the file, the object close the file and re-open it for the new purpose
which is writing (app).
20
Program 5 : Reading & Writing
11. while (rwFile >> name) {
12. FullNames = name + FullNames;
13. }
Line 11 shows a while statement, the condition of continue looping is that the file still contains
text to read. The condition between the while brackets() is a reading statement that is either
successful in reading (true) or not (false).
If the reading statement {rwFile >> name} in line 11 reads a text successfully, then the file
is not ended yet. In this case, the system considers that the result of reading is true and the
while loop runs the statement in line 12.
If the reading statement in line 11 fails to read data, then this means that files ends and no
more text to read. In this case, the system considers that the result of reading is false and
the while loop terminates.
9. fstream rwFile;
14. rwFile.open("Friends.txt", ios::out);
15. rwFile.close();
If the second parameter in the open function is ios::out, The file is opened for writing.
If the file does not exist, it is created.
If the file already exists, its contents are deleted (the file is truncated). The file is opened
as empty file and the new text is added at the beginning of the file.
21
Program 6 : Reading & Writing
1. #include <iostream>
2. #include <fstream>
3. #include <string>
4. using namespace std;
5. int main(){
6. string filename = "TestRW.txt", buffer;
7. fstream outputfile, inputfile;
8. outputfile.open(filename, ios::out); if (outputfile.fail()) return 0;
9. outputfile << "British University in Egypt"; outputfile.close();
Lines 6 and 7 defines 4 objects, line 6 defines two string objects and line 7 define two fstream
objects. Both fstream objects will access the same file, but one for writing (out) and one for
reading (in).
The object “outputfile” is for writing (out). The second statement in line 8 is a conditional
statement that tests if the condition (outputfile.fail()) is true or false. The fail() function in
the fstream objects returns true if the file fails to create or open, the reason of failure could be
due to the permission/security of the computer system or the storage is full.
In general, the return statement ends the program. Here the program terminates if the
outputfile object fails to open the file.
Line 9 writes in the file the statement “British University in Egypt” and then closes the
file.
Line 10 uses the fstream object to open a file for reading (in). It tests if the inputfile object
fails to open file. If it fails to open, then the program terminates. the file fails to open due to
reasons like the file does not exist or no permissions to open the file,
23
Program 6 : Reading & Writing
12. inputfile.seekg(0, ios::beg); inputfile >> buffer; cout << buffer << endl;
14. inputfile.seekg(3, ios::beg); inputfile >> buffer; cout << buffer << endl;
16. inputfile.seekg(-5, ios::end); cout << buffer << endl;
In general, reading from a file starts from the beginning of the file, and continues to the end of
the file. The position of the reading pointer from a newly opened file is zero, and program read a
text the reading pointer moves to the position of next text to read.
seekg() sets the position of the next character to be extracted from the file input stream. The
word seek mean to search or to look out for getting something. And the character g refers to the
getting action. If the program requires to read from a specific position, it moves the reading
pointer to this position. The inputfile object of type fstream has the function “seekg”, this
function moves reading pointer to any position within the file.
The function seekg(position, offset) has two parameters. The position refers to the location
where the program should start reading, while the offset refers to the place of start counting the
location from. For example, line 12 starts reading from the beginning and count 0 characters,
while line 14 starts from the beginning and then place the reading pointers after three
characters.
24
Program 6 : Reading & Writing
12. inputfile.seekg(0, ios::beg); inputfile >> buffer; cout << buffer << endl;
14. inputfile.seekg(3, ios::beg); inputfile >> buffer; cout << buffer << endl;
16. inputfile.seekg(-5, ios::end); cout << buffer << endl;
Line 12 places the reading pointer at position 0 from the beginning, then reads a string from the
file. Since the reading operator () ends after space, so it reads the word “British” only.
Line 14 places the reading pointer at position 3 from the beginning, then reads a string from the
file. It starts reading after third character in the word “British”, so starts at character t and ends
at h before the space as “tish”.
Line 16 places the reading pointer at 5 places (characters) before the end of the file. It moves
backward by 5 characters before the end of the file.
25
Program 7 : Reading & Writing
1. #include <iostream>
2. #include <fstream>
3. #include <string>
4. using namespace std;
5. int main() {
6. fstream accessFile;
7. accessFile.open("Trial.txt", ios::out);
8. accessFile << "abcdefghijklmnopqrstuvwxyz" << endl;
9. accessFile.close();
18. return 0;
19. }
26
Program 7 : Reading & Writing
8. accessFile << "abcdefghijklmnopqrstuvwxyz" << endl;
10. accessFile.open("Trial.txt", ios::in);
12. while (!accessFile.eof()) {
13. accessFile.seekg(2, ios::cur);
14. accessFile >> c;
15. cout << c << endl;
16. }
Lines 8 uses the object “accessFile” to write in the text file "Trial.txt" the alphabet from
‘a’ to ‘z’, then this object closes the file.
Line 10 uses the object “accessFile” to read from the text file "Trial.txt". Line 12 shows a
looping statement that continue iterating if the object “accessFile” did not reach the end of
the opened file “eof”.
Notice that when the file is opened for reading, the reading pointer starts at the first position of
index zero.
In line 13, the object “accessFile” uses the seekg() function to move the reading pointer from
the current position “ios::cur” by two character. Then line 14 reads the character at the
position where the reading pointer is pointing to, then line 15 prints this character.
Lines 13, 14, and 15 are repeated until the end of file “eof” is reached.
Notice that when object “accessFile” read the character ‘x’, the reading pointer points to the
character ‘y’. And when the reading pointer moves by two character by the “seekg()” function,
the pointer reaches the end of the file and nothing to read. In this case, line 14 fails to read any
character, and so the value of c remains of the same value x. 27
Sample Problem: to be solved by the
student for training.
Write a C++ program that receives from the user 10 integers.
This program creates two files, one for odd number “oddFile.txt”, and
one for even numbers “evenFile.txt”
For every entered integer by the user, the program checks this number:
If this number is even, then it is added to the “evenFile.txt”,
Otherwise this number is added to the “oddFile.txt”.
Then write a function that calculates the averages of the values in a
file. Then call this function twice, once for the “evenFile.txt” file and
once for the “oddFile.txt” file. Then print the two average values.
28
28
Sample MCQ for Programming
So far :
1. What is the output of the following Program? 2. What is the output of the following Program? If the
1. #include <iostream> Test2.txt file contains online one line : "British
2. #include <fstream>
University in Egypt [ICS]"
3. #include <string>
1. #include <iostream>
4. using namespace std;
2. #include <fstream>
5. void main(){
3. #include <string>
6. fstream dataFile;
4. using namespace std;
7. string name;
5. void main() {
8. dataFile.open("demofile.txt", ios::out);
6. string filename = "Test2.txt", buffer;
9. dataFile << "string1" << "\n";
7. fstream inputfile;
10. dataFile.close();
8. inputfile.open(filename, ios::in);
11. dataFile.open("demofile.txt", ios::out);
9. inputfile.seekg(8, ios::beg);
12. dataFile << "string2" << "\n";
10. inputfile.seekg(-2, ios::cur);
13. dataFile.close();
11. inputfile >> buffer; cout << buffer <<
14. dataFile.open("demofile.txt", ios::in);
endl;
15. if (dataFile.eof()) cout << "END";
12. inputfile.close();
16. else{ dataFile >> name;cout << name; }
13. }
17. dataFile.close();
18. }
a) itish
b) h
a) String2 c) Uni
b) “Run time error in line 8” d) “Nothing is printed”
c) “Run time error in line 14” e) “Run time error”
d) String1String2
e) String1
29
Introduction to Programming
and Problem Solving
Lecture 2
Arrays
11. cout << "y[0] = " << y[0] << endl; //Prints 23
12. cout << "y[1] = " << y[1] << endl; //Prints 41
13. cout << "y[2] = " << y[2] << endl; //Prints rubbish
14. //Warning: Index '3' is out of valid index range '0' to '2'
15. cout << "y[3] = " << y[3] << endl;
16. cout << "The size of the array y is : " << sizeof(y) << endl;
17. return 0;
18. } 31
RAM
Lines 4 defines a primitive datatype, which is the integer variable x. Any variable of a primitive
datatype is designed to hold a single value. The size of this variable in memory is 4 bytes. The
variable x is also initialized to the value ‘10’.
The size of the array y is three, such that this array can hold 3 integer values. The entire array
has only one name, and each element in the array is accessed by a unique index. The statement
“y[0] = 23;” in line 7 saves the value 23 in the array y in the first element of index 0.
The index of the elements in the array starts by the index 0 to first element, followed by second
element of index 1, and the third element is of index 2. Accordingly, if the size of the array is
three, then the index of the last element is 2.
32
RAM
Unlike variables, if the value of one element in the array is not initialized, the program will run
without a compile-time error or a run-time error, but the value of this non-initialized element is
rubbish. The rubbish value printed on the output screen is “-858993460”.
The range of indexes of the array is based on its size, if the size of the array is 3 then the range
of values starts from 0 to 3-1. If the index used in accessing values in the array is not in the
correct range, then the value of this index is rubbish. The index is said to be not in the correct
range if it is of a negative value or its value is greater than the size of the array -1.
Line 17 uses the sizeof() function to print the size of the array y. The array y holds three
integers and the size of an integer is 4 bytes, then the memory allocated for this array y is of
size 4x3 which is 12 bytes. 33
Program 9 : Looping in Array
1. #include <iostream>
2. using namespace std;
3. int main() {
15. return 0;
16. }
34
Program 9 : Looping in Array
4. const int nEmp = 6;
5. int eSal[nEmp], sum=0;
6. for (int i = 0; i < nEmp; i++) {
7. cout << "Enter the salary of Employee ";
8. cout << i + 1 << " : ";
9. cin >> eSal[i];
10. }
Lines 4 defines a constant integer nEmp of a value 6. Then line 5 uses this constant integer to set
the size of the array of integers eSal.
When defining an array, the number of values in the array must be either a value or a constant
integer. It can not be a variable because the size of the array should be predefined and can not
be changed during the running of the program.
If line 4 defines nEmp as a variable, the compiler shows an error “expression must have a
constant value” in line 5.
The for loop in line 5 iterates on all the elements of the array, starting by the element at index
zero (0), and ending by the element at index (nEmp-1). The number of iterations of this for loop
is 6 iterations. At each iteration, the statements in lines 7, 8 and 9 get a value from the user and
set this value to the iterated element in the array.
The for loop in line 11 iterates on all the elements. At each iteration, the statement in line 12
gets a value from the iterated element in the array and add it to the sum value.
35
Program 10 : Array Size Constant
1. #include <iostream>
2. using namespace std;
3. int main() {
4. const int s = 10;
5. int age[s] = {13, 10, 20, 21, 31, 25, 14};
15. return 0;
16. }
36
Program 10 : Array Size
Constant
4. const int s = 10;
5. int age[s] = {13, 10, 20, 21, 31, 25, 14};
Lines 5 defines a constant integer 6 of a value 10. Then line 6 uses this constant integer to set
the size of the array of integers age.
Line 6 defines and initializes the array age. The initialization list in line 6 is a series of values
separated by commas and between curly brackets. These values are stored in the array elements
in the order they appear in the list.
The array in line 6 reserve in the memory 10 places, and so C++ expects to be initialized by 10
elements. Three cases are expected here:
If the list includes exactly 10 elements, then the 10 elements are places in the 10 places of
the array.
If the list includes less number of elements as the statement of line 6 that includes 7
elements only, then C++ completes the list in the array by zero values.
{13, 10, 20, 21, 31, 25, 14, 0, 0, 0}
If the list includes more number of elements, a compile time error appears “too many
initializer values”.
The array can be defined and initialized without setting its size, C++ will reserve a number of
places in the memory exactly according the number of values in the list.
int age[] = {13, 10, 20, 21, 31, 25, 14};
37
Program 10 : Array Size
Constant
7. for (int i = 0; i < s; i++) cout << age[i] << ", ";
12. for (int i = s-1; i >= 0; i--) cout << age[i] << ", ";
Lines 7 iterates through elements of the array, starting from the first of index 0 to the last
element of index 9. As shown in the output, the array includes the 7 values used in the
initialization list, while the rest of the elements in the array are initialized by zero.
{13, 10, 20, 21, 31, 25, 14, 0, 0, 0}
Lines 12 iterates through elements of the array in a reverse order, starting from the last of
element in the array of index 9 (s-1) to the first element of index 0. As shown in the output:
{0, 0, 0, 14, 25, 31, 21, 20, 10, 13}
It is important to remember that in C++, the values of the elements in the array are initialized to
zero if the array is not initialized.
38
Program 11 : Function call
1. #include <iostream>
2. using namespace std;
3. int find(int arr[], int size, int query) {
4. for (int i = 0; i < size; i++) {
5. if (arr[i] == query)
6. return i;
7. }
8. return -1;
9. }
10. int main(){
11. int q;
12. const int s = 10;
13. int age[s] = { 10, 12, 14, 17, 11, 2, 4, 5, 12, 11};
14. cout << "What is the number you are looking for ? ";
15. cin >> q;
16. int result = find(age, s, q);
17. if (result != -1)
18. cout << "The number you entered is of index " << result;
19. else
20. cout << "The number you entered is not found ";
21. return 0;
22. }
39
Program 11 : Function call
12. const int s = 10;
13. int age[s] = { 10, 12, 14, 17, 11, 2, 4, 5, 12,
11};
16. int result = find(age, s, q);
17. int find(int arr[], int size, int query) {
9. }
The main function passes the array age, the constant s, and the
Int find(arr[], …) {
variable q to the function find(,,). The value of size is }
equals to the value of s in the main() function, and the value of
query is equals to the value of q in the main() function.
The first parameter in the function find(int arr[], int int main(){
age[s] = { 10, 12, …
size, int query) is the array arr[]. Notice that the array
find(age, …
parameter arr[] does not include the size of the array }
between the box brackets.
After calling the function in line 16, the array age[] in the
function main() is passed by reference to the array arr[] in
the function find(,,). arr[] 10 12 14
Pass by reference means that both array names age[] and
arr[] are referring to the same array. And inside the body of age[]
function find(,,), the array arr[] is referring to the
elements in the array age[].
40
Program 11 : Function call
3. int find(int arr[], int size, int query) {
4. for (int i = 0; i < size; i++) {
5. if (arr[i] == query)
6. return i;
7. }
8. return -1;
9. }
The main function passes the array age, the constant s, and the variable q in the function call
find(age, s, q). The role of this function is to find a specific value q in the array age of size
s.
The for loop in line 4 iterates for (size = s) times across the elements in the array (arr[i] =
age). And at each iteration, the condition in line 5 tests if element arr[i] in this iteration is
equal to the value of query.
So it tests if (arr[0]==query), (arr[1]==query), (arr[2]==query) … and (arr[size-
1]==query).
However, if one of these tests succeeded, then the required number (query) is found and no
need to continue searching. So, the function terminates the loop by returning the index of the
found element.
The statement (return i;) in line 6 terminates the function and returns the index of the
required element. And the statement return -1; in line 8 terminates the function and returns
the value of -1 which means the q or query is not found in the array age or arr.
41
Program 12 : Array of characters
1. #include <iostream>
2. using namespace std;
3. bool compare(char arr1[], char arr2[], int size) {
4. bool equal = true;
5. for (int i = 0; i < size; i++) {
6. if (arr1[i] != arr2[i])
7. equal = false; strArray1 E g y p t
8. }
9. return equal;
10. } strArray2 E g y p t
11. int main() {
12. char strArray1[] = { 'E','g','y', 'p', 't' };
13. char strArray2[] = "Egypt";
14. bool result = compare(strArray1, strArray2, 5);
15. if (result)
16. cout << "The two arrays are identical";
17. else
18. cout << "The two arrays are not identical";
19. return 0;
20. }
42
Program 12 : Array of characters
12. char strArray1[] = { 'E','g','y', 'p', 't' };
13. char strArray2[] = "Egypt";
14. bool result = compare(strArray1, strArray2, 5);
15. bool compare(char arr1[], char arr2[], int size) { .. }
Lines 12 and 13 define two arrays of characters strArray1 and strArray1. Both arrays are of
the same number of elements, and also the elements in both arrays are identical. However, both
arrays are initialized by two different ways.
The first array is initialized using the curly bracket to enclose a set of characters that are
separated by a comma. Note that the number of elements in both arrays is not stated in the box
brackets, this is because C++ can indicate the number of the elements of an array by counting
the initialized number of elements between the curly brackets {}.
The second array is initialized as a string between double Quotations "Egypt", as the string is
known as a series of character. C++ considers the first character in the string "Egypt" as a the
first character in the array strArray2[0]='E', and the second character in the string "Egypt"
is the second character in the array strArray2[1]='g', and so on.
Both arrays are passed as parameters to function compare() as arr1[], arr2[]. This function
compares between each pair of corresponding characters in both arrays. If all pairs of
corresponding characters do no follow this condition (arr1[i] != arr2[i]), then these two
arrays are identical and the function returns true. If this condition is true for any pairs of
corresponding characters, then this function returns false.
43
Program 13 : Save to File
1. #include <iostream>
2. #include <fstream>
3. #include <string>
4. using namespace std;
5. void saveToFile(string arr1[], int arr2[], double arr3[], int sizeOfArrays) {
6. ofstream outputFile;
7. outputFile.open("SavedNumbers.txt");
8. outputFile << "Day" << "\t\t" << "# Visitors" << "\t" << "Income" << "\n";
9. for (int count = 0; count < sizeOfArrays; count++) {
10. outputFile << arr1[count] << "\t\t";
11. outputFile << arr2[count] << "\t\t";
12. outputFile << arr3[count] << "\n";
13. }
14. outputFile.close();
15. }
16. int main() {
17. const int size = 7;
18. int numVisitors[size] = { 5, 4, 17, 14, 15, 12, 43 };
19. double income[size] = { 312.1, 211.5, 111.8, 412.9, 400, 500, 1300.4 };
20. string days[size] = {"Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri" };
21. saveToFile(days, numVisitors, income, size);
22. return 0;
23. } 44
Program 13 : Save to File
18. int numVisitors[size] = { 5, 4, 17, 14, 15, 12, 43 };
19. double income[size] = { 312.1, 211.5, 111.8, 412.9, 400, 500, 1300.4 };
20. string days[size] = {"Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri" };
21. saveToFile(days, numVisitors, income, size);
45
Program 14 : 1-Dim Array
1. #include <iostream>
2. using namespace std;
3. void getValues(int arr[], int size) {
4. for (int i = 0; i < size; i++) {
5. cout << "enter value " << i + 1 << " : ";
6. cin >> arr[i];
7. }
8. }
9. int maxValue(int arr[], int size) {
10. int max = -1;
11. for (int i = 0; i < size; i++) {
12. if (max < arr[i]) max = arr[i];
13. }
14. return max;
15. }
16. void main() {
17. const int size = 7;
18. int data[size];
19. cout << "Please enter 7 values between 0 and 100 : \n";
20. getValues(data, size);
21. int maxVal = maxValue(data, size);
22. cout << "Max is " << maxVal << " \n ";
23. }
46
Program 15 : 1-Dim Array
1. #include <iostream>
2. using namespace std;
3. const int arrSize = 10;
4. void getData(int array[], int sizeOfArray){
5. cout << "Please enter " << sizeOfArray << " integers: \n";
6. for (int i = 0; i < sizeOfArray; i++)
7. cin >> array[i];
8. }
9. }
10. void main(){
11. int array[arrSize];
12. getData(array, arrSize);
13. int sumPair = 0;
14. cout << "Enter a number : "; cin >> sumPair;
15. cout << "Array pairs whose sum equal to " << sumPair << " :\n";
16. int counter = 0;
17. for (int i = 0; i < arrSize; i++)
18. for (int j = i + 1; j < arrSize; j++)
19. if (array[i] + array[j] == sumPair){
20. cout << array[i] << "," << array[j] << endl;
21. counter++;
22. }
23. cout << "Number of pairs whose sum equal to " << sumPair;
24. cout << " is " << counter << "\n"; 47
Program 16 : 1-Dim Array
1. #include <iostream>
2. using namespace std;
3. int main(){
4. const int s = 10;
5. int userInput, i = 0;
6. int age[s];
7. while (i < s) {
8. cout << "Enter a positive number less than 100 : ";
9. do {
10. cin >> userInput;
11. if (userInput > 100)
12. cout << "The number is greater than 100, enter again : ";
13. } while (userInput > 100);
14. age[i++] = userInput;
15. }
16. int counterOdd = 0, counterEven = 0;
17. for (int i = 0; i < s; i++) {
18. if (age[i] % 2 == 0) counterEven++;
19. else counterOdd++;
20. }
21. cout << "The number of even numbers entered is : " << counterEven << "\n";
22. cout << "The number of odd numbers entered is : " << counterOdd << "\n";
23. return 0;
24. } 48
Program 17 : Sorting
1. #include <iostream>
2. using namespace std;
3. void sortArr(int arr[], int s) {
4. for (int i = 0; i < s; i++) {
5. for (int j = i + 1; j < s; j++) {
6. if (arr[i] > arr[j]) {
7. int temp = arr[i];
8. arr[i] = arr[j];
9. arr[j] = temp;
10. }
11. }
12. }
13. }
14. int main() {
15. const int s = 10;
16. int age[s] = {13, 10, 20, 21, 31, 25, 14};
17. sortArr(age, s);
18. //print the array in a sorted order
19. for (int i = 0; i < s; i++) {
20. cout << age[i] << ", ";
21. }
22. return 0;
23. } 49
Program 17 : Sorting
15. const int s = 10;
16. int age[s] = {13, 10, 20, 21, 31, 25, 14};
17. sortArr(age, s);
18. void sortArr(int arr[], int s) {
13. }
Lines 15 defines an a constant integer s of a value 10. Then line 16 uses this constant integer to
set the size of the array of integers age, and initializes the array by 10 elements.
Then line 17 is a function call statement sortArr(age, s). This function call will hold the
processing of the main function and start processing the code in the function sortArr(). After
finishing the code in the function, the code in the function resumes processing in line 19.
The main function passes the array age and the variable s to the function sortArr(,). The
array is passed by reference without using the address operator &. Pass by reference means that
any change in the array elements or the order of these elements in the array, the change will be
applied in the original array in the main function. The array is always passed by reference using
its name only without the address operator.
The function sortArr(int arr[], int s) starts working after being called in line 17. This
function does not return any data, as the return data type is void which means that it has no
return statement.
The role of this function is to change the order of the elements within the passed array. These
elements are not sorted and the role of this function is to sort these elements in an ascending
order. The original array will be changed after running the code in this function.
50
Program 17 : Sorting
4. for (int i = 0; i < s; i++) {
5. for (int j = i + 1; j < s; j++) { i j
0 1 2 3 4 5 6 7 8 9
6. if (arr[i] > arr[j]) {
2
7. int temp = arr[i]; arr[] 13 10 20 21 31 25 14 0 0 0
Swap
10. } i j
11. } 0 1 2 3 4 5 6 7 8 9
12. } arr[] 10 13 20 21 31 25 14 0 0 0
The code includes two nested loops in lines 4 (10 is not > 20)
and 5, and keep comparing each pair of i
No Swap
j
elements in the array in line 6. Lines 7, 8 and 9 0 1 2 3 4 5 6 7 8 9
swap elements to place the smaller element arr[] 10 13 20 21 31 25 14 0 0 0
before the largest elements in the array. (10 is not > 21)
No Swap
In the first iteration in the outer-loop, the first ………
i j
element of index i=0 is 13 and is compared, by 0 1 2 3 4 5 6 7 8 9
the second element of index j=1, if it is arr[] 10
2
13 20 21 31 25 14 0 0 0
greater, then the two elements are swapped.
(10 > 0) 1
Swap 3
Then the first element of index i=0 is temp 10
compared to the third element of index j=2, if i ……… j
0 1 2 3 4 5 6 7 8 9
it is greater, then swapping and so on until the 2
last element is reached in the array by the arr[] 0 13 20 21 31 25 14 10 0 0
This process continues until all the elements in (20 is not > 21)
No Swapping
the array are sorted in an ascending order.
52
Program 18 : 2-Dim Array
1. #include <iostream>
2. using namespace std;
3. int main() {
4. const int rows = 2, cols = 4;
5. int grades[rows][cols] = { {73, 35, 63, 81}, {63, 56, 31, 21} };
6. cout << "The total size of the array in bytes : ";
7. cout << sizeof(grades) << endl; grades[2][4]
8. int avgPerRow, avgTotal = 0; First col Sec col Third col Four col
9. for (int i = 0; i < rows; i++) { First
[0][0] [0][1] [0][2] [0][3]
10. avgPerRow = 0; row
Second
11. for (int j = 0; j < cols; j++) { row [1][0] [1][1] [1][2] [1][3]
12. avgPerRow = avgPerRow + grades[i][j];
13. }
14. avgPerRow /= cols;
15. cout << "The average value of the values in row ["; grades[rows][cols]
16. cout << i << "] is " << avgPerRow << endl; 73 35 63 81
17. avgTotal += avgPerRow; 63 56 31 21
18. }
19. avgTotal /= rows;
20. cout << " The average value of the average of all rows";
21. cout << " is " << avgTotal << endl;
22. return 0;
23. }
53
Program 18 : 2-Dim Array
4. const int rows = 2, cols = 4;
5. int grades[rows][cols] = { {73, 35, 63, 81}, {63, 56, 31, 21} };
6. cout << "The total size of the array in bytes : ";
7. cout << sizeof(grades) << endl;
Line 3 defines a global constant integer Cols of a value 3. This constant integer is defined as
global because it is defined outside any function. This constant can be accessed from any
function, either main() or getMax() functions.
Line 13 defines a local constant integer Rows of a value 3. This constant is defined as local
because it is defined within the main() function. This constant can be accessed from the main()
function only that is defined within.
Line 14 defined an array of two dimensions, the first dimension of size [Rows] and the second
dimension of size [Cols].
Line 15 defines an array of strings of size [Rows]. This array is used for text representation of the
rows in the two-dimensional array.
The first row in the array is of index 0
The first row in the array is of index 1
The first row in the array is of index 2
57
Program 19 : Pass 2-Dim Array
23. cout << "Maximum Value is : " << getMax(array, 2);
24. int getMax(int arr[][C], int R) {
25. int max = 0;
26. for (int i = 0; i < R; i++) {
27. for (int j = 0; j < C; j++)
28. if (max < arr[i][j]) max = arr[i][j];
29. }
30. return max;
31. }
Line 23 calls the function getMax(array, 2) and passes to this function the two-dimensional
array array, and an integer R that represents the number of rows in this array.
Line 4 defines the function header “int getMax(int arr[][C], int R)”. The first parameter
of this function is array “int arr[][C]”.
The first box bracket that represents the size of the rows of the array arr is empty. It is
unknown to the function and should be passed separately through the second parameter
“int R” of the function.
The second box bracket that represents the size of columns of the array arr is the global
constant C. In C++, the two-dimensional array parameter in a function definition must
include the size of columns.
The two nested loops in lines 6 and 7 go through all the elements in the array arr. These two
nested loops search for the maximum value among a group of positive value, such that the
minimum value must be zero. The initial value of the maximum max is zero as defined in line 5. 58
Program 20 : Pass 2-Dim Array
1. // symmetric or not.
2. #include <iostream>
3. using namespace std;
4. const int cols = 3;
5. // Returns true if mat[N][N] is symmetric,
6. // else false
7. bool isSymmetric(int mat[][cols], int N) {
8. for (int i = 0; i < N; i++)
9. for (int j = 0; j < N; j++)
10. if (mat[i][j] != mat[j][i])
11. return false;
12. return true;
13. }
[ ]
18.
19. else
cout << "This matrix is symmetric."; 1 3 5
20. cout << "This matrix is not symmetric."; 3 2 4
21. return 0;
22. }
5 4 1
59
Sample Problem: to be solved by the
students for training.
Write a C++ program to get from the user the results of 10 students, then saves the results in a file:
1. Define in the “main()“ function two-dimensional array of name “results” of 2 columns and 10
rows, the first column in this array is for physics module and the second column is for math. [2
marks]
2. In the “main()“ function, get from the user the values of the “results” array. Then call the function
passed(results) to and print the returned value from this function. Then ask the user to enter a
specific string variable “name” and call the function saveResults(results, name). [2 marks]
3. Pass the results array to a function passed(results), this function includes one parameter which is
the results array. This function counts the number of students who passed in the two modules, if
the two values are greater than 40. his function has an integer return type, it returns the counted
number of passed students. [3 marks]
4. Pass the results array to a function saveResults(results, name), this function includes two
parameter, the results array and a string name. This function saves values in the results array in a
text file, the name of this file is the string name. This function has no return type. [3 marks]
60
Sample Problem: to be solved by the
students for training.
Write a C++ program the get from a teacher the grades of a group of
students to do some operations as follows:
In the main() function, get from the teacher the grades of 10 students for 5
subjects. Then save these grades in a two-dimensional array grades.
Pass the array grades to a function avgStudentGrade(), this function includes a
parameter that represents the index of a students (from 0 to 9). This function will
calculate and return the average grade of the five subjects for the passed index.
Call the function avgStudentGrade() from the main() function to print the average
grade of every student.
Pass the array grades to a function avgSubjectGrade(), this function includes a
parameter that represents the index of a subject (from 0 to 4). This function will
calculate and return the average grade of the ten students for the passed index.
Call the function avgSubjectGrade() from the main() function to print the average
grade of every subect.
61
Sample MCQ for Programming
So far :
1. What is the output of the following program? 2. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. #include <string> 2. using namespace std;
3. #include <fstream> 3. int y = 2;
4. using namespace std; 4. int proc2(int d) { return (d + y++); }
5. string probFile = "example.txt"; 5. int proc1(int d) { return (d + ++y + proc2(d)); }
6. const int numOfStr = 6; 6. void main() {
7. void main() { 7. int g = 1;
8. string ArrOrder[numOfStr]; 8. cout << proc1(g) + proc2(g);
9. ofstream yofile(probFile); 9. string name[4] = { "Egyptian", "British",
10. yofile << "none,\tfirst,\tsecond,\t"; 10. "Arabian", "American" };
11. yofile << "third,\tfourth,\tfifth"; 11. cout << "-" << name[2][2];
12. ifstream myfile(probFile); 12. }
13. for (int i = 0; i < numOfStr; i++) a) 13-a
14. myfile >> ArrOrder[i];
b) 10-a
15. myfile.close();
c) 11-E
16. //Printing the output
17. for (int i = 0; i < numOfStr; i++) d) 12-a
18. cout << ArrOrder[i]; e) 14-a
19. }
a) none, first, second, third, fourth, fifth
b) none,first,second,third,fourth,fifth
c) nothing is printed
d) none,\tfirst,\tsecond,\tthird,\tfourth,\tfifth
e) Error in line 10
62
Sample MCQ for Programming
So far :
3. What is the output of the following program? 4. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. const int a = 3, b = 3; 3. const int a = 7;
4. int calc(int arr[][b]) { 4. void calc(int arr[], int g, int t) {
5. int temp = 0; 5. t = arr[g];
6. for (int i = 0; i < a; i++) 6. arr[g] = arr[g + 1];
7. for (int j = 0; j < b; j++) 7. arr[g + 1] = t;
8. temp += arr[0][j]; 8. }
9. return temp; 9. void main() {
10. } 10. int array[a] = { 3, 4, 7, 1, 9, 1, 6 };
11. void main() { 11. calc(array, 3, 2);
12. int array[a][b] = { {1, 2, 3}, {2, 3, 4} 12. calc(array, 5, 4);
}; 13. for (int i = (a - 1); i >= 0; i--)
13. cout << calc(array) << endl; 14. cout << array[i] << " ";
14. } 15. cout << endl;
16. }
a) 12
b) 18 a) 6191743
c) 15 b) 6197134
d) “Compile time Error in line 4” c) 3479161
e) “Compile time Error in line 12” d) 3471916
e) 1619743
63
Sample MCQ for Programming
So far :
5. What is the output of the following program? 6. What is the output of the following Program?
1. #include <iostream> 1. #include<iostream>
2. using namespace std; 2. using namespace std;
3. void main() { 3. void main() {
4. string s = "Faster"; 4. const int n = 3, y = 3;
5. char as[] = "Safer"; 5. int r = 0;
6. int i = 1; 6. int arr[n][y] = { {9, 4, 2}, { 1, 9, 8}, { 3, 3,
7. if (as[i] == s.at(i)){ 3} };
8. cout << as[i++] << "," << as[++i] 7. for (int i = n - 1; i >= 1; i--)
9. cout << " at " << i << endl; 8. for (int j = y - 1; j >= 0; j--) {
10. } 9. r += arr[i][j] % n;
11. else 10. }
12. cout << "nothing"; 11. cout << r;
13. } 12. }
a) f,e at 3
b) nothing a) 8
c) s,t at 2 b) 3
d) “Compile time error in line 7”, can-not compare a c) Error in line 6, array size miss-matching
string to an array. d) [Nothing is Printed]
e) f,e at 2 e) Run time error
64
Sample MCQ for Programming
So far :
7. What is the output of the following program? 8. What is the output of the following Program?
1. #include<iostream> 1. #include<iostream>
2. using namespace std; 2. using namespace std;
3. int rec(int arr[][4], int s1) { 3. void main() {
4. if (s1 == 0) 4. int arr[] = { 2, 2, 1 };
5. return arr[s1][s1 % 3] + 2; 5. string name = "alye";
6. else 6. cout << sizeof(arr) + sizeof(name.at(0)) + *arr;
7. arr[s1 % 3][s1] += 3; 7. }
8. rec(arr, s1 - 1);
9. }
10. void main() {
11. int data[5][4] = { { 1, 2, 3, 4 }, a) 5
12. { 2, 3, 9, 8 },
b) 15
13. { 1, 5, 15, 10 },
14. { 7, 7, 7, 7 } };
c) 14
15. cout << rec(data, 2); d) 13
16. } e) 2
a) 5
b) 2
c) 3
d) Error in the function call in line 11
e) Error in the array definition in line 10
65
Sample MCQ for Programming
So far :
9. What is the output of the following program? 10. What is the output of the following Program?
1. #include<iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. void main(){ 3. void main() {
4. bool r[5] = { true, false, true }; 4. int arr[4] = { 1, 2, 3, 4 };
5. for(int i = 0; i < 5; i++) 5. cout << (sizeof(int) * 2);
6. cout << r[i]; 6. cout << ", " << (sizeof(arr));
7. } 7. }
a) 16, 8
a) truefalsetrue b) 8, 16
b) 101 c) 8, 8
c) 10100 d) 16, 16
d) Truefalsetruefalsefalse e) 8, 4
e) 01011
66
Introduction to Programming
and Problem Solving
Lecture 3
Structures and Enumerations
di
us
radi
Template
am
7. };
et
e
8. circle getInfo() { Are
r
a
9. circle tempCircle;
10. cout << "Enter the diameter of a circle: ";
11. cin >> tempCircle.diameter;
12. tempCircle.radius = tempCircle.diameter / 2; The creation
13. return tempCircle; of an object:
14. } circle c;
15. void main() {
16. circle c; c
17. c = getInfo(); Struct radius=17
diameter=34
18. double const pi = 3.14; object Area=867
19. c.area = pi * pow(c.radius, 2.0);
20. cout << "Radius: " << c.radius << endl;
21. cout << "Area: " << c.area << endl;
22. }
68
Program 21 : Structure
Circle
3. struct circle {
4. int radius;
circle c; c
radius=17
di
us c.radius = 17;
radi
am
diameter=34
5. int diameter; c.diameter = 34;
et
area=867
er
6. double area; Are
a c.area = 867;
7. };
17. circle c;
18. c.area = 867;
A structure is a user-defined complex datatype, that abstracts different correlated
values of different data types. The body of this structure is enclosed between curly
brackets {}, and abstracts the definition of other variables/objects. These
variables/objects are packaged together in a structure.
Lines 3 to 7 defines a structure named as circle, this structure contains three primitive
datatype double. Line 3 defines a new structure circle using the word struct that is
defined using “struct circle”. The body of the circle structure includes the definition of
three double variables radius, diameter and area.
Line 17 defines an object of the circle structure of a name c. The circle structure is a
template for creating objects like the object c. The structure circle contains only the
definition of the three member variables “radius”, “diameter”, and “area”, while the
object c contains the values of these variables.
Line 18 uses The dot operator (.) allows the access structure members in a program. This line
assigns a new value “867” to the member variable “area” in the object c. 69
Program 21 : Structure
17. circle c;
18. c = getInfo();
19. circle getInfo() {
10. circle tempCircle;
11. cout << "Enter the diameter of a circle: ";
12. cin >> tempCircle.diameter;
13. tempCircle.radius = tempCircle.diameter / 2.0;
14. return tempCircle;
15. }
Line 17 defines an object c of datatype circle.
Line 18 calls a function called “getInfo” that returns an object of datatype circle, the
returned object from this function is assigned to the object c.
The function “getInfo” is defined in line 9. This function has no parameters and returns an
object of type circle structure.
Inside the body of function “getInfo” includes a definition of object tempCircle of datatype
circle in line 10. Line 12 get the value of the member variable tempCircle.diameter from
the user.
Line 13 uses the value of member variable diameter in the object tempCircle to calculate
the value radius in the same object.
Finally, the structure object tempCircle that is created in the function “getInfo” is
returned in line 14. This tempCircle object includes the value of diameter entered by the
user, and the value of radius calculated within this function, the variable area is not filled 70
Program 22 : Structure
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. struct InventoryItem {
5. int partNum;
6. int onHand;
7. double price;
8. };
9. void getItem(InventoryItem& p) {
10. cout << "Enter the part number: "; cin >> p.partNum;
11. cout << "Enter the quantity on hand: "; cin >> p.onHand;
12. cout << "Enter the unit price: "; cin >> p.price;
13. }
14. void showItem(InventoryItem p) {
15. cout << "Part Number: " << p.partNum << endl;
16. cout << "Units On Hand: " << p.onHand << endl;
17. cout << "Price: $" << p.price << endl;
18. }
19. void main() {
20. InventoryItem part;
21. getItem(part);
22. cout << "--------------------------------\n";
23. showItem(part);
24. } 71
Program 22 : Structure
4. struct InventoryItem {int partNum; int onHand; double price;};
20. InventoryItem part;
21. getItem(part);
22. void getItem(InventoryItem& p) {
23. cout << "Enter the part number: "; cin >> p.partNum;
24. cout << "Enter the quantity on hand: "; cin >> p.onHand;
25. cout << "Enter the unit price: "; cin >> p.price;
26. }
Line 4 defines a user-defined complex datatype, this datatype is the structure
InventoryItem. This structure contains 2 integers (partNum and onHand) and one double
variable (price).
Line 20 in the main function, defines an object part of datatype InventoryItem. Then line
21 calls a function “getItem()” and passes the object “part” to this function.
The function “getItem()” is defined in line 9. This function is defined to receive one
parameter which is the object “p” of type “InventoryItem”. The object “p” is passed to
function “getItem()” by reference, such that the object “part” in the “main()” function is
changed if the object “p” in the “getItem()” function is changed.
Lines 10, 11, and 12 in function “getItem()” get three values from the user, and set these
values to the three member variables (partNum, onHand and price) of the object “p”.
Since the object “part” is passed by reference to the function “getItem()”, then the change
to object “p” is already reflected to the object “part” in the “main()” function. In other
words, Both “part” and “p” are refereeing to the same object. 72
Program 22 : Structure
4. struct InventoryItem {int partNum; int onHand; double price;};
20. InventoryItem part;
23. showItem(part);
24. void showItem(InventoryItem p) {
25. cout << "Part Number: " << p.partNum << endl;
26. cout << "Units On Hand: " << p.onHand << endl;
27. cout << "Price: $" << p.price << endl;
28. }
Line 4 defines a user-defined complex datatype, this datatype is the structure
InventoryItem. Line 20 in the main function, defines an object part of datatype
InventoryItem. Then line 21 calls a function “showItem()” and passes the object “part” to
this function by value. The function “showItem()” function has a new copy of object “part”
known as the new object “p”. Any change in the object “p” will not affect the original copy
which is the object “part” in the “main()” function.
Lines 10, 11, and 12 in function “showItem()” prints the three values of the member variables
(partNum, onHand and price) of the object “p” to the user.
1. #include <iostream>
2. #include <fstream>
3. #include <string>
4. using namespace std;
5. struct Employee {
6. string name;
7. int ID;
8. double salary;
9. };
10. void main() {
11. const int fact1Size = 5;
12. Employee factory1[fact1Size];
13. string empName;
14. for (int i = 0; i < fact1Size; i++) {
15. cout << "Enter name of emplyee: ";
16. getline(cin, empName);
17. factory1[i] = { empName, i, 1000 };
18. }
19. ofstream fileOfEmps;
20. fileOfEmps.open("Employees.txt");
21. for (int i = -1; i < fact1Size; i++) {
22. if (i == -1) {
23. fileOfEmps << "ID\tName\t\tSalary\n";
24. continue;
25. }
26. fileOfEmps << factory1[i].ID << "\t" << factory1[i].name;
27. fileOfEmps << "\t\t" << factory1[i].salary << "\n";
28. } fileOfEmps.close();
29. } 74
factory1
Program 23 : Structure name
ID
salary
name
ID
salary
name
ID
salary
name
ID
salary
name
ID
salary
Line 17 is a block assignment, that assigns all the values within the structure together in a
single statements.
Instead of assigning each element in the structure Employee separately, the block assignment
considers the order of the elements in structure Employee and assign a value to the
corresponding variable/object in this structure.
So in the same order, empName is assigned to the object name, i is assigned to ID, and 1000
is assigned to salary.
Lne 17 can be replaced by the following 3 lines, both have the same meaning:
17. factory1[i].name = empName;
18. factory1[i].ID = i;
19. factory1[i].salary = 1000;
76
factory1
Program 23 : Structure name
ID
salary
name
ID
salary
name
ID
salary
name
ID
salary
name
ID
salary
77
Program 24 : Structure
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. const int numOfStudent = 6;
5. struct student {string studentName; int studentId; float studentGrade;};
6. void sortStudents(student students[]) {
7. for (int i = 0; i < numOfStudent - 1; i++) {
8. for (int j = i + 1; j < numOfStudent; j++) {
9. if (students[i].studentGrade < students[j].studentGrade) {
10. student temp = students[i];
11. students[i] = students[j];
12. students[j] = temp;
13. }
14. }
15. }
16. }
17. void main() {
18. const int numOfStudent = 6;
19. student students[]= { {"Ahmed Mahfoz", 211231, 45},
20. {"Samir AbdelLatif", 223412, 67},
21. {"Marwa Solimn", 267644, 55},
22. {"Eid Morgan", 255543, 78},
23. {"Sara Amin", 265633, 62},
24. {"Mostafa Negm", 265633, 62} };
25. sortStudents(students);
26. cout << "Students ordered from best to lowest grade:\n";
27. for (int i = 0; i < numOfStudent; i++)
28. cout << students[i].studentName << endl;
29. } 78
Program 24 : Structure
25. sortStudents(students);
26. void sortStudents(student students[]) {
27. for (int i = 0; i < numOfStudent - 1; i++) {
28. for (int j = i + 1; j < numOfStudent; j++) {
29. if (students[i].studentGrade < students[j].studentGrade) {
30. student temp = students[i];
31. students[i] = students[j];
32. students[j] = temp;
33. }
34. }
35. }
36. }
The array students is passed to the sortStudents() function in line 25 in the main()
function. The sortStudents() function is defined in line 6 of parameter array of student
structures.
The condition in line 9 tests if the grade of a student students[i] is less than the grade of a
student students[j], then these two students are swapped.
Note that the object students[i] is before the object students[j] in the array
students[].
Note that the array students is passed by reference, which means that the change in the
order of the array in the sortStudents() function is reflected to the array students in in
the main() function. The & operator is not used because passing array is by reference by
79
default.
Sample MCQ for Programming
So far :
1. What is the output of the following program? 10. What is the output of the following Program?
1. #include<iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. struct dataStruct { 3. struct data{
4. int i; 4. int x; int y;
5. }; 5. };
6. double func(dataStruct d) { 6. int funct(data n, int i){
7. d.i++; 7. if(i == 1) return (n.x+n.y)-2*i;
8. return d.i; 8. else {
9. } 9. n.x = n.x+n.y+i*3;
10. void main() { 10. return funct(n, i-1);
11. int f = 3; 11. }
12. dataStruct d; 12. }
13. d.i = f; 13. int main(){
14. cout << func(d); 14. data d; d.x=3; d.y=7;
15. } 15. cout<<funct(d, 4);
16. }
a) 2
b) 3
c) 4 a) 56 [3,7]
d) 5 b) 78 [78,7]
e) 6 c) 50 [3,7]
d) 62 [62,7]
e) 52 [78,7]
80
Sample MCQ for Programming
So far :
8. What is the output of the following Program? 6. What is the output of the following Program?
1. #include <iostream> 1. #include<iostream>
2. using namespace std; 2. #include<string>
3. const int d = 3; 3. using namespace std;
4. struct Int{ int val = 0; }; 4. struct person { std::string name = "BUE"; int id =
5. int getRes(Int arr[][d], int d){ 3; };
6. int r = 0; 5. void main() {
7. for (int i = 0; i < d; i++) 6. person b1; b1.id = 2; b1.name = "cairo";
8. for (int j = 0; j < d; j++) 7. person b2;
9. r += arr[i][j].val; 8. cout << b1.id + b2.id;
10. return r%d; 9. }
11. }
12. int I(int i){Int ob;
13. if(i>=0) ob.val = i; return ob; } a) 2
14. void main13(){
b) 3
15. Int array[3][d] = { { I(1), I(2), I(3) },
c) 4
16. { I(-4), I(-3), I(-1) },
17. { I(4), I(5), I(2) } }; d) 5
18. cout << getRes(array, d); e) 1
19. }
a) Compile Time Error
b) 2
c) Run Time Error
d) 0
e) 1
81
Introduction to Programming
and Problem Solving
Lecture 4
Classes
di
us
7. double getArea(){ radi
am
et
8. double const pi = 3.14;
e
get
r
9. double area = pi * pow(radius, 2.0); Are
a
10. return area;
11. };
12. };
13. circle getInfo() { The creation
14. circle tempCircle; of an object:
15. cout << "Enter the diameter of a circle: ";
16. cin >> tempCircle.diameter;
circle c;
17. tempCircle.radius = tempCircle.diameter/2;
18. return tempCircle;
19. } class c
20. void main() { object radius=17
21. circle c; diameter=34
22. c = getInfo();
23. cout << "Radius: " << c.radius << endl;
24. cout << "Area: " << c.getArea() << endl;
25. } 83
Program 25 : Class
Circle
4. class circle { circle c; c
di
us c.radius = 17;
5. public: radi radius=17
am
c.diameter = 34; diameter=34
et
6. int radius;
e
r
7. int diameter; get
Are
a
8. double getArea(){
9. double const pi = 3.14;
10. double area = pi * pow(radius, 2.0);
11. return area;
12. };
13. };
22. circle c;
24. cout << "Radius: " << c.radius << endl;
25. cout << "Area: " << c.getArea() << endl;
A class is a user-defined complex datatype, that abstracts different correlated
variables of different data types, and abstracts also different functions that operates
on the class data. The body of this class is enclosed between curly brackets {}. The
defined variables/objects and functions within a class are called members. The
accessibility of the variables/objects and functions within a class is specified, the
accesses level a class member can be either public or private.
In a simple way, a class is structure that includes (1)functions and (2)access specifier.
The definition in line 4 uses the term class in creating a new user-defined a new complex
data type called “circle”. The body of the class circle includes the definition of two int
variables radius and diameter and one function getArea(). 84
Program 25 : Class
Circle
4. class circle { circle c; c
di
us c.radius = 17;
5. public: radi radius=17
am
c.diameter = 34; diameter=34
et
6. int radius;
er
7. int diameter; get
Are
a
8. double getArea(){
9. double const pi = 3.14;
10. double area = pi * pow(radius, 2.0);
11. return area;
12. };
13. };
22. circle c;
24. cout << "Radius: " << c.radius << endl;
25. cout << "Area: " << c.getArea() << endl;
A member variable is a variable defined inside the body of a class. The variables radius and
diameter are two member variables of class circle.
A member function is a function defined inside the body of a class. The function getArea()is
member function of class circle.
Line 22 defines and object c of datatype class circle. The member variables and functions
of an object can be access dot “.” operator like “c.radius” and “c.getArea()”. Line 24
prints the value of (inside) the variable “radius” while line 25 prints the returned value from
the function “getArea()”.
24.cout << "Radius: " << c.radius << endl;
25.cout << "Area: " << c.getArea() << endl; 85
Program 25 : Class
4. class circle {
5. public: If line 5 is deleted
6. int radius;
7. int diameter;
8. double getArea(){
9. double const pi = 3.14;
10. double area = pi * pow(radius, 2.0);
11. return area;
12. };
13. };
22. circle c;
24. cout << "Radius: " << c.radius << endl;
25. cout << "Area: " << c.getArea() << endl;
Access Specifier is a way to control the access of class members. Line 5 specifies (public:)
that all members defined after this line are said to be public. The member variable radius is
said to be public, also variable diameter and function getArea().
Line 22 constructs an object c of datatype class circle.
Line 24 is accessing a member variable radius in object c using “c.radius”. The variable
radius is accessed in the main function and outside the body of the class circle, this
member can be accessed outside the body of its class only if this variable is defined as public.
If line 5 is deleted, the member variables and functions can not be accessed in line 24 and
25, this is because these members are not public. If Access specifiers are omitted, all
members will have defaulted to being private. C++ shows a compile time error if line 5 is 86
Program 26 : Class Access Specifier
1. #include <iostream>
2. using namespace std;
3. class Rectangle {
4. private:
5. int width;
6. int length;
Rectangle
7. public:
h
8. void set(int w, int l) { widt
Class
le
9. width = w;
n
Rectangle
gt
10. length = l; get
h
Are
a(
11. } )
12. int getArea() {
Set()
13. return width * length;
14. }
15. };
16. void main() {
17. Rectangle rect;
Object
18. int wid, len; rect rect
width=10
19. cout << "Enter Width: "; cin >> wid; length=5
20. cout << "Enter Length: "; cin >> len;
21. rect.set(wid, len);
22. cout << "Area of the rectangle = ";
23. cout << rect.getArea() << "\n";
24. }
87
Program 26 : Class Access Specifier
3. class Rectangle {
4. private:
5. int width; Rectangle
6. int length;
7. public: h
widt
8. void set(int w, int l) {
le
9. width = w;
n
gt
get
h
10. length = l; Are
a()
11. }
12. int getArea() { Set()
13. return width * length;
14. }
15. };
A class contains access specifiers like private and public specifier. When a variable is
set to be private, this variable can not be accessed directly from outside the body of
the class. If no access specifier is specified in the class, then all members of this class is
by defaulted is private. Any member defined below the private key word is considered
as private and any member defined below the public key word is defined as public.
Line 4 specifies that members variables below this line are going to be private, so the
member variables width and length are said to be private. Line 7 specifies that members
below this line are going to be public, so the member functions set(int, int) and
getArea() are said to be public. 88
Program 26 : Class Access Specifier
3. class Rectangle {
4. private:
5. int width; Rectangle
6. int length;
7. public: h
widt
8. void set(int w, int l) {
le
9. width = w;
n
gt
get
h
10. length = l; Are
a()
11. }
12. int getArea() { Set()
13. return width * length;
14. }
15. };
Private member variables in a specific class are accessible only from within member
functions in the same class. In another way, Private member variables are only accessed
from within the body of the class between the brackets {}.
The functions set(int, int) and getArea() are member functions in the class, which
means that these functions are inside the body of the class. Inside the body of the member
functions set(int, int) and getArea(), private member variables width and length can
be accessed successfully without any errors.
Lines 9 and 10 sets the values of the two private member variables width and length. These
two lines are in the body of member function set(int, int) of the same class.
Line 13 returns the product of the two private member variables width and length. This line
lies in the body of the member function getArea() of the same function. 89
Program 26 : Class Access
Specifier
17. Rectangle rect;
18. int wid, len;
19. cout << "Enter Width: "; cin >> wid;
20. cout << "Enter Length: "; cin >> len;
21. rect.set(wid, len); rect
width=10
22. cout << "Area of the rectangele = "; length=5
23. cout << rect.getArea() << "\n";
le
7. public:
Rectangle
gtn
8. void set(int, int); get
h
Are
a(
9. double getArea(); )
10. }; Set()
11. void Rectangle::set(int w, int l) {
12. width = w; length = l;
13. }
14. double Rectangle::getArea() {
15. return width * length;
16. }
17. void main() {
18. Rectangle rect;
Object rect
width=10
19. int wid, len; rect length=5
20. cout << "Enter Width: "; cin >> wid;
21. cout << "Enter Length: "; cin >> len;
22. rect.set(wid, len);
23. cout << "Area of the rectangele = ";
24. cout << rect.getArea() << "\n";
25. }
91
Program 27 : Class inline functions
8. void set(int, int);
9. double getArea();
11. void Rectangle::set(int w, int l) {
12. width = w; length = l; rect
width=10
13. } length=5
14. double Rectangle::getArea() {
15. return width * length;
16. }
Class member functions can be defined either inside or outside the class body between {}. If
the function implementation is included inside the class body, the member function is named
as inline member function.
When a function body is longer, a prototype for the function should appear in the class body,
instead of the function body itself. The function body definition is then placed outside the
class declaration, either following it or in a separate file. In this case the function definition
contain the class name Rectangle and a double colon (::) between the function return type
void and function name set.
void Rectangle::set(int w, int l){ .. }
Inside the class declaration the functions would be replaced by the following function
prototypes:
void set(int, int);
double getArea();
92
Program 28 : Class Example
1. #include <iostream>
2. using namespace std;
3. class dataScore {
4. private: dataScore
5. int score; score
6. public: class add
S
set core(
7. void addScore(int val) { score += val; } Template get S cor )
Sco e()
8. void setScore(int val) { score = val; } re(
)
9. int getScore() { return score; }
10. };
93
Program 29 : Class constructor
1. #include <iostream>
2. using namespace std;
3. class Circle {
4. private:
5. double radius;
6. public:
Circle
7. Circle() {
us
8. radius = 1; radi
9. } Class
10. void setRadius(double r) { Circle get
Are
a(
11. if (r >= 0) )
12. radius = r;
Set()
13. }
14. double getArea() {
15. return 3.14 * pow(radius, 2);
16. }
17. };
18. void main() { circle1
19. Circle circle1; Object circle1 radius=1
20. Circle circle2; Object circle2
21. circle2.setRadius(2);
22. cout << "The area of circle1 is " << circle1.getArea() << endl;
23. cout << "The area of circle2 is " << circle2.getArea() << endl; circle2
radius=2
24. }
94
Program 29 : Class constructor
3. class Circle {
4. private:
5. double radius;
6. public:
7. Circle() { circle1 circle2
8. radius = 1; radius=1 radius=1
9. }
17. Circle circle1;
18. Circle circle2;
A constructor is a special public member function that runs when an object of this class
is defined. A constructor looks like a regular function except that its name must be the
same as the name of the class and it has no return datatype. This is how the compiler
knows that a particular member function is a constructor. Most often programmers use
a constructor to initialize an object’s member variables.
Lines 7, 8 and 9 defines a public member function “Circle()” in class Circle. This function
has the same name as the class, also this function has no return datatype. This member
function is known as a class constructor.
Line 17 defines an objects circle1 of datatype class Circle. This line constructs an object
in the memory of name circle1. When this object is constructor, C++ implicitly calls the
constructor “Circle()” of the class Circle. The constructor “Circle()” initializes the
private member variable radius to 1.
Also Line 18 defines object circle2 of the class Circle and, C++ calls constructor
“Circle()” of this object to initialize radius to 1. 95
Program 29 : Class constructor
10. void setRadius(double r) {
11. if (r >= 0)
12. radius = r;
13. }
14. double getArea() { circle1 circle2
15. return 3.14 * pow(radius, 2); radius=1 radius=2
16. }
Line 19 calls function “setRadius()” of object circle2. This function call passes the value 2
to the function setRadius(double r) of parameter r. Function “setRadius()” is a public
member function in class Circle, this function sets the private member variable radius to
the passed value r as shown in line 12.
Line 20 and 21 call function “getArea()” of objects circle1 and circle2 respectively. This
function call returns a double value (the area), the calculation of the returned value is based
on the private member variable radius. The returned value of this function is printed.
Both member functions “setRadius()” and “getArea()” in class Circle has access on the
private member variables in class Circle.
96
Program 29 : Class constructor
10. void setRadius(double r) {
11. if (r >= 0)
12. radius = r;
13. }
14. double getArea() { circle1 circle2
15. return 3.14 * pow(radius, 2); radius=1 radius=2
16. }
Function “setRadius()” is used to set the value of the private member variable radius. The
c++ compiler prevents the direct access to variable radius, it allows the access to private
variable indirectly through the member function “setRadius()”.
The function “setRadius(double r)” checks first if the passed value is greater than zero. It
not correct to set a negative value to the radius’s length. If the condition on the passed value
is true, then the function sets the member variable radius by the passed value r.
Access specifier allows the design of a professional programs, it controls the access to the
member variables and functions. Any function, as in the main function, is not allowed to
access a private member except through a public member function. This prevents the
setting of a wrong value according to the problem, like preventing the setting of a
negative value to the member variable radius in this problem. 97
Program 30 : Class constructor
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. class module {
5. private:
6. string moduleName; string moduleLeader; int numOfStudents;
7. public:
8. module() { numOfStudents = 0; }
9. void setModuleDate(string name, string leader) {moduleName = name;moduleLeader = leader;}
10. void setNumOfStudents(int num) { numOfStudents = num; }
11. string getReport() { string s= moduleName+"/|"+moduleLeader+"/|"+to_string(numOfStudents);
12. return s;
13. }
14. };
15. void main() {
16. module year1[5];
17. string s1, s2;
18. int num;
19. for (int i = 0; i < 5; i++) {
20. cout << "Enter Module Name : "; cin >> s1;
21. cout << "Enter Module Leader : "; cin >> s2;
22. cout << "Enter Number of students : "; cin >> num;
23. year1[i].setModuleDate(s1, s2);
24. if (num > 10) year1[i].setNumOfStudents(num);
25. }
26. for (int i = 0; i < 5; i++) { cout << year1[i].getReport()<<endl; }
27. }
Program 30 : Class constructor
16. module year1[5];
17. string s1, s2;
18. int num;
19. for (int i = 0; i < 5; i++) {
20. cout << "Enter Module Name : "; cin >> s1;
21. cout << "Enter Module Leader : "; cin >> s2;
22. cout << "Enter Number of students : "; cin >> num;
23. year1[i].setModuleDate(s1, s2);
24. if (num > 10) year1[i].setNumOfStudents(num);
25. }
26. for (int i = 0; i < 5; i++) { cout << year1[i].getReport()<<endl; }
Line 16 defines an array year1[] of 5 objects of a user-defined datatype class module. The
C++ calls the constructor for each object in this array.
Line 23 sets the values of two member variables in each object in the array indirectly. The
function call “year1[i].setModuleDate(s1, s2)” calls the function “setModuleDate()” in
each object .
99
Program 31 : Class destructor
1. #include <iostream>
2. using namespace std;
3. class Circle {
4. private:
5. double radius;
6. public:
7. Circle() {cout << "Class is now constructed"; }
8. ~Circle() {cout << "Class is now destructed"; }
9. };
10. void consdestClass() {
11. Circle circle1;
12. cout << "Program is executing" << endl;
13. }
14. void main() {
15. cout << "Program is started " << endl;
16. consdestClass();
17. cout << "Program is ended" << endl;
18. }
100
Program 31 : Class destructor
10. void consdestClass() {
11. Circle circle1;
12. cout << "Program is executing" << endl;
13. }
14. void main() {
15. cout << "Program is started " << endl;
16. consdestClass();
17. cout << "Program is ended" << endl;
18. }
The first line (line 19) in the main function prints the text “Program is started”. The
second step in the main function (line 20) calls the function consdestClass(),
The first line in function consdestClass() (line 15) defines an object circle1, the
datatype of this object is class Circle. C++ automatically calls the “constructor” of this class
after creating the object circle1 in the memory.
Line second line in function consdestClass() (line 16) prints the text “Program is
executing”.
At the function consdestClass() ends in line 17, the function circle1 is not going to be
used anymore. The object circle1 can not be used outside function consdestClass()
because it is defined locally in this function. C++ removes (destructs) this object from the
computer memory after the end of function consdestClass() to free space for new objects.
At this point, C++ automatically calls what is called the “destructor” function of the class.
After the end of function consdestClass() and returns back to line 20, line 21 is executed
by printing “Program is ended”. 101
Program 31 : Class destructor
3. class Circle {
4. private:
5. double radius;
6. public:
7. Circle() {cout << "Class is now constructed"; }
8. ~Circle() {cout << "Class is now destructed"; }
9. };
10. void consdestClass() {
11. Circle circle1;
12. cout << "Program is executing" << endl;
13. }
Destructors are public member functions with the same name as the class, preceded by
a tilde character (~). Destructors are automatically called when an object is destroyed.
In the same way that constructors can be used to set things up when an object is
created, destructors are used to perform shutdown procedures when the object goes out
of existence.
Function Circle() is a constructor for class Circle, while function ~Circle() is a
destructor for the same class.
Line 13 defines an object circle1, the datatype of this object is class Circle. C++
automatically calls the constructor of this class after creating the object circle1. This
function prints “Class is now constructed”.
Line 17 ends the function consdestClass() where object circle1 is defined locally. This
object is destroyed after the end of this function because it can not used outside it. C++
automatically calls the destructor of this class before deleting the object circle1 from the
102
computer’s memory. This function prints “Class is now destructed”.
Program 32 : Class parametrized
constructor
1. #include <iostream>
2. using namespace std;
3. class Room {
4. private:
5. double length, breadth, height;
6. public:
7. Room(double len, double brth, double hgt) {
8. length = len;
9. breadth = brth;
10. height = hgt;
11. }
12. double calculateArea() { return length * breadth; }
13. double calculateVolume() { return length * breadth * height;}
14. };
15. void main() {
16. //Room room1; //Not allowed
17. Room room2(42.5, 30.8, 19.2);
18. cout << "Area of Room = " << room2.calculateArea() << endl;
19. cout << "Volume of Room = " << room2.calculateVolume() << endl;
20. }
Program 32 : Class parametrized
constructor
3. class Room {
4. private:
5. double length, breadth, height;
6. public:
7. Room(double len, double brth, double hgt) {
8. length = len;
9. breadth = brth;
10. height = hgt;
11. }
16. //Room room1; //Not allowed
17. Room room2(42.5, 30.8, 19.2);
Line 3 defined a class Room of 3 private member variables length, breadth and height
and 3 public functions. One of the public function in this class Room is a parametrized
constructor. Line 7 defines a parametrized constructor Room(double, double, double) of
3 parameters. The objective of this constructor is to set the values of private variables by the
passed parameters.
Line 17 defines an object room2 of the user-defined datatype class Room. The object
definition includes 3 double values between brackets (), C++ internally search for the
corresponding parameterized constructor that includes 3 parameters. This definition passes 3
double values to the three parameters {len, brth, hgt} of the parameterized constructor.
Lines 8, 9 and 10 in the body of the parameterized constructor sets the values of the private
members by the passed value to the constructor parameters .
104
Program 32 : Class parametrized
constructor
3. class Room {
4. private:
5. double length, breadth, height;
6. public:
7. Room(double len, double brth, double hgt) {
8. length = len;
9. breadth = brth;
10. height = hgt;
11. }
16. //Room room1; //Not allowed
17. Room room2(42.5, 30.8, 19.2);
A constructor of no parameter is called a default constructor, while a constructor of one
or more parameters is called a parameterized constructor. A class may contain more
than one constructor, each of different number of parameters.
C++ allows the presence of a default constructor, and it allows also the presence of
parameterized constructor. The need of the parameterized constructors is to initialize
the member variables of the class. Any definition a class object of no parameters is not
allowed by C++ compiler if the class does not contain a default constructor and contains
only parameterized constructors.
Line 16 is commented // using because it shows a compile time error. Class Room contains a
parametrized constructor and does not contain a default constructor.
105
Sample Problem: to be solved by the
students for training.
Write a C++ program to get from the user the age of 10 students. Then order the list of
these students in an ascending order by age and print the number of passed students:
1. Define a class named as “student”, this class contains a private boolean variables “pass” and a
private integer variable “age” (the value of this variable refers to age of the student in years
only). [3 marks]
2. In the “main()“ function, get from the user 10 students and store these events in an array called
“students“. Call the function Orderstudents(students) to sort the students according to their age
and print the returned value from this function. Then ask the user to enter a specific value to an
integer variable “age” and call the function countStudents(students, age) and print the output. [2
marks]
3. Pass the students array to a function Orderstudents(students), this function includes one
parameter which is the array of students. This function sorts the array according to the age of the
students. This function has no return type. [3 marks]
4. Pass the array students to a function countStudents(students, age), this function includes two
parameter which is the array of students and an age. This function has an integer return type, it
returns the number of students who passed (pass value is true), and their age is greater than age.
[2 marks]
106
Sample Problem: to be solved by the
students for training.
Write a class named Car that has the following member variables: model,
manufacturer, year. The class should have the following constructors:
Default constructor: A default constructor sets the model and manufacturer to
“”, and year to 0.
Parametrized Constructor: Accepts the model, manufacturer, and year as
arguments.
setModel: Function to assign a value to the model variable.
setManufacturer: Function to assign a value to the manufacturer variable.
setYear: Function to assign a value to the year variable.
getModel: An accessor function for the model variable.
getManufacturer: An accessor function for the manufacturer variable.
getYear: An accessor function for the year variable.
expectedPrice: Prints a message of the price expected value which is calculated
as:
if ((model= “Marcedes”)and year>2012) Then print “more than 2 millions”
if ((model= “BMW”)and year>2010)) Then print “about 1.5 million”
if ((model= “Ford”)and year>2010)) Then print “about a million”
otherwise, print “you are in the safe side, you can pay less than a million”
Then write a program that demonstrates the Car class by asking the user for the
model, manufacturer, year of a car. Then it reports expected price of this car. 107
Sample MCQ for Programming
So far :
3. What is the output of the following program? 4. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. #include <string> 2. using namespace std;
3. using namespace std; 3. class Square{
4. class Circle { 4. private:
5. private: 5. int length = 22;
6. string s = "A"; 6. Square(int l){ set(l); }
7. public: 7. public:
8. Circle(string s1) { s = s1; cout << s << 8. void set(int l){ length = l; }
"a"; } 9. int get(){ return length; }
9. Circle() { cout << s << "b"; } 10. };
10. ~Circle() { cout << s << "c"; } 11. void main(){
11. }; 12. Square s(44);
12. void consdestClass() { 13. cout << s.get();
13. Circle circle1("B"); 14. }
14. }
15. void main() {
16. Circle circle2("C"); a) “Run time error”
17. consdestClass();
b) “Compile time error in line 5”
18. }
c) 44
a) AaAcBaBc
d) 22
b) AaAcCaCc
e) “Compile time error in line 12”
c) CaCcBaBc
d) CaBaBcCc
e) BaBcCaCc
108
Sample MCQ for Programming
So far :
5. What is the output of the following program? 6. What is the output of the following Program?
1. #include<iostream> 1. #include <iostream>
2. class circle { 2. class circle {
3. private: 3. private:
4. double radius; 4. const int pi = 3;
5. public: 5. int radius = 1;
6. void store(double r) { radius = r; } 6. double area;
7. void display() { 7. void setRadius(int r) { radius = r; }
8. std::cout << "r = " << radius; 8. public:
9. } 9. circle() { }
10. }; 10. circle(int r) { setRadius(r); }
11. void main() { 11. int getArea() { area = radius * radius * pi;
12. circle c; // an object of circle return area; };
class 12. };
13. c.store(5.0); 13. void main() {
14. c.display(); 14. circle s2(2);
15. } 15. circle s1;
16. std::cout << s1.getArea() + s2.getArea();
17. }
109
Sample MCQ for Programming
So far :
7. What is the output of the following program? 8. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. class dataScore { 3. class arr4Class {
4. private: 4. private:
5. int score; 5. int v[4];
6. public: 6. public:
7. dataScore(int val) { score = val; } 7. arr4Class(int v0, int v1, int v2, int v3) {
8. void addScore(int val) { score += 8. v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3;
val; } 9. }
9. int getScore() { return score; } 10. int getVSum() { return (v[0] + v[1] + v[2] + v[3]);
10. }; }
11. void main() { 11. };
12. dataScore ds; 12. void main() {
13. for (int i = 1; i <= 10; i++) { 13. arr4Class a0(0, 0, 0, 0), a1(1, 2, 3, 4);
14. ds.addScore(1); 14. cout << a0.getVSum() << a1.getVSum();
15. } 15. }
16. cout << ds.getScore(); a) 0
17. }
b) 010
a) Run time error c) 4
b) Compile time error d) 1
c) Logical error e) 10
d) Nothing is printed
e) 10
110
Sample MCQ for Programming
So far :
9. What is the output of the following program? 10. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. class arrClass { 3. class comp1 {
4. private: 4. int g = 1;
5. int v[2] = {0, 0}; 5. int getG() { return g; }
6. public: 6. };
7. arrClass() { v[0] = 1; } 7. struct comp2 {
8. arrClass(int v0) { v[0] = v0; } 8. int g = 1;
9. arrClass(int v0, int v1) { v[0] = v0; v[1] = 9. };
v1; } 10. void main() {
10. int getV() { return (v[0] + v[1]); 11. comp1 c1;
11. } 12. comp2 c2;
12. }; 13. cout << c1.getG()+c2.g;
13. void main() { 14. }
14. arrClass a0, a1(1), a2(2);
15. cout << a0.getV()+ a1.getV() + a2.getV();
16. }
a) 1
a) 1 b) 2
b) 3 c) 3
c) 4 d) Run time error
d) 5 e) Compile time error
e) 7
111
Sample MCQ for Programming
So far :
2. What is the output of the following Program?
1. #include <iostream>
2. using namespace std;
3. class Circle {
4. private:
5. int radius;
6. public:
7. Circle() { radius = 1; cout << "print1,"; }
8. Circle(int r) { radius = r; cout << "print2,"; }
9. ~Circle() { cout << "print3,"; }
10. void setRadius(int);
11. };
12. void Circle::setRadius(int r) {
13. if (r >= 0) radius = r; cout << "print4,";
14. }
15. void main() {
16. Circle circle1(2);
17. Circle circle2;
18. circle2.setRadius(3);
19. }
a) print2,print1,print4,print3,print3,
b) print1,print2,print3,print4
c) print2,print1,print4,print3,
d) print1,print2,print3,print4,
e) Error in line 13 in accessing private variable from outside the class 112
Introduction to Programming
and Problem Solving
Lecture 5
Pointers
RAM
Size=4
x Address of x is 00DEF8FC
25
&x = 00DEF8FC
RAM
Program 33 : Pointers
Size=4
4. int x = 25; x 25 &x
5. cout << "The address of x : " << &x << endl;
6. cout << "The size of address of x : " << sizeof(&x) << endl;
7. cout << "The size of x : " << sizeof(x) << " bytes\n";
8. cout << "The value of x : " << x << endl;
Every variable in C++ has a datatype, a name, a value, and an address. An address of a
variable is the location of the variable in the computer’s memory. The address of a
variable can be obtained by preceding the name of a variable with an ampersand sign
(&), known as address-of operator. Address refers to the location of a variable in the
memory.
The memory of computer is called “RAM” which is an abbreviation for “Random Access
Memory”. When a variable is defined in the program, the computer placed the variable
randomly in any location in the memory.
Every byte in the computer memory has an
address. Variables are composed of multiple
bytes, e.g. Integer x is saved in 4 bytes. The
address of a variable is the address of the first
byte in the variable.
The size of the address of a variable or an object
is 4 bytes. 115
Program 33 : Pointers
4. int x = 25;
5. cout << "The address of x : " << &x << endl;
6. cout << "The size of address of x : " << sizeof(&x) << endl;
7. cout << "The size of x : " << sizeof(x) << " bytes\n";
8. cout << "The value of x : " << x << endl;
By default, C++ prints addresses in hexadecimal (base 16) to save space. Hexadecimal
uses the numeric digits 0 through 9 and the letters 'a' through 'f' to represent the
numeric values 0 through 15). So, instead of representing a decimal number 15 by two
digits 1 and 5, this number can be represented in Hexadecimal by one digit only.
Line 4 defines a variable, the datatype of this variable is integer (int), the name of this
variable is x, the value of this variable is 24, and finally the address of this variable which is
(&x).
Line 5 pints the address of the variable x, that has the form (&x). The printed address has a
hexadecimal representation. The number of digits in a hexadecimal number is much less than
in a decimal number. The address (&x) is printed as 00DEF8FC. The printed address may be
changed in every time the program runs. This is because the computer placed the variable in
a random location every time.
Lines 6 prints the size of the address of the variable x, which is 4. This means that the
address of any variable or object is 4 bytes.
While line 7 prints the size of the integer variable x. Finally, line 8 prints the value of the
variable x which is 24. 116
Program 34 : Pointers
1. #include <iostream>
2. #include <string>
3. using namespace std;
4. void main() {
5. int x = 25;double y = 31; string str = "British";
6. int *px; // Variable px is a pointer to an integer.
7. px = &x; // Store the address of the variable x in px.
8. double *py; // Variable py is a pointer to a double.
9. py = &y; // Store the address of the variable y in py.
10. string *pstr; // Variable pstr is a pointer to a string.
11. py = &y; // Store the address of the variable str in pstr.
12. cout << "The size of address of int ( x ) : " << sizeof(px) << endl;
13. cout << "The size of address of double ( y ) : " << sizeof(py) << endl;
14. cout << "The size of address of string ( str ) : " << sizeof(pstr) << endl;
15. if (px == &x){
16. cout << "The addresses &x and px are equal, " << endl;
17. cout << "and each is equal to : " << px << endl;
18. }
19. *px = 100; //Access the value of x indirectly.
20. cout << "The value of x is changed to 100 : \n";
21. cout << "x = " << x << ", *px = " << *px << endl;
22. *px *= 2; //Multiply the value of x by 2.
23. cout << "The value of x is multiplied by 2 : \n";
24. cout << "x = " << x << ", *px = " << *px << endl;
25. }
Program 34 : Pointers
5. int x = 25; double y = 31; string str = "British";
6. int *px; // Variable px is a pointer to an integer.
7. px = &x; // Store the address of the variable x in px.
8. double *py; // Variable py is a pointer to a double.
9. py = &y; // Store the address of the variable y in py.
10. string *pstr; // Variable pstr is a pointer to a string.
11. pstr = &str; // Store the address of the variable str in pstr.
The pointer is a variable that holds a value, this value refers to an address in the
memory. The size of this variable in the memory is four bytes, independent on the data
type of the referred address. The size of pointers to integer, double or string is the
same, 4 bytes.
Line 12 prints the size of the pointer px to an integer x,
the printed value is 4. Line 13 prints the size of the pointer
py, which is 4 also. Line 14 prints the size of the pointer
pstr, which is 4 also.
if (px == &x){
The symbol px refers to a pointer variable that holds
the address of the integer x.
The symbol &x refers to the address of the integer x.
Then, both symbols are the same and their values is
equal, and the condition is true.
The value of px is printed as a hexadecimal number of 4
digit-pairs “0028F8D8”.
Program 34 : Pointers
19. *px = 100; //Access the value of x indirectly.
20. cout << "The value of x is changed to 100 : \n";
21. cout << "x = " << x << ", *px = " << *px << endl;
22. *px *= 2; //Multiply the value of x by 2.
23. cout << "The value of x is multiplied by 2 : \n";
24. cout << "x = " << x << ", *px = " << *px << endl;
The value of the variable can be accessed directly by the variable name {for example:
cout<<x;}. Also, the value of the variable can be also accessed indirectly through the
pointer to this variable {for example: cout<<*px;}. The symbol {*} precedes the
pointer name to refer to the value of the variable pointed to by the pointer.
Line 10 sets the value of {*px} by 100. The variable {px} is RAM
a pointer to the integer variable x, it holds the value of
the address of the integer variable x. The variable {*px}
holds the value of the integer variable x itself. Size=4
So, the statement {*px = 100;} is the same as the
px 0028F8D8
statement {x = 100;}. In other words, the value of *px is
Size=4
the same as the value of x.
(x) or (*px) 25 &x
Line 10 contains the statement {*px *= 2;} that multiplies
the value of *px by 2 and sets the result to again in *px.
This statement can be completely replaced by the It can described as follows :
statement {x *= 2;} to do the same processing. px = *(&x) = *&x = x
* 120
Program 35 : Pointers
1. #include <iostream>
2. using namespace std;
3. void main() {
4. //Define an array of integers
5. int numbers[5];
124
Sample MCQ for Programming
So far :
3. What is the output of the following program? 7. What is the output of the following program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. class circle { 3. void main() {
4. private: 4. int d[4] = { 2, 3, 4 };
5. const int pi = 3; 5. int x = 3;
6. int radius = 1; 6. int* y = &x;
7. double area; 7. cout << (*(d + 1) + *y + *(d + 3)) <<
8. void setRadius(int r) { radius = r; } endl;
9. public: 8. }
10. circle() { }
11. circle(int r) { setRadius(r); } a) “Compile time error in line 7”, the d is an array.
12. int getArea() {
b) 6
13. area = radius * radius * pi; return
area;
c) 3
14. }; d) 7
15. }; e) 9
16. void main() {
17. circle s2(2);
18. circle s1;
19. std::cout << s1.getArea() + s2.getArea();
20. }
a) Wrong output
b) Error in line 14
c) Error in line 15
d) 3
e) 15 125
Sample MCQ for Programming
So far :
5. What is the output of the following program? 6. What is the output of the following Program?
1. #include <iostream>; 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. struct d { 3. class dataClass {
4. int u; 4. private:
5. d* v; 5. float f = 1.1;
6. }; 6. public:
7. void main() { 7. float g = f + 1.3;
8. d r[2]; (*r).u = 1; (*r).v = &(r[1]); 8. };
9. ++(*r).u = 3; (*((*r).v)).u = 2; 9. void main() {
10. int z = 0; 10. dataClass* Arr;
11. for (int i = 0; i < 2; i++) 11. int size = 3;
12. z += r[i].u; 12. Arr = new dataClass[size];
13. cout << z; 13. Arr[0].g = 2;
14. } 14. cout << Arr->g + Arr[2].g;
15. }
a) 4
b) 5
c) 3 a) “Compile time error in line 7”, f is private member variable.
d) Compile time error b) “Compile time error in line 12”, size of array must be constant.
e) Run time error c) “Compile time error in line 10”, Arr->g is not a correct operator.
d) 2.0
e) 4.4
f) 1.3
126
Sample MCQ for Programming
So far :
9. What is the output of the following program? 10. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. int x1 = 2; 3. void main() {
4. int change(int x2, int& x3) { 4. int a[3] = { 2, 3, 4 };
5. return x1 + x2 + ++x3; 5. int v = 1, * r = &v, * p;
6. } 6. p = r;
7. void main() { 7. *p += sizeof(a) / sizeof(int) + *(a + 1);
8. int x4[4] = { 1, 2, 3, 0 }; 8. cout << v << '#' << *r;
9. int x5 = 2; x1 = 1; 9. }
10. int x6 = change(*x4, x5);
11. cout << x6 + x5 << endl; a) 7#3
12. }
b) 4#9
c) 2#8
a) 6
d) 5#5
b) “Compile time error in line 10”, function parameters are not
e) 7#7
correct.
c) 8
d) 3
e) 5
127
Sample MCQ for Programming
So far :
12. What is the output of the following Program?
1. #include <iostream>
2. using namespace std;
3. void main() {
4. int d[4] = { 1, 2, 3 };
5. char z = 65;
6. int* y = &d[2];
7. cout << z << "-";
8. cout << z + 1 << "-";
9. cout << *(d + 1) << "-";
10. cout << *y << "-";
11. cout << *(d + 3) << "-";
12. }
a) 65-66-1-3-Null-
b) 65-66-2-3-0-
c) A-B-2-3-0-
d) Compile time error
e) A-66-2-3-0-
128
Introduction to Programming
and Problem Solving
End of Programming,
part 2