You are on page 1of 54

Computer Engineering Department

ENG 200 - C++ Programming Laboratory

Lab Manual
ENG 200
C++Programming Language

Prepared by:

Eng. Zainab Bahbahani Eng. Amal Al-Saleh

1
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

Table of content:

Lab Number Topic


1 Lab No. 1(I) Introduction to C++ programming Language (I) 3
2 Lab No. 1(II) Introduction to C++ programming Language (II) 16

3 Lab No. 2 Control Structures (I) 23

4 Lab No. 3 Control Structures (II) 28

5 Lab No. 4 Functions (I) 32

6 Lab No. 5 Functions (II) 34

7 Lab No. 6(I) Arrays 36

8 Lab No. 6(II) Arrays & Functions 38

9 Lab No. 7(I) Pointers 40


10 Lab No. 7(II) Strings 43
11 Lab No. 8 File Processing 46
12 Lab No. 9 Classes 49

2
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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.

Simple output instruction

cout<< Welcome All to C++ course\n; Comment [z1]: Anything between the
quotation will be displayed as it is.

1. Anything written between the quotations will be printed as it is.


2. C++ provides control instructions to be used between the quotations to control the
sentence format, for example:
a. \n = new line
b. \t = tab
3. You can add newline to the simple output instruction as follows:
cout<<Welcome All<<endl;

3
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

The simple output C++ program will be like this:

#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

ENG 200 - C++ Programming Laboratory

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

2. When the program is opened the following windows will be displayed:

5
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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:

6. A pop up win32 console wizard will be displayed click then

Select then click as shown in the next page:

7
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

A new workplace is created as shown:

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

, and in the field labeled Name write l1.cpp

,then click
As shown in the following page:

8
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

A new empty sheet will be created as shown below:

9
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

In this page you can write your code.

8. Write the following C++ code:

While typing the code you will notice:


The editor gives different colors for reserved words, quote, library name,
comment, or simple command.
Whenever you add a bracket or quotation symbols the editor will print it as pair,
i.e when you print { the editor will add } right after it.
The editor displays a pull down menu while typing the commands so you can
either select the required command from the list or type it yourself.
9. To build the file go-to menu Build click Build Lab1

10
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

If no errors in your code you will get the following message:

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

ENG 200 - C++ Programming Laboratory

How to copy the output:


1. On the output console screen click on , a pull down menu will be displayed,
select Edit Mark as shown below:

12
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

2. On the console screen select the required lines as shown:

3. Click again on and select Edit Copy as shown:

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

ENG 200 - C++ Programming Laboratory

14
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

Lab Homework :

Prepare for the next lab by reading the following lines:

Arithmetic operations in C++

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:

Let a=5, b=2, c=6, d=2

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:

Answer the following questions:

Let a= 5, b=8, d=2

What will be the output of the following :

1. a += b (a = )
2. a = b/d (a = ..)
3. a = b%d (a = ..)

15
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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

Background: Exercise from lab 1

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:

sum = num1 + num2

ave= (num1+num2)/2

Answer:

In order to solve the problem first we need to define the variables num1, num2, and
sum as integers.

In Naming the variable we must take into considerations two things:

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

ENG 200 - C++ Programming Laboratory

The following line is the statement for defining integers in C++:

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.

statements and both of them are equivalent:

cin >>num1>>num2; cin>>num1; Comment [z4]: Storing the first integer


in num1
cin>>num2;
Comment [z5]: Storing the second
To display the result for the user after the calculation write the following output line: integer in num2

cout<<The sum is: <<sum<<endl;

cout<<The ave is: <<ave<<endl;

Please fill the space in the code for exercise 1:

#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

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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:

C:\Users\Dell\Cpp1.cpp: error C2143: syntax error : missing ';' before '}'

C:\Users\Dell\Cpp1.cpp:  File path

error C2143:  Error/Warming Number

syntax error : missing ';' before '}'  Error/Warning Description

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

ENG 200 - C++ Programming Laboratory

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'

'x' : undeclared identifier Declare x (int x;)

newline in constant Missing the last " in


4
Ex: cout<<"Hello; the cout

illegal escape sequence Missing the first " in


5
Ex: cout<<Hello"; the cout

syntax error : missing ';' before


6 Missing ;
Ex: cout<<"Hello"

20
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

binary '<<' : 'class


std::basic_ostream<char,struct
std::char_traits<char> >' does not The is an error in
7 define this operator or a conversion to '<<' for the cout or
a type acceptable to the predefined '>>' for the cin
operator

Ex: cout<<"hello">>endl;

mismatch in formal parameter list The is an error in '<'


8 for the cout , should
Ex: cout<"Hello"<<endl; be '<<'

9 unexpected end of file found Misssing { or }

The is an error in

int Main();
missing function header
10 It should be
Ex: int Main();
int main(){

21
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

Warning Justification

'main' : function should return a Missing: return 0;


value; 'void' return type assumed

2 local variable 'x' used without having


been initialized
The available should be
Ex: initialized

int x;

cout<<x<<endl; Cin>>x; or x = 2;

output: Depends on the


question.
-858993460

Press any key to continue

Using cin for one variables:

cin >> x;

Using cin for more than one variable:

cin >>x>>y;

cin >> x>> y>>z;

***Dont write it: cin >> x, y ;

22
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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

Simple if statement: The If statement is a statement used when an instruction cannot


be executed unless a certain condition is achieved, for example:

1. If (the number is divided by 2) then Comment [z6]: Condition, the condition


must be true to execute the
(Tell me it is an even number). conditional instruction.
2. If (the number is divided by 2 and 3) then Comment [z7]: Conditional instruction.
Comment [z8]: Condition.
(Tell me it is a multiple of 6). Comment [z9]: Conditional instruction.

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

The number is even

If the number is odd display the following message:

The number is odd

Answer: The if statement in C++ is written as follows:

if (( num % 2) == 0)

cout<<The number is even\n;

if ((num % 2) == 1)

cout<<The number is odd\n;

23
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

Please fill the space in the following code:

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

if statement if else statement


if (num%2 == 0) if (num%2 == 0)
cout<<the number is even\n; cout<<the number is even\n;
if (num%2 == 1) else
cout<<the number is odd\n; cout<<the number is odd\n;

Exercise2: Redo Lab 2 exercise using if-else statement.

24
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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

The while loop is written as follows

counter =0; Comment [z10]: We must initialize the


loop to indicate the first time

while (counter < 10) Comment [z11]: Our while loop will be
repeated unless the counter is
greater than 10.
{

Comment [z12]: Write here the


statement that needed to be repeated

counter ++; Comment [z13]: Here we are


incrementing the counter. Other way
to do it is counter = counter +1;
}

25
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

Exercise 3: Colours that can be produced by visible light of a single wavelength


(monochromatic light) are referred to as the pure spectral colour. Although the spectrum
is continuous and therefore there are no clear boundaries between one colour and the
next, the ranges may be used as an approximation, as follows:

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

The output should be as follows:

Enter wavelength between 380nm and 750nm: 400


The color is Violet

Enter wavelength between 380nm and 750nm: 470


The color is Blue

Enter wavelength between 380nm and 750nm: 500


The color is Green

Enter wavelength between 380nm and 750nm: 580


The color is Yellow

Enter wavelength between 380nm and 750nm: 600


The color is Orange

Enter wavelength between 380nm and 750nm: 700


The color is Red

26
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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;

default: Comment [z17]: This is a reserved


word used to give an output for any
other value of key out of our required
cout<<Do nothing\n; rage.

break;}

28
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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:

for ( starting counter; stopping condition; incrementing the counter)

Lab exercise: Update the problem of even odd checker from while loop to for loop.

Answer: The for loop header will be as follows:

for (i = 0; i <10; i++) Comment [z18]: Starting the counter

{ Comment [z19]: Stopping condition


Comment [z20]: Dont forget semicolon
is what we use in the for loop.
} Comment [z21]: Incrementing the
Exercise1: Redo from lab 3 example 1 using case statement. counter
Comment [z22]: The statements to be
repeated.
switch(g)
{
case 10:
case 9 :
cout<<The grade is A\n;
break;
case 8:
cout<<The grade is B\n;
break;

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

ENG 200 - C++ Programming Laboratory

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.

And store it as an integer.

The program should be able to tell the month of birth in words.

Repeat the process for n number of date-of-birth entered by the user.

Sample output:

Please enter your date of birth in format [YYMMDD]

901002

You were born in October

Hint: variable definition:

int bdate;

Use 1 integer division (/) and 1 modulus (%) to extract the month digits.

30
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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.

int main() { Comment [Z24]: Important


{ } Comment [Z25]: Function parameter
.. int main()
return 0; {
}
void functionname(int a, int b, int c, ) return 0;
{ }
}
Why we need the function? What is a function parameter? The following lab exercise will
make it easy to answer these questions:

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

ENG 200 - C++ Programming Laboratory

In the main Function


#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int xpowery (int x, int y)
{ {
int xpowery=1, x, y; int power=1;
. for (i=0; i<= y; i++)
. power *= x;
for (i=1; i<=y; i++) retun power;}
xpowery*=x; int main()
.. {
int x, y;
return 0; .
} .
cout<<The value of <<x;
cou<< to the power <<y;
cout<< = <<xpowery(x,y)<<endl;
return 0;
}

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

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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.

How to define a one dimension array in C++?


<type> <name> [size];
example: int myarray[10] Comment [Z29]: Array name
Comment [Z30]: Array size, it is a must
to give the array size when you
Exercise 1: Write a C++ program that reads 10 student grades in the exam then do the define it in the main.

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

ENG 200 - C++ Programming Laboratory

for (i=1; i<10; i++)


if (mynumlist[i] > max)
max = mynumlist[i];
.
.
ave=
.
..
//find the grades above the average
//find the grades below the average

return 0;
}
Complete the previous program and run it

Exercise 2: Modify the previous code to do the following:


Search the array for the maximum value found and tell how many maximum found in
the array and what it is first location of the maximum value in the array.

37
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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

Arrays can be also manipulated through functions.

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

ENG 200 - C++ Programming Laboratory

to call the function from the main it will be as follows:

find(x,n,freq,loc); Comment [z34]: The array and how it


is passed to the main.

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

ENG 200 - C++ Programming Laboratory

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:

To define y as integer and yptr as a pointer

int y, *yptr;

Assignment statements with pointers

yptr = &y; //means the variable y will hold the address of x

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

ENG 200 - C++ Programming Laboratory

Exercise 2: Redo exercise 1 using pointers instead of reference variables.


#include <iostream>
using namespace std;

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)
{
..
..
..
..
}
Exercises 3:
Write a program that will do the following:

1. Enter the values of arrays A and B. This is done by function read.


2. Calculate the values of array C, where C[i] = (A[i] + 2/3*(B[i]). This is done
by function cal.
3. Calculate the average of the resulted array C. This is done by function ave.
4. Print the output from the main function.

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

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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:

char color[]= blue; Comment [z38]: array color of 5


characters b , l, u, e, and \0
char color[]={ b, l, u, e, \0 };
Comment [z39]: array color of 5
characters b , l, u, e, and \0

const char *colorPtr = blue Comment [z40]: pointer variable


colorPtr that points to the letter b in
the string blue
Important note: when declaring a character array containing a string, the array must be
large enough to store the string and its terminating null character.

Common Errors: Not allocating sufficient space in a character array to store the null
character that terminates a string.

How to store a string?


A string can be stored in an array using stream extraction with cin. i.e. cin >>word.
To input an entire line of text into an array, C++ provides the function cin.getline
which takes three arguments a character array in which the line of text will be stored,
a length, and a delimiter character. See the next example:

char sentence [80]; Comment [z41]: declares array of 80


characters
cin.getline (sentence, 80, \n);
Comment [z42]: reads a line of text
cin.getline (sentence, 80); from the keyboard into the array
Comment [z43]: reads a line of text
String manipulation functions of the string-handling library from the keyboard into the array and
has /n as a default value.
43
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

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 s2[15] = "I Like ";

char s3[15] = "C++";

char s4[15]

How to use the string functions:


strcpy(s4, s1);
strcpy is a function to do string copy were it will copy the value in the s1 to s4. Make
sure that s4 is large enough to hold s1.

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

ENG 200 - C++ Programming Laboratory

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

ENG 200 - C++ Programming Laboratory

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.

C++ provides several statements to allow the programmer to manipulate with


files, for example creating a file, writing data to a new file appending data to an existing
file, reading data from a file, updating an existent file. In this lab we are interested in
creating new file and write to it data, and open an existent file to read data from it.

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 the following file manipulation library

#include <fstream>

To define a file to read from:

ifstream fin ("in.txt"); Comment [z44]: The input data file


must have the exact name as defined
below to read from.
to create a file to write data to

ofstream fout ("out.txt");

To read a single integer from a file

fin >> n;
46
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

To write to a new file

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

ENG 200 - C++ Programming Laboratory

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:

ID Name Total Grade


112233 Maha 77.5
113344 Ahmad 82.6
115566 Ali 65.3
115577 Suha 98.5

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

ENG 200 - C++ Programming Laboratory

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:

Visual Studio 2013

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.

Example 1: write the following code and examine the output:

#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

s1.displayMessage( ); Comment [z49]: How to access a


function in the class defined in the
public area.
return 0;}

49
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

OUTPUT:

Welcome to Kuwait University

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>

using namespace std;

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

Student::Student (string name, int id)


{
setName(name);
50
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

setId(id);
}

void Student::setName(string name)


{
firstName = name;
}

//write the function setID

string Student::getName()
{
return firstName;
}

// write the function for getID

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

Regarding the previous program, you can notice the following:

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

ENG 200 - C++ Programming Laboratory

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"

Student::Student (string name, int id)


{
setName(name);
setId(id);
}

52
Computer Engineering Department

ENG 200 - C++ Programming Laboratory

void Student::setName(string name)


{
firstName = name;
}
//write the function setID

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

ENG 200 - C++ Programming Laboratory

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

You might also like