Professional Documents
Culture Documents
Lab Manual
ENG 200
C++Programming Language
Prepared by:
1
Computer Engineering Department
Table of content:
2
Computer Engineering Department
Lab No. 1
Introduction to C++ programming Language (I)
Objectives:
1. Learning what is C++
2. Familiarization with visual studio 2013 compiler.
3. Being able to write simple C++ program.
Software Tool:
Microsoft Visual Studio 2013
Background:
C++ is a programming language used to communicate with the computer to perform
certain applications and solving problems.
The very basic structure used in every C++ Program is the following:
#include <iostream>
using namespace std;
//here is the definition area
int main()
{
// here you write your program
return 0;
}
Note: Whatever is written after the // is a comment and cannot be seen by the
compiler.
cout<< Welcome All to C++ course\n; Comment [z1]: Anything between the
quotation will be displayed as it is.
3
Computer Engineering Department
#include <iostream>
using namespace std;
int main()
{
cout<< Welcome All to C++ course \t;
cout<< Congratulation you just completed lab 1<<endl;
return 0;
}
Run the previous code using Microsoft visual Studio 2013
4
Computer Engineering Department
How to Use Microsoft Visual Studio 2013 to run the C++ code?
1. Double click on the program Microsoft visual studio2013 shown on the desk top
OR from the program list Windows Visual Studio 2013 Visual Studio 2013
5
Computer Engineering Department
3. From The Start Page tab, go to the label Start and click on New project
4. The following popup window will be opened:
6
Computer Engineering Department
5. From the list on the left click on Installed Template Visual C++ Win 32.
In the middle of the popup window a list will be displayed, click on Win32 Console
Application, in the Name field type the project name which will be Lab1 then click
As shown below:
7
Computer Engineering Department
7. Right mouse click on Source File Add New Item, and with left mouse button
click on New Item.
A new pop up window will be displayed, from the list on the left click Installed Visual
C++, and then a list in the middle of the page will appear, select
,then click
As shown in the following page:
8
Computer Engineering Department
9
Computer Engineering Department
10
Computer Engineering Department
10. To run the program and see the output: Go-to menu DEBUG Start
Without Debugging
A console window will pop displaying the output of the code as shown:
11
Computer Engineering Department
12
Computer Engineering Department
4. To add the output at the end of your code, go to the .cpp file you just wrote then
add it as a comment. To add the output as comment first type /* then paste the
copied text then type */(Note that once you type /* the editor will directly print
*/ after it, so no need to type it). You will see that the text is turned to green
which means it is comment. As shown in the next page:
13
Computer Engineering Department
14
Computer Engineering Department
Lab Homework :
In C++ we have special code to perform the arithmetic operations, these codes are:
1. Pranthesis () z=(x+y)
2. Multiplication * z=x*y x= x*y x*=y
Division / z=x/y x=x/y x/=y
Modulo(the remainder % z=x%y x=x%y x%=y
of integer division)
3. Addition + z=x+y x=x+y x+=y
Subtraction - z=x-y x=x-y x-=y
I have grouped them according to their priority. This means, number 1 has the
highest priority and number 2 has the lowest.
Example:
Confirm that:
a. a+b-c/d = 4
b. (a+b-c)/d = 0 (integer division)
c. (a+(b-c))/d = 0 (integer division)
Exercise:
1. a += b (a = )
2. a = b/d (a = ..)
3. a = b%d (a = ..)
15
Computer Engineering Department
Lab No. 1
Introduction to C++ programming Language (II)
Objectives:
1. Familiarization with visual C++ compiler.
2. Learning how to use simple cin and cout and assign statements.
3. Learning how to use operators, precedence, and parenthesis.
4. Being able to write and compile C++ program with cin, cout, and assign
statements.
5. Learning how to fix basic syntax errors.
Software Tool:
Visual Studio 2013
Exercise1: Write a C++ program that will read 2 integer numbers from the user
(num1, num2) and find their summation and store it in variable (sum), then find their
average and store it in variable (ave). Use the following arithmetic expression to
perform the addition operation:
ave= (num1+num2)/2
Answer:
In order to solve the problem first we need to define the variables num1, num2, and
sum as integers.
1. In C++ the variable name must be alphanumeric, which means it must start with
letter and it may include numbers and alphabet letters ONLY, but no other
character like (@,#,$,%,^,&,*, ,-,+,space, etc).
2. C++ is a case sensitive language it means; the capital letter is different than small
letter (example: Num is not the same as num) so always make sure to be
consistence with the case is your variable names.
16
Computer Engineering Department
int num1, num2, sum, ave; Comment [z2]: Type of the variable
Comment [z3]: Variable name can be
To read the variables as an input from the user we write one of the following input anything that is alphanumeric.
#include <iostream>
using namespace std;
int main()
{
..
..
..
return 0;
}
Exercise 2: Write a C++ program that reads a Fahrenheit temperature and outputs the
equivalent centigrade temperature. The equation for converting Fahrenheit temperature
to Celsius is
9
tf = tc + 32
5
17
Computer Engineering Department
Syntax errors:
When a C++ statement is written in correctly the compiler will detect that and give you
some error messages, and it is known as syntax error.
Exercise 3: Ask the students to modify exercise 2 by adding 10 syntax errors based on
the handout given in the following pages, and show them how to read the error and how
to use the handout to correct it.
18
Computer Engineering Department
Students Handout
Compilation Errors and Warnings
Compilation Error
It refers to a state when a compiler fails to compile the code, due to syntax errors in the
code.
Compilation Warning
It refers to a state when the code is valid and compiles successfully, but may not be
what the programmer intended.
When you compile a code with compilation errors or warnings you will get a message
depending on the type of error or warning:
Errors Justification
Spelling mistake
1 invalid preprocessor command 'inlude'
'include'
Ex: #inlude<iostream>
Spelling mistake
2 Cannot open include file: 'iosteam': 'iostream'
No such file or directory
19
Computer Engineering Department
Ex: #include<iosteam>
Using a variable
undeclared identifier:
without declaring
Using namespace
'cout' , 'cin' or 'endl'
std; is missing
3 Spelling mistake
'return0'
'return 0'
Spelling mistake
'retrn'
'return 0'
Spelling mistake
'cot'
'cout'
20
Computer Engineering Department
Ex: cout<<"hello">>endl;
The is an error in
int Main();
missing function header
10 It should be
Ex: int Main();
int main(){
21
Computer Engineering Department
Warning Justification
int x;
cout<<x<<endl; Cin>>x; or x = 2;
cin >> x;
cin >>x>>y;
22
Computer Engineering Department
Lab No. 2
Control Structures (I)
Objectives:
1. Understanding the if statements: simple if, if else, and if else if else.
2. Understanding the while loop statement.
3. Learning how to write simple if, if-else, and nested if-else in a C++ Program.
4. Learning how to write the while loop statement in a C++ program.
Software Tool:
Visual Studio 2013
Background
Exercise1: Write a C++ language program to determine whether a given integer (num)
is even or odd. If it is even display the following message
if (( num % 2) == 0)
if ((num % 2) == 1)
23
Computer Engineering Department
#include <iostream>
using namespace std;
int main()
{
..
..
..
..
return 0;
}
I will leave example 2 to be done as homework.
if else if else: The if-else statement is used when we have two paths in our
problem, the first one will be active when the condition is true otherwise we will go to
the other path. In our previous even odd checker example, the number is either even or
odd it cannot be anything else, or both at the same time. Thats why the two if
statements can be rewritten as follow:
24
Computer Engineering Department
Nested if-else statements; this statement is used when we have sets of conditions to
be checked one after another in a specific order.
Example: 1
if (the student grade less than 60)
he is F
else if (the student grade less than 70)
he is D
else if (the student grade less than 80)
he is C
else if (the student grade less than 90)
he is B
else if (the student grade less than 100)
he is A
While loop:
This statement is used when we want to repeat a specific action certain amount of
times. In our even odd checker example we did it to check the condition for only one
number entered by the user. With the while loop we can repeat the checking for several
times, without rerunning the program.
Exercise2 (cont): Redo the previous example for even odd checker and it should be
repeated 10 times.
Answer
while (counter < 10) Comment [z11]: Our while loop will be
repeated unless the counter is
greater than 10.
{
25
Computer Engineering Department
Color Wavelength
From the given table, write a C++ program using if else
statement and while loop to read the wavelength from the
violet 380450 nm
user and gives the equivalent color representation (within the
visible spectrum). Your program should stop when -1 is
blue 450495 nm
entered as a value for the wavelength.
green 495570 nm
yellow 570590 nm
orange 590620 nm
red 620750 nm
26
Computer Engineering Department
Lab Homework:: Fever is a frequent medical sign that describes an increase in internal
body temperature to levels above normal. According to one common rule of thumb,
fever is generally classified as follows:
Grade C Write a C++ program that will take n different
Low-grade 38-39 temperatures and print their equivalent classification.
Moderate 39-40 Your program must use while loop and if else
High-grade 4041.1 statement.
Hyperpyrexia >41.1
27
Computer Engineering Department
Lab No. 3
Control Structures (II)
Objectives
1. Understanding the switch statement.
2. Understanding the for loop statement.
3. Learning how to write a statement in a C++ program
4. Learning how to write a for loop statement in a C++ program.
Software Tool:
Visual Studio 2013
Background
The switch case statement: The switch statement is another way to present the
nested if else statement. In the switch statement we need a key. The value of the key
will direct me to the correct path. For example, if we have a food menu divided into
three taps: 1. Entrance. 2. Main course. 3. Desert. When you choose 2 you will be taken
to the main course tap, this means the number is the key. The switch statement is
written as follow:
switch (key) Comment [z14]: The value of the key
here is integer from 1 to 3.
{
case 1: Comment [z15]: If the value of the key
is 1 then do the statement below till
cout<<Entrance\n; you reach the break.
break; Comment [z16]: This is an instruction
to tell the program that we found our
case 2: case and please break till the end of
the switch statement.
cout<<Main course\n;
break;
Case 3:
cout<<Desert\n;
break;
break;}
28
Computer Engineering Department
Lab exercise: Update the problem of even odd checker from if-else statement to switch
case statement.
For loop: In the previous lab we discussed the while loop, and we understood that is it
a way to repeat a group of statements in C++. The for loop is another way to do that,
but in for loop usually we have a starting value, stopping condition and the increment all
in the header of the for loop. The header of the for loop is look like this:
Lab exercise: Update the problem of even odd checker from while loop to for loop.
case 7:
cout<<The grade is C\n;
break;
case 6:
cout<<The grade is D\n;
break;
case 5:
case 4:
case 3:
case 2:
case 1:
29
Computer Engineering Department
case 0:
cout<<The grade is F\n;
break;
default:
cout<<error\n;
break;
}
Exercise2: Write a C++ Programming Language that will read the user date-of-birth in
the following format: (YYMMDD)
Where YY represents the year, MM represents the moth and the DD represents the Day.
Sample output:
901002
int bdate;
Use 1 integer division (/) and 1 modulus (%) to extract the month digits.
30
Computer Engineering Department
Lab Homework: Solve the following C++ problem in order to prepare for quiz 1.
Write a c++ program language to perform the following output:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice [1,2,3,4] or -1 to stop
1
Enter two numbers:
4
5
4 +5=9
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice [1,2,3,4] or -1 to stop
3
Enter two numbers:
4
5
4 * 5 = 20
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice [1,2,3,4] or -1 to stop
-1
Thank you for using our calculator
Press any key to continue
31
Computer Engineering Department
Lab No. 4
Functions (I)
Objectives:
1. Learn how to write a function in C++.
2. Learn how to return values from a function in C++.
Software Tool:
Visual Studio 2013
Background
What is function? In C++ programming, we can combine a set of statements to be
executed together, in a form called function. Usually it is a set of mathematical
operations.
Function definition:
Define prototype of the function before OR Defining the whole function before the
the main then writing the function after main
the main
#include <iostream> #include<iostream>
using namespace std; using namespace std;
void functionname(int, int, int, ); viod functionname(int a, int b, int c, ) Comment [Z23]: Function parameter.
Exercise 1: Write a C++ program to calculate the value of x raised to the power y (xy).
Repeat the operation for 10 numbers. First write it in the main. Then write it using a
function.
32
Computer Engineering Department
Exercise 1: Write a C++ program that will use the function fact to calculate the
Factorial of an integer n. Repeat the operation until the user enter -1 as a value of n.
Useful hints:
Factorial of 5 = 5 * 4 * 3 * 2 * 1
Factorial of n = n *(n-1)*(n-2)*(n-3)*...*3*2*1
33
Computer Engineering Department
Lab No. 5
Functions (II)
Lab Objectives:
1. Learn how to return multiple values from a function in C++ by reference.
2. Learn basic mathematical functions from library cmath.
Software Tool:
Visual Studio 2013
Background: Referenced variables are used when you need the function to change the
value of more than one variable and show the effect in the main. You can define a
referenced variable by giving the notation & before the variable name in the function
argument.
Example: Write a C++ function swap that will take two variables x and y and exchange
their values:
Solution: write the following program and check the output
#include <iostram>
using namespace std;
void swap (int &x, int &y); Comment [226]: This notation is used
to defined the variable as referenced
variable
int main()
{int a,b;
cout<<Enter two values for x and y \n;
cin>>a>>b;
cout<<Before swap:The value of x =<<x<< The value of y =<<y<<endl;
swap(a,b);
cout<<After swap:The value of x =<<x<< The value of y =<<y<<endl;
return 0;
}
void swap(int &x, int &y)
{ int temp;
temp= x;
x=y; Comment [227]: The new value of x
will be changed in the main too on
y = temp; the variable a.
} Comment [228]: The new value of y
will be changed in the main too on
the variable b.
34
Computer Engineering Department
Exercise 1: Write a C++ program that calls a function findac to calculate the area a,
and circumference c of a circle. The function will read the radius of the circle r from the
user and display the area and the circumference on the screen.
#include <iostream>
using namespace std;
void findac (double , double &, double &);
int main()
{
double r, a, c;
findac( r, a, c);
..
return 0;
}
void findac(double x, double &w, double &z)
{
w = 3.14 * x * x ;
z = 2.0 * 3.14 * r; }
Exercise 2: Write a function called distance that calculates two distances. The first
distance is between the two points (x1, y1) and (x2, y2) entered by the user, and the
second distance is between the point (x1, y1) and the origin (0,0). All numbers and
returned values should be of type double. The distance is calculated using the following
equation:
distance = ((X2-X1)2 + (Y2-Y1)2)1/2
Useful Hints:
1. All numbers and return values should be of type double.
2. Use library cmath for finding the power and square-root
#include<cmath>
3. Use the functions pow(x,y) from cmath library to calculate xy.
4. Use the function sqrt(x) from the cmath library to calculate x1/2.
35
Computer Engineering Department
Lab No.6
Arrays(I)
Objectives
1. Understand how to define array in C++.
2. Ability to read write and manipulate arrays.
Software Tool:
Visual Studio 2013
Background
What does array means? Arrays are data structures consisting of related data item of
the same type. The array can be of any type, It could be integer, double, character or
string.
following:
1. Finding the maximum the minimum and the average and print them.
2. Finding the grades below the average and print it.
3. Find the grades above the average and print it.
#include <iostream>
using namespace std;
int main()
{
int i;
double sum=0,max, min, ave, mynumlist [10];
cout<<
for (i=0; i<10; i++)
{
cin>>mynumlist[i];
sum+=mynumlist[i];}
i=0;
max = mynumlist[i];
36
Computer Engineering Department
return 0;
}
Complete the previous program and run it
37
Computer Engineering Department
Lab No. 6
Arrays (II)
Objectives
1. Understand how to pass an array to a function in C++.
2. Be able to manipulate an array that is defined in the main using functions.
Software Tool:
Visual Studio 2013
Background:
Arrays & functions: From the previous lab we learned how to define the array in the
main and how manipulate the array looking for certain values (maximum minimum or
comparisons).
Exercise1: Write a C++ program to search a one dimensional array x of size n for a specific
value key. The value of n will be entered by the user. The program will use a function named
find to search for the key in the array x and find the frequency of its occurrence and save it in
the variable freq and find the location of the first occurrence and store the index in variable loc.
Sample Output:
The Enter the size of the array x: 6
Enter the values for the array x; 2 4 7 3 4 6
Enter the key: 4
The value 4 is presented 2 times
The first key at element 1
Solution tips:
We need to define the prototype of a function that takes an array x with its size which is n and
return the values of the two variable freq, and loc which will be reference variables. The
prototype will be as follows:
Comment [z31]: Defining the array to
void find (int [], int, int &, int &); be passed to the function with
variable size, its size is defined in the
main.
Comment [z32]: & symbol refers to call
by reference variable which is
variable definition in the main: explained in the function lab.
Comment [z33]: Defining the array x of
int x[50], int n, int freq, int loc; type integer with maximum size 50.
38
Computer Engineering Department
to define the function it will be as follows: Comment [z35]: Size of the array.
Comment [z36]: The variable freq
defined in the main as integer and
void find (int x[], int n, int &freqf, int &locf) will be passed by reference to the
#include <iostream> function.
Comment [z37]: The variable freq
using namespace std; defined in the main as integer and
will be passed by reference to the
function.
void find (int [], int, int &, int &);
int main()
{
int x[50], int n, int freq, int loc;
.
.
find(x,n,freq,loc);
.
Return 0;
}
void find (int x[], int n, int &freqf, int &locf)
{
..
..
..
..
}
39
Computer Engineering Department
Lab No. 7
(I)Pointers
Objectives
1. Learning how pointers are defined and used in C++.
2. Ability to write a C++ program using pointers to pass referenced variables to
function.
Software Tool:
Visual Studio 2013
Part II-Pointers: Pointers are certain type of variables defined to hold the address of
the variable it is pointing too. To define the variable as pointer we add the symbol *
before the variable name.
Example:
int y, *yptr;
Assume having the following C++ instructions, and assume the value of y is stored in
memory location 6000000. Verify the output result.
int y=5;
int *yptr;
yptr=&y;
//output
cout<<*yptr<<endl; //5
cout<<y<<endl; // 5
cout<<yptr<<endl; // 600000
cout<<&y<<endl; //600000
Conclusion: The address operator (&) is a unary operator that returns the memory
address of its operand. However, the indirection/dereferencing operator (*) is a unary
operator that returns the synonym /nick name of the object to which its pointer operand
points.
40
Computer Engineering Department
int main()
{
int x[50], int n, int freq, int loc;
.
.
find(x,n,&freq,&loc);
.
return 0;
}
void find (int x[], int n, int *freqf, int *locf)
{
..
..
..
..
}
Exercises 3:
Write a program that will do the following:
Sample output:
Enter array size: 5
Enter the value of array A: 1 2 3 4 5
Enter the value of array B: 6 7 8 9 10
Elements of Array C : 5 6.08088 7.06538 8 8.90273
Average of array C = 7.0098
41
Computer Engineering Department
Lab Homework: Solve the following C++ problem at home in order to prepare for quiz
1, do the entire job by yourself and ask the lab engineer for help if needed.
Write a C++ program that will read n students grades (n could be from 1 to 100) of
c++ test and find the 1st, the 2nd and the 3rd. The redo the exercise using functions.
42
Computer Engineering Department
Lab No. 7
(II)Strings
Objectives:
1. Introducing the type definition string and the library string.
2. Familiarization with predefined string functions in string library.
3. Ability to use strings manipulation functions.
Software Tool:
Visual Studio 2013
Background
A string is a series of characters treated as a single unit. A string may include
letters, digits, and various special characters such as +, -, *, / etc.
In C++, a string is an array of characters ending in the null character (\0), which
specifies were the string terminates in memory.
A string maybe assigned in a declaration in different ways as follows:
Common Errors: Not allocating sufficient space in a character array to store the null
character that terminates a string.
The string-handling library provides many useful functions for manipulating string data,
comparing strings, searching strings for characters and other strings, tokenizing strings
(separating strings into logical pieces) and determining the length of strings.
Exercise 1: Write a C++ program to define strings and manipulate them using the
string functions available in cstring library: strcpy, strcat, strcmp and strlen and check
your output.
Solution hints:
You need to include the cstring library
#include <cstring>
Define the following strings:
char s1[25] = "Hello ";
char s4[15]
strcat(s1 , s2);
strcat is string concatenate function were it will concatenate the string s2 to the end of
string s1 and store it in s1. Make sure that s1 is large enough to hold both strings.
cout<<strlen(s3);
strlen is string length function were it wwill count the characters in string s3 and return
the length as integer.
44
Computer Engineering Department
cout<<strcmp(s1, s3)
strcmp is string compare function were it will take two functions and compare them if
they are equal it will return 0 if s1 is greater than s3 it will return the value 1, if s1 is
less than s3 then it will return the value -1.
45
Computer Engineering Department
Lab No. 8
Files
Objectives
1. Understanding the concept of files in C++ programming.
2. Ability to read from creates, and writes to files in C++.
Software Tool:
Visual Studio 2013
Background: Storage of data in variables and arrays is temporary. Files are used for
data persistence-permanent retention of large amount of data. The reason is that files
store data so that data may be retrieved for processing.
Exercise 2: Write a C++ program which will read an integer from a data file called
in.txt and find its factorial. Print the number and it factorial in another file called
out.txt.
Solution hints:
#include <fstream>
fin >> n;
46
Computer Engineering Department
fout << "The factorial of " << n << " is: " << nf << endl;
The input file needs to be created and filled with the required data before running the
program.
In case you do not have cin or cout in your program then the terminal screen will be
empty with no results. You need to open the output file to check the correctness of your
program.
47
Computer Engineering Department
Challenge Exercise:
1. (Implement reading data from a file): Assume having an input file which
contains student ID, name, and total grades. Write a C++ program that reads
the data from that input file and display it on the screen. Sample output might
be as follows:
2. (Implement writing data to a file): Write a C++ program that calculates the
squares of the numbers in the range from 0 to 9 and display the numbers and
their squares in a tabular format in an output file. The output should be in the
following manner:
Number Square
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
3. Use the HELP provided with your C++ visual studio to find the role of each of
the following file open modes: ios::app, ios::ate, ios::in, ios::out, ios::trunk,
and ios::binary.
48
Computer Engineering Department
Lab No. 9
Classes:
Objectives:
1. Familiarization with Classes definition in C++.
2. Being able to define class with data members.
3. Being able to access the data members through the functions set and get.
4. Being able to write a constructor to initialize the data members of the class.
Software Tool:
Background
Why do we need classes? Classes are used to create new data types that do not
exist in C++ programming language (i.e. int, double, char ..). Classes enable the
programmer to model objects that have attributes (represented as data members) and
behaviors or operations (represented as member functions). That is types containing
data members and member functions are defined in C++ using the keyword class.
Once a class has been defined, the class name is now a type name, which can be
used to declare objects of that class.
#include <iostream>
using namespace std;
class Student Comment [z45]: Class name similar to
variable name in naming rules.
{
public: Comment [z46]: Reserved word to
indicate that this area is public can
void displayMessage( ) be accessed by the main.
{
cout << "Welcome to Kuwait University \n";
}
}; Comment [z47]: Every class must end
with semi-colon.
int main( )
{
Student s1; Comment [z48]: Defining s1 as a class
of type Student
49
Computer Engineering Department
OUTPUT:
Note that:
The class name is case sensitive. To write a professional C++ program, you need
to capitalize the first character of the class name.
Class definition will always end with ; .
The member access specifies public and private are used to control access to a
classs data members and member functions.
A classs private members can be accessed only by member function of that class.
The public members of a class maybe accessed by any function in the program
that holds as handle on an object of that class.
Exercise 1: Write a C++ program that defines a class Student with a data members
first name firstName (type string), and student number, studentId (type int). Your
class should have a constructor that initializes the two data members. Provide a set and
get function for each data member. Write a test program that demonstrates class
Students capabilities. Create two Student objects s1, s2 and display each objects
firstName and studentId.
#include <iostream>
#include <string>
class Student
{
public:
Student (string, int);
void setName (string);
// define the set function for the data member studentId
string getName();
//define the get function for the data member studentId
private:
string firstName;
int studentId;
};
setId(id);
}
string Student::getName()
{
return firstName;
}
int main( )
{
Student s1("Ahmed" , 205113344);
Student s2("Raghda" , 206115566);
cout << "Name and id of s1 is: " << s1.getName() << " " << s1.GetId() << endl;
return 0;
}
The class has a constructor function which initializes the two data members. This
constructor function is a special member function that has the same name of the
class and no return data types. The constructor function is invoked each time an
object of the class is created.
Since data members cannot be initialized in a class definition, then they must be
initialized in a constructor, or their values may be set after their object is created.
Set and get functions are provided for each data member.
51
Computer Engineering Department
Set function is used to initialize the value of the data member (i.e. name or Id);
therefore, it has an input and has no output (i.e. void Student::setName(string name)
and void Student::setId(int id)).
Get function is used to retrieve the value of the data member; therefore, it has no
output (i.e. string Student::getName()and int Student::GetId()).
Since the member functions blocks were written outside the class, then you need
to attach the class name followed by :: before the function name in the function
(i.e. void Student::setId(int id)).
Exercise 2 Redo exercise 2 but with separating the file into, header file, class file and
main program file.
// student.h
#include <string>
using namespace std;
class Student
{
public:
Student (string, int);
void setName (string);
// define the setID function for the data member studentId
string getName();
//define the getID function for the data member studentId
private:
string firstName;
int studentId;
};
// student.cpp
#include <string>
using namespace std;
#include "student.h"
52
Computer Engineering Department
string Student::getName()
{
return firstName;
}
// write the function for getID
// lab10.cpp
#include <iostream>
#include <string>
using namespace std;
#include "student.h"
int main( )
{
Student s1("Ahmed" , 205113344);
Student s2("Raghda" , 206115566);
cout << "Name and id of s1 is: " << s1.getName() << " " << s1.GetId() << endl;
// write the cout for s2;
return 0;
}
Challenge Exercise:
Create a class rectangle with attributes length and width, each of which defaults to
1. Provide member functions that calculate the Perimeter and the area of the
rectangle. Also provide set and get functions for the length and width attributes.
The set functions should verify that length and width are each floating-point
numbers larger than 0.0 and less than 20.0.
Create a class TicTacToe that will enable you to write a complete program to play
the game tic-tac-toe. The class contains as private data a 3-by-3 double
subscripted array of integers. The constructor should initialize the empty board to
all zeros. Allow two human players. Wherever the first player moves, place a 1 in
53
Computer Engineering Department
the specified square. Place a 2 wherever the second player moves. Each move
must be an empty square. After each move, determine whether the game has
been won or is a draw. If you feel ambitious, modify your program so that the
computer makes the move for one of the players. Also, allow the player to specify
whether he or she wants to go first or second. If you feel exceptionally ambiguous,
develop a program that will play three-dimensional tic- tac-toe on a 4-by-4 board
(Extremely Challenging!).
54