c++ lab manual

74
1 Yarmouk University Computer Science Department C++ Programming Lab manual Prepared by: Dr. Iyad Abu Douh, Ahmed Bani-Hani, Fatima Abu-Hawas, Siba Shaher, Asma Alhami, Enas Abdelrazak, Reham Abdelqader, Maisaa Khazaleh, Nahed Mansour, Wafaa Qarqaz, Amal Abu Naser, Ikdam Alhami

description

c++ lab manual

Transcript of c++ lab manual

Page 1: c++ lab manual

1

Yarmouk University

Computer Science Department

C++ Programming

Lab manual

Prepared by:

Dr. Iyad Abu Douh, Ahmed Bani-Hani, Fatima Abu-Hawas,

Siba Shaher, Asma Alhami, Enas Abdelrazak,

Reham Abdelqader, Maisaa Khazaleh, Nahed Mansour,

Wafaa Qarqaz, Amal Abu Naser, Ikdam Alhami

Page 2: c++ lab manual

2

Table of Contents

Lab 1: Use the Visual studio environment and Debugging the Code. ...... 3

Lab 2: Use the arithmetic operations and if/else selection structure. ... 11

Lab 3 Classes and Objects .............................................................. 18

Lab 4 Separating class interface from its implementation and data

validation. ..................................................................................... 30

Lab 5 More about selection structures( if and switch statements). ...... 36

Lab 6 Control Structures: while , do-while and for Loop ................... 46

Lab 7 Using Functions .................................................................... 50

Lab 8 Random numbers, scope rules, and default Arguments ............ 55

Lab 9 Function Overloading and recursion ....................................... 60

Lab 10 Arrays ................................................................................ 65

Lab 11 Using Pointers ..................................................................... 70

Lab 12 Using files. ......................................................................... 73

Page 3: c++ lab manual

3

Lab 1: Use the Visual studio environment and Debugging the

Code.

Lab Objectives:

• Learn the student, how to open the Microsoft visual c++ 6.0 , and use it to write

and execute a simple program that print a simple statement.

• Find and correct the errors.

• Applying the escape characters like \n, \t,\r,\a.

• Using the single line and multiline comments.

Background:

The student should know the structure of a simple c++ program, in that, any program may

be written according to the following format:

#include<iostream>

using namespace std;

void main()

{

//Program body

}

Also the student should know the meaning for each one of the escape characters:

\n : new line

\t : tab space

\a: alarm

\r: return the cursor to the first character in the same line.

The syntax for comments:

The // character is used at the beginning of a single line comment.

The characters (/*)is used at the beginning of a multi line comment, and the character (*/) is

used at the end.

Pre-lab:

Learn the basic structure for a simple c++ program

Page 4: c++ lab manual

4

Learn the function of the escape characters and who to use them.

Know the syntax for writing comments in the program.

Assessment tools:

The assessment is according to the student participation in the lab if the student solves the

exercise, he will get the participation mark for this lab.

Lab Assignments:

• Lab assignment-1

Learn the student how to open Microsoft visual c++ 6.0 :

• Click on the Start button.

• Choose all programs.

• Then choose Microsoft visual c++ 6.0 as shown in figure 1.

Page 5: c++ lab manual

5

Figure 1

Then you will see a new window that enables you to open a file and write a new program as

shown in figure 2.

Page 6: c++ lab manual

6

Figure 2

From the file menu choose new, a new window will appear as shown in figure 3.

Page 7: c++ lab manual

7

Figure 3

Click on the tab project, choose win32 console application, specify a name for the project,

and then click on the button ok.

From the window appears chooses an empty project then click on finish as shown in figure4.

Page 8: c++ lab manual

8

Figure 4

After that, from the file menu choose new , from the new window click on the tab file,

choose c++ source file, then click on ok as shown in figure 5.

Figure 5

Lab assignment-2

Use the Microsoft visual c++ 6.0 to write the following code.

// this rogram to print a simple statement

#include <iostream>

using namespace std;

void main()

{

cout << "Welcome to the wonderful world of C++!!!\n";

}

Page 9: c++ lab manual

9

In order to compile this code, from the menu build choose build as shown in figure6.

Figure 6

If the program has any error, this error will be list in the window, and you can correct it. To

be able to execute your program, you should correct all the errors.

In order to run your program, from the menu build choose execute, a new window will

appear like figure7.

• Lab assignment-3

What is/are the output for the following code:

#include <iostream>

using namespace std;

void main()

{

cout << "Welcome to the wonderful world of C++!!!\n";

Page 10: c++ lab manual

10

cout << "Lab1 \t";

cout<<"\n END\t PROGRAM\t BYE";

cout<<"Welcome in yarmouk univerity\rHellooo";

}

Lab Problems:

• Lab Problem-1

Write a program to print the following text:

Hello in my university

(empty line)

Im a student in it faculty

(empty line)

Welcome.

• Lab Problem -2

Find and correct the errors in the following code.

#include <iostream>

void main()

{

cout << "we are happy"

}

• Lab Problem -3

Find the errors in the following code.

#include <iostream>

using namespace std;

void main

{

cout >> "c++ first exam/n";

cout<<"\n END\t PROGRAM\t BYE;

}

Page 11: c++ lab manual

11

Lab 2: Use the arithmetic operations and if/else selection

structure.

Lab Objectives:

• Teach the students how to use the arithmetic operations in mathematical

expressions, and use it to write and execute a simple program.

• Teach the students the arithmetic operation precedence.

• Learn the student, how to use if/else selection statements, and use it to write and

execute a simple program.

• Applying the arithmetic operations with if/else selection statements, and use it to

write and execute a program.

• Convert arithmetic expression from scientific notation to C++ notation.

Background:

• The arithmetic operations in C++ are:

• The precedence of the arithmetic operation in C++ is as the following :

Page 12: c++ lab manual

12

• Decision Making: Equality and Relational Operators:

• If Statement:

o Condition

� Expression can be either true or false

� Can be formed using equality or relational operators

o if statement

� If the condition is true, the body of the if statement executes

� If the condition is false, the body of the if statement does not

execute

If ( Condition )

{

Statement(s);

}

Page 13: c++ lab manual

13

Figure1: the structure of the if statement

Pre-lab:

The student should know the structure of a simple C++ program, in that, any program may

be written according to the following format:

#include<iostream>

using namespace std;

void main()

{

//Program body

}

The student should know the keywords of simple C++.

Assessment tools:

Page 14: c++ lab manual

14

The assessment is according to the student participation in the lab if the student solves the

exercise, he will get the participation mark for this lab.

Lab Assignments:

• Lab assignment-1

Rewrite the following expression in C++ Code and print it.

If the parentheses are removed, we obtain a + b + c + d + e / 5, which evaluates incorrectly

as:

• Lab assignment-2

Read an integer number of a fixed length (3 digits) from the standard input then print its

digits separated by spaces. For example if 364 is the input then the output should be 3 6 4 or

4 6 3

Hint: Use division and modulus operator.

#include<iostream>

using namespace std;

Page 15: c++ lab manual

15

void main( )

{

int x;

cin>>x;

if(x>=100 && x<=999)

{

cout<<x%10<<" ";

x=x/10;

cout<<x%10<<" ";

x=x/10;

cout<<x%10<<" ";

x=x/10;

}

}

• Lab assignment-3

Write a program to read three integer numbers then find and print the largest one

among these numbers.

#include<iostream>

using namespace std;

void main( )

{

int x;

cin>>x;

int y;

1

2

1- Main body

2- If body

3- If condition

3

Page 16: c++ lab manual

16

cin>>y;

int z;

cin>>z;

int max=x;

if(max<y)

max=y;

if(max<z)

max=z;

cout<<"The Max Value is:"<<max<<endl;

}

Lab Problems:

• Lab Problem-1: Read an integer number of a fixed length (4 digits) from the standard input then print the

sum of the odd digits.

• Lab Problem -2

Fill in the blank in the following code; what should the program print? based on

the conditions in the programs that check the x variable value:

#include<iostream>

using namespace std;

void main( )

{

int x;

cin>>x;

if(x>=0)

{

cout<<"x value is...... "<<endl;

if( x%2==0)

{

cout<<"x value is...... "<<endl;

if( x>999 & x<10000)

{

cout<<"x value contains ....digits

"<<endl;

Page 17: c++ lab manual

17

}

}

}

• Lab Problem -3

Body Mass Index Calculator (BMI) calculator formulas for calculating BMI is:

Create a BMI calculator application that reads the user’s weight and height then calculates

and displays the user’s body mass index.

Print “Underweight” if the BMI result is less than 18.5

Print “Normal” if the BMI result is between 18.5 and 24.9

Print “Overweight” if the BMI result is between 25 and 29.9

Print “Obese” if the BMI result is 30 or greater

Page 18: c++ lab manual

18

Lab 3 Classes and Objects

Class Postcard

Lab Objectives

After performing this lab, the students should be able to:

• Discover classes

• Complete a C++ classes. Class definitions include member access specifiers, member

functions, constructors, and data members.

• Perform Object construction

• Control access to object data members and member functions by using the private

member access specifiers.

• To appreciate the value of object orientation.

Background:

No general back ground needed for this lab.

Pre-labs:

1. Review how to define a variable of type string.

2. Quick review for the class definition, the constructor, and the class members.

Lab

PURPOSE: Prints out generic greeting from vacation spot of choice

class Postcard

{

public:

void print()

{ cout << "Dear " << to_string << ", \n";

cout << "Weather's great, Wish you were here !" << "\n\n";

cout << "See you soon," << "\n";

cout << from_string << ".\n";

}

};

Study the Postcard class, and then do the following:

Page 19: c++ lab manual

19

To do: Complete the class definition by

1. Defining a private data members "to_string" and " from_string" of type string.

2. Adding a constructor to receive a string value for both the variable "to_string" and

the variable " from_string" used in print member function.

To do: Write a program that constructs a postcard object and calls the print member

function.

Classes: Class Rectangle

Background:

Rectangle definition

A 4-sided polygon where all interior angles are 90°.

How to find the area of a rectangle:

The area of a rectangle can be found by multiplying the width times the

height.

If a rectangle has a width of length 6 inches and a height of 4 inches, its area

is 6*4=24 square inches

Pre-labs:

1. Review the definition of rectangle.

2. Review the types of rectangle.

3. Write down the equation for computing rectangle Area.

4. Compute manually the area of rectangle of width: 6.5 and height 11.3.

Lab

The following is a class called Rectangle which contains two private data elements ,

Width and Height of type double and a number of member functions. Fill in the

blanks to complete the class definition.

#include <iostream>

------------------

----------- Rectangle

{

: --------------

double Width;

double Height;

Page 20: c++ lab manual

20

public:

//write a constructor that calls set_height and set_width functions to initialize

data members

//write a function set_height that sets the Height if it is positive, otherwise

Height will be zero.

//Function set_width that sets the Width if it is positive, otherwise Width will

be zero.

//write the header of a function area that returns the area of a rectangle

-----------------------------------------------------

{

return Width * Height;

}

void print()

{

//complete function print to print the data members

}

};

void main()

{

//create an object T1 from class Rectangle of width 4 and height 5

//call function area

//call function print

}

Page 21: c++ lab manual

21

Class Calculator

Background:

Pre-labs:

An elementary back ground about the simple math operations (+,-,*,/)

Lab

Studey the following class definition then:

Complete the class definition and

Answer the questions associated to this exercise ********************************************************************

#include<iostream>

using namespace std;

class SimpleCalculator

{

public:

// write definition for add method

//function subtraction definition

double subtract( double a,double b)

{

return a-b;

}

double multiply( double a,double b)

{

return a*b;

}

/*// write definition for divide member function */

Page 22: c++ lab manual

22

};

int main()

{

double x=10.0;

double y= 2.5;

/* declare any other variables needed here */

/* initiate an object of type SimpleCalculator*/

/* write a line that adds x & y through your SimpleCalculator object;

assign the result to a variable named "addition"*/

cout<<"Adding x and y yields"<<addition<<"\n";

double Subtraction =------- // complete the sentance by calling subtract member

function using the declared object.

cout<<"Subtracting y from x yields"<<Subtraction<<"\n";

double multiplication =------- // complete the sentance by calling multiply member

function using the declared object.

cout<<"multiplying x and y yields"<<multiplication<<"\n";

/* write a line that divides x & y through your SimpleCalculator object;

assign the result to a variable named "division"*/

cout<<"divideing x byy yields"<<division<<"\n";

return 0;

}

Q1. why does the SimpleCalculator class have no constructor?

Page 23: c++ lab manual

23

Q2.why are no private data members needed for class SimpleCalculator?

To do:

1. Modify your class so that SimpleCalculator has a private data members called

answer. After performing an operation, assign the result to answer .

2. Add a member function named getAnswer to retrieve the result of the last

arithmatic operation performed by the object.

3. Also, add a constructor for class SimpleCalculator that

initializes the value of answer to 0.

To do:

1. Modify the program so that the SimpleCalculator class has input member function

that allows the user to input two doubles. The function should then store the values

that were input in private data members a and b.

2. Create two constructors for this class, one that takes no arguments and initializes a

and b to 0 and another that takes two doubles and initializes a and b to those

values.

3. Create a member function printValues that displays the values of a and b.

4. Finally, modify the main function by adding the following code segment:

SimpleCalculator sc; //instantiate object

sc.input();

sc.printValues();

cout<<"Adding a and b yields"<<sc.add()<<"\n";

Page 24: c++ lab manual

24

Class Triangle

Background:

Triangles are classified by the number of equal sides they have to:

• scalene - all 3 sides have different lengths

• isosceles - 2 sides have equal lengths

• equilateral - all 3 sides are equal .

If you know the length of all 3 sides of a triangle, you can

calculate the area by using Heron's Formula (sometimes called

Hero's Formula) see the figure.

First we have to define a triangle's perimeter which is (side a +

side b + side c).

A triangle's semi-perimeter (or 's') is one half of the perimeter or

to put it another way:

Semi-perimeter = (side a + side b + side c) ÷ 2

Example: A triangle has side a = 4, side b = 5 and side c = 6. What is its area?

The perimeter = 4 + 5 + 6 = 15.

The semi-perimeter is one half of this or 7.5

Using Heron's formula,

area = square root (s • (s - 4) • (s - 5) • (s - 6))

area = square root (7.5 • (7.5 - 4) • (7.5 - 5) • (7.5 - 6))

area = square root (7.5 • (3.5) • (2.5) • (1.5))

area = square root (98.4375)

area = 9.921567416...

Pre-labs:

1. Review the definition of triangle.

2. Review the types of triangle.

3. Write down the equation for computing Triangle Area.

4. Write down the equation for computing Triangle perimeter.

5. Compute manually the area and the perimeter of triangle of sides: 0.5, 1.5 and 3.

Lab:

Step 1: Create the class Triangle using the following information:

public:

Triangle (double, double,double); //constructor

double Area(); // calculate the area of triangle

double perimeter (); // calculate the perimeter of triangle

Page 25: c++ lab manual

25

double get_Side1 ();//return the value of the first side of triangle

double get_Side2 ();//return the value of the second side of triangle

double get_Side3 ();//return the value of the third side of triangle

/*set values for the triangle sides values*/

void set_Sides(double, double,double);

string check_Type ();// decide the type of the triangle

void print ();// print all information about the triangle

private:

double Side1;

double Side2;

double Side3;

};

Step 2:. Write a program that constructs a Triangle object and calls all the members

functions.

Page 26: c++ lab manual

Class Students

Background:

The sample mean is the average

from the sample divided by the total number of events.

sample mean. In math terms,

Where n is the sample size a

34, 43, 81, 106, 106 and

We compute the sample mean by adding and dividing by the number of samples, 6.

34 + 43 + 81 + 106 + 106 + 115

6

Pre-labs:

6. Review the definition of mean.

7. Write down the equation for computing the mean of several numbers.

8. Compute manually the mean of the following values 3.4,12,16,22.5,9

Lab

1. Write a class implementation for a class Student with the following

StudentName of type string.

mark1, mark2, and mark3 all of them of type double.

And the following member functions

26

average and is computed as the sum of all the observed outcomes

from the sample divided by the total number of events. We use x as the symbol for the

In math terms,

and the x correspond to the observed valued.

and 115

We compute the sample mean by adding and dividing by the number of samples, 6.

34 + 43 + 81 + 106 + 106 + 115

= 80.83

Review the definition of mean.

the equation for computing the mean of several numbers.

Compute manually the mean of the following values 3.4,12,16,22.5,9

Write a class implementation for a class Student with the following data members

StudentName of type string.

mark1, mark2, and mark3 all of them of type double.

And the following member functions:

A default constructor to set :

StudentName to an empty string,

mark1, mark2, and mark3 all of them to 0 .

Paramerized costructor to set all data members.

print function to print the information of any Student object.

and is computed as the sum of all the observed outcomes

as the symbol for the

We compute the sample mean by adding and dividing by the number of samples, 6.

the equation for computing the mean of several numbers.

Compute manually the mean of the following values 3.4,12,16,22.5,9

data members:

mark1, mark2, and mark3 all of them of type double.

mark1, mark2, and mark3 all of them to 0 .

Paramerized costructor to set all data members.

print function to print the information of any Student object.

Page 27: c++ lab manual

27

• SET_DATA function to assign values to

StudentName,mark1,mark2,and mark3 .

• GET_DATA functions to return student name.

• RESULT function return "PASS" if the total of his marks more

than or equal to 50 otherwise return "FAIL" .

2. In the main function:

__ define an object of type Student called S1.

__ call SET_DATA function to set the values of StudentName,mark1,mark2,and mark3 to

"ahmed",22,21, and 40 respectively.

__ call GET_DATA functions to return data members.

__ call the print function.

__ call the RESULT function for object S1.

Page 28: c++ lab manual

28

Class Bank Account

Background:

To open a new account, the following information should be provided to the client:

- The customer name (first, Middle, Last).

- some personal information about the customer( such as : the Address, Gender, and

ID Number)

To deposit money to the account

- The deposit value is simply added to the account balance using the following

equation (Account_Balance=Account_Balance+Deposit_Amount).

To withdraw from an account

- The client checks the account balance to see if it is sufficient or not. If so, the

amount is deducted from the account as follows:

Account_Balance=Account_Balance-Withdraw_Amount

Other wise, the transaction is cancelled.

Pre-labs:

9. Review the bank transactions (Open account, deposit, and withdraw).

10. Write down the information needed to open an account.

11. Write down the equation needed to deposit to an account.

12. Write down the conditions and the equation needed to withdraw from an account.

Lab:

Step1: Write implementation for class bank_Account that contains the following

members:

Data members:

1. customer_Name of type string

2. cutomer_ID of type string.

3. account_Number of type string.

4. account_Balance of type double.

Member functions:

1. Empty constructor (default constructor) to initialize all data members to their

appropriate default values.

2. Parameterized constructor to initialize all data members to the given values.

3. get_Balance Function to return the account_Balance.

Page 29: c++ lab manual

29

4. deposit Function which receives the amount of money to be deposited and performs

the deposit transaction according to the equation you've learned.

5. withdraw Function which receives the amount of money to be withdrawn and checks

it against the account balance to decide whether to perform the transaction or not.

Step2: Write main function to do the following:

1. Create an object called Account1 using the default constructor.

2. Create an object called Account2 using the parameterized constructor with the

following information: "Amal Ahmad", "190-12-9876","1234567", 120.

3. Return the account_Balance of the customer Account2.

Step3: Enhance your class by adding a print member function to print all the information

about the customers.

Page 30: c++ lab manual

30

Lab 4 Separating class interface from its implementation and

data validation.

Lab Objectives:

- Learn how to engineer a class to separate its interface from its

implementation and encourage reuse.

- Learn how to validate data members in set functions, to ensure that data in

an object adheres to a particular format or is in proper value range.

Background:

Separating class interface from its implementation:

Interface of the class: - Specifies what services the class permits users to use and how to request

those services, but not specify how the services are implemented.

- Contains the prototype of the member functions and the declaration of the

data members.

- We place class interface in header file.

Define member functions outside the class definition, in a separate source-code file:

- In source-code file for a class

o Use binary scope resolution operator (::) to “tie” each member

function to the class definition

o Implementation details are hidden

o Client code does not need to know the implementation

Driver files (source file)

o Program used to test software (such as classes).

o Contains a main function so it can be executed.

#include preprocessor directive

- Used to include header files

- Instructs C++ preprocessor to replace directive with a copy of the contents

of the specified file

- Quotes indicate user-defined header files

- Angle brackets indicate C++ Standard Library

Validating Data with set Functions • set functions can validate data

– Known as validity checking

– Keeps object in a consistent state

• The data member contains a valid value

– Can return values indicating that attempts were made to assign invalid

data.

• string member functions

– length returns the number of characters in the string.

– substr returns specified substring within the string.

Pre- Lab: The student must know how to:

- Define a class and use it to create object.

Page 31: c++ lab manual

31

- Define member functions in a class to implement the class's behaviors.

- Declare data members in a class to implement class's attributes.

- Call a member function of an object to make that member function

performs its task.

- Use a constructor to ensure that an object's data is initialized when the

object is created.

Learning Outcomes: You will:

- Be able to write a full documented and separated interface C++ program

that deals with classes.

- Be able to validate data members in set functions, to ensure that data in an

object adheres to a particular format or is in proper value range.

Assessment tools: - Notes will be taken during the lab time.

- Quizzes.

Lab Exercises: Exercise #1:

Write a full documented and separated interface C++ program that implements

class Point that contains the data members x and y of type integers and the following

member functions:

1- Parameterized constructor that initializes x and y to any given values.

2- setX function to assign new value to x between 10 and 50.

3- setY function to assign new value to y, the value must be greater than or equal

to 0.

4- getX to return the value of x.

5- print to print any point as ordered pair.

Write a main function declare object p1 with the values 12 and 30 to x and y

respectively, and test the member functions.

The solution:

To create a full documented and separated interface C++ program that implements

class Point:

1- Create new project of type Win32Console Application of any name.

2- then add a header file name e.g. point.h to write the class interface as

follows: //file name: point.h

class Point

{

private:

int x,y;

public:

Point(int, int);

void setX(int);

void setY(int);

int getX();

void print();

};

Page 32: c++ lab manual

32

3- then add a source file e.g. implementation.cpp to write the implementation for

each member function as follows:

//file name: implementation.cpp

#include <iostream>

using namespace std;

#include "point.h"

Point::Point(int a, int b)

{

setX(a);

setY(b);

}

void Point::setX(int a)

{

x = (a>= 10 && a<= 50)? a : 10;

}

void Point::setY(int b)

{

if(b>= 0)

y = b;

else y = 0;

}

int Point::getX()

{

return x;

}

void Point::print()

{

cout<<"("<<x<<","<<y<<")"<<endl;

}

4- then add a source file named e.g. driver.cpp to write the main function and test

class operations as follows:

//file name: driver.cpp

#include<iostream>

using namespace std;

#include "point.h"

void main()

{

Point p1(12,30);

p1.print();

p1.setX(8);

p1.setY(3);

p1.print();

Page 33: c++ lab manual

33

cout<<p1.getX()<<endl;

}

Exercise #2: Write a full documented and separated interface C++ program that implements class

Student that contains the following data members:

- name of type string.

- ID of type integer.

- grade of type double.

And the following member functions:

- default constructor to initialize name to ali, ID to 2012066034, and grade

to 65.7.

- setName to assign new value to the data member name but ensure that the

name has at most 20 characters.

- setGrade to assign new value to the grade but ensure that the grade be

greater than or equal to 60.

- Print to print the student information.

Write a main function, declare object s1 of type Student and use the s1 to test all

operations of class Student.

The solution:

To create a full documented and separated interface C++ program that implements

class Student:

1- Create new project of type Win32Console Application of any name.

2- then add a header file name e.g. student.h to write the class interface as

follows:

//file name: student.h

#include<string>

using namespace std;

class Student

{

private:

string name;

int ID;

double grade;

public:

Student();

void setName(string);

void setGrade(double);

void print();

};

3- then add a source file e.g. implementation.cpp to write the implementation

for each member function as follows:

//file name: implementation.cpp

#include <iostream>

using namespace std;

Page 34: c++ lab manual

34

#include "student.h"

Student::Student()

{

setName("ali");

ID = 2012066034;

setGrade(65.7);

}

void Student::setName(string n)

{

if(n.length()<= 20)

name = n;

else

name = n.substr(0,20);

}

void Student::setGrade(double gr)

{

grade= gr >= 60 ? gr: 60;

}

void Student::print()

{

cout<<name<<" "<<ID<<" "<<grade<<endl;

}

4- then add a source file named e.g. driver.cpp to write the main function and

test class operations as follows:

//file name: driver.cpp #include<iostream>

using namespace std;

#include "student.h"

void main()

{

Student s1;

s1.print();

s1.setName("Ahmad Mohammed");

s1.setGrade(2010902023);

s1.print();

}

Lab Assignment: Assignment #1: Write a full documented and separated interface C++ program that

implements class Calculator that contains the data member x and y of type integer and the

following member functions

1) Add to return the result of summing x and y

2) Sub to return the result of subtracting y from x

Page 35: c++ lab manual

35

3) Mul to return the result of multiplying x by y

4) Div to return the result of dividing x by y

5) Mod to return the result of x % y

6) Constructors to initialize object data members x and

Write the main function and define an object of type Calculator to test all the member

functions.

Assignment #2: Write a full documented and separated interface C++ program that

implements class Book that contains the following:

1) One data member that contains book title.

2) One data member that contains book author

3) One data member that contains book publisher.

4) One data member that contains book ISBN

5) Member function to set all data member values

6) Get functions to retrieve ISBN and author name value for a given book.

7) Member function to print a summary of information for a given book.

Define a main function with objects of type Book to test the class operations.

Assignment # 3:

Write a full documented and separated interface C++ program that implements class

Account that a bank might use to represent customers' bank accounts.

- Your class should include one data member of type double to represent the account

balance.

- Your class should provide a constructor that receives an initial balance and uses it to

initialize the data member. The constructor should validate the initial balance to

ensure that it is greater than or equal to 0. If not, the balance should be set to 0 and the

constructor should display an error message, indicating that the initial balance was

invalid.

The class should provide three member functions:

- Function credit should add an amount to the current balance.

- Member function debit should withdraw money from the account and should

ensure that the debit amount does not exceed the account's balance. If it does,

the balance should be left unchanged and the function should print a message

indicating "Debit amount exceeded account balance."

- Member function getBalance should return the current balance.

Create a program that creates two Account objects and test the member functions of

class Account.

Page 36: c++ lab manual

36

Lab 5 More about selection structures( if and switch

statements).

Lab Objectives:

• Teach the student, how to use if/else selection statements, and use it to write and

execute a simple program.

• Teach student the structure of the switch statement.

• How to convert between if/else and switch statement.

Background:

• Decision Making: Equality and Relational Operators:

• If/else Statement:

o Condition

� Expression can be either true or false

� Can be formed using equality or relational operators

o if statement

� If the condition is true, the body of the if statement executes

� If the condition is false, the body of the else statement executes

If ( Condition )

Page 37: c++ lab manual

37

{

Statement(s);

}

Else

{

Statement(s);

}

Figure1: The structure of the if/else statement

• Switch Statement:

o Value

� Integer value or variable or expression

� Char value or variable

� Bool value or variable

o Case statement

� If the value in the switch statement is equal to the value in one of

the case statemets, the body of the case statement executes

� If the value in the switch statement doesn’t match any value of the

case statements , the body of the default statement executes

Switch ( integer variable, value, or expression)

{

1-Executes when the condition is true.

1

2

1

Page 38: c++ lab manual

38

Case value1 :

Statement(s);

Break;

Case value2 :

Statement(s);

Break;

Case value3 :

Statement(s);

Break;

.

.

.

Default :

Statement(s);

Break;

}

2

3

4

1- Integer variable, value or expression

(including char and bool data types).

2- Swich statement body.

3- Case statement parts.

4- Default statement.

Page 39: c++ lab manual

39

Figure2: The structure of the switch statement.

Pre-lab:

The student should know the structure of a simple if statement:

If ( Condition )

{

Statement(s);

Page 40: c++ lab manual

40

}

Figure3: The structure of the if statement

The student should know the Parts of simple if Statement.

Assessment tools:

The assessment is according to the student participation in the lab if the student solves the

exercise, he will get the participation mark for this lab.

Lab Assignments:

• Lab assignment-1 Write a program to read character then find if it is capital or small.

#include<iostream>

using namespace std;

void main()

{

Page 41: c++ lab manual

41

char letter;

cin>>letter;

if(letter >='A' && letter <='Z')

cout<<"Capital Case"<<endl;

else if(letter >='a' && letter <='z')

cout<<"Small Case"<<endl;

else

cout<<"Incorrect Caharcter..."<<endl;

}

• Lab assignment-2

Implement the calculator using if/else statement. The program should ask the user to

input two operands and an operation, your program should print the result of

performing the required operation on the input operands as the following output

suggests:

Enter operand 1: 5

Enter operand 2: 10

Enter operation: /

The result of 5/10 is 0.5

#include<iostream>

using namespace std;

void main()

{

int a;

cout<<"Enter operand 1: ";

cin>>a;

int b;

cout<<"Enter operand 2: ";

cin>>b;

char op;

cout<<"Enter operation:";

cin>>op;

Page 42: c++ lab manual

42

if(op== '+')

cout<<"The result of "<<a<<op<<b<<" is

"<<a+b<<endl;

else if(op == '-')

cout<<"The result of "<<a<<op<<b<<" is "<<a-

b<<endl;

else if(op == '*')

cout<<"The result of "<<a<<op<<b<<" is

"<<a*b<<endl;

else if(op == '/')

cout<<"The result of "<<a<<op<<b<<" is

"<<static_cast<float>(a)/b<<endl;

else

cout<<"Incorrect operation was

entered..."<<endl;

}

• Lab assignment-2

Implement the calculator using switch statement. The program should ask the user to

input two operands and an operation, your program should print the result of

performing the required operation on the input operands as the following output

suggests:

Enter operand 1: 5

Enter operand 2: 10

Enter operation: /

The result of 5/10 is 0.5

#include<iostream>

using namespace std;

void main()

{

Page 43: c++ lab manual

43

int a;

cout<<"Enter operand 1: ";

cin>>a;

int b;

cout<<"Enter operand 2: ";

cin>>b;

char op;

cout<<"Enter operation:";

cin>>op;

switch(op)

{

case '+':

cout<<"The result of "<<a<<op<<b<<" is "<<a+b<<endl;

case '-':

cout<<"The result of "<<a<<op<<b<<" is "<<a-b<<endl;

case '*':

cout<<"The result of "<<a<<op<<b<<" is "<<a*b<<endl;

case '/':

cout<<"The result of "<<a<<op<<b<<" is

"<<static_cast<float>(a)/b<<endl;

default:

cout<<"Incorrect operation was entered..."<<endl;

}

Page 44: c++ lab manual

44

}

Lab Problems:

• Lab Problem-1:

Write a program to read four integer numbers then find and print the second maximum

one among these numbers.

• Lab Problem -2

The following program has a nested if structure, however some of its cout statements

are missing reporting words in the blanks (……). Fill the missing blanks with what you

think logically sound as in the bold cout, and then run the program to check its output.

#include<iostream>

using namespace std;

void main()

{

int num;

cout<<"Enter a number: ";

cin>>num;

if(num%2!=0)

if(num>10)

if(num<20)

cout<<"your numbers is ODD, >10 and

<20\n";

else

cout<<"your number is ..... and ....";

else

cout<<"your number is .... and ...";

Page 45: c++ lab manual

45

else if(num<0)

cout<<"your number is ... and ...";

else

cout<<"your is .... and ....";

}

• Lab Problem -3

Write a program that reads three nonzero integers and determines and prints whether

they’re the sides of a right triangle.

Page 46: c++ lab manual

46

Lab 6 Control Structures: while , do-while and for Loop

Lab Objectives:

After performing this lab, the students should be able to

• explain the basics of while and for loops and while loops

• apply the syntaxes of loop structures

• design programs using loop structures

• solve (hard) problems of repetitive nature using loop structures

Background: Loop structures called for loops and while loops are covered as some basic control

structures. The loop can be used to do repetitive calculations. Though human beings

can do calculation or processing or repetitive nature by hand, it is much slower and

tedious for the human being. Good and solid logic of loop structures can be used to

solve such problems in a very efficient way.

For example, in order to compute the sum of 1 + 2 + 3 + … + 100, we can do easily

using the following code:

int sum = 0;

for (int j = 1; j <= 100; j++)

sum += j;

There are two control structures used often: the for loop and the while loop (and do

while as a different way of while).

The syntaxes of these two loop structures are as follows:

for (initialize loop variables; loop terminator;

loop variable update)

{

Statements in the block or one statement

}

Not all three components of the for loop are necessary, in fact for ( ; ; ) is a valid

statement. The loop variable update can be increments of loop variable(s) or

decrements; there can be more than one loop variable in the same for loop separated

by comma (,) and there can also be nested for loops of for loop inside for loop etc.

When there is only one statement in the block, the enclosing braces{} can be omitted.

The following are a few valid for loop statements

The loop structure can be used to do the following problems encountered often in the

first programming course (usually considered challenging for the students new to

programming):

Page 47: c++ lab manual

47

1. Reverse an integer

2. Compute the prime number

3. Compute a function such as exp (x) (exponential function).

Pre-labs:

1. Study Deitel’s book (how to program C++) control structures.

2. Explain which of the following for loops are valid and which are invalid and why.

3. Convert the following for loop to while loop.

4. Convert the following while loop to for loop.

5. Analyze the following for loops in the table and state whether

a. They compile

b. They run

c. They print out a line

d. They print out more than one line Answer yes or no to each.

• for (j = 1; j <= 10; j++); for (j = 1; j <= 10; j++); for (j = 1; j <= 10; j++); for (j = 1; j <= 10; j++); • for (j = 1; j < 11; ++j); for (j = 1; j < 11; ++j); for (j = 1; j < 11; ++j); for (j = 1; j < 11; ++j); • for (j = 1; j <= 10; j++) for (j = 1; j <= 10; j++) for (j = 1; j <= 10; j++) for (j = 1; j <= 10; j++)

cout<<“Hellocout<<“Hellocout<<“Hellocout<<“Hello\\\\n”; n”; n”; n”; • for (j = 1; j <= 10; j++); for (j = 1; j <= 10; j++); for (j = 1; j <= 10; j++); for (j = 1; j <= 10; j++);

cout<<“Hellocout<<“Hellocout<<“Hellocout<<“Hello\\\\n”; n”; n”; n”; • for (j = 1, j <= 10, j++) for (j = 1, j <= 10, j++) for (j = 1, j <= 10, j++) for (j = 1, j <= 10, j++)

cout<<“Hellocout<<“Hellocout<<“Hellocout<<“Hello\\\\n”; n”; n”; n”;

Assessment tools:

The assessment is according to the student participation in the lab if the student solves the

exercise, he will get the participation mark for this lab.

Lab Assignments:

• Lab assignment-1:

Reverse an integer:

Problem statement: Given an integer n such as 1367. Write a program that computes

the inverse of this integer as 7631.

#include<iostream>

using namespace std;

void main()

{

int x;

cin>>x;

while (x != 0)

{

int r = x % 10; // Get the last digit of x

x = x / 10; // divide x by 10 through integer

Page 48: c++ lab manual

48

cout << r<<" ";

} }

When running this code with x = 1367 for example, we calculate r = 7 and x = 136

and display 7; then calculate r = 6 and x = 13 and then display 6; then calculate 3 and

display 3 and then calculate and display 1.

• Lab assignment-2:

Compute prime number

A prime number p > 1 is a positive integer which has 1 and itself as the only factors.

Prime numbers have special properties that are different from non -prime (also called

composite) numbers > 1. For example 4 is dividing by 2 so 4 is not a prime number.

The lists of prime numbers from 2 to 30 are: 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. To

determine if an integer n > 1 is a prime number, theoretically we need to verify that

for i = 2, 3, 4, 5, .., up to n-1, none of them divides n.

#include<iostream>

using namespace std;

void main()

{

int x;

cin>>x;

bool isPrime=true;

int i=2;

while(i<x-1)

{

if(x%i==0)

{

isPrime=false;

break;

}

i++;

}

if(isPrime)

cout<<"number is prime"<<endl;

else

cout<<"number is not prime"<<endl;

}

• Lab assignment-3:

Compute power:

To calculate X y (x to the power y) where both x, y are integers we must repeat multiply x by

it self y times. For example, if x=3, y=4 so you must compute 3*3*3*3.

Page 49: c++ lab manual

49

#include<iostream>

using namespace std;

void main()

{

int x,y;//x is base , y is power

cin>>x>>y;

int result=1;

for(int i=1;i<=y;i++)

result*=x;

cout<<x<<" to the power

"<<y<<"="<<result<<endl;

}

Lab Problems:

• Lab Problem-1

Write a C++ program to find the summation of the following series (using for statement)

S=1+ 4 + 9+ 16+………+(n*n).

• Lab Problem-2 Write a C++ program to print all numbers (that are multiple of 3) from 1 to 100 every 6

numbers on a line.

• Lab Problem-3 Write a C++ program to find the summation of even digits for any read number from the

keyboard (the number could be of any length).

Page 50: c++ lab manual

50

Lab 7 Using Functions

Functions.

Lab Objectives:

After completing this lab, the students should be able to

• Explain the concepts of functions.

• use common math functions available in the C++ Standard Library.

• Explain what a function prototype is and how that is different from the

function definition.

• Convert the code processing in the main function to a function called

from the main function.

• Create functions with multiple parameters.

• The mechanisms for passing information between functions and

returning results.

Background: The function is a good mechanism to encapsulate code used repeatedly in a

program so that it can be called from other parts of the code. A function does not use

a keyword called function but instead the programmer has to define function

prototype before the main function and then define the function again later.

A function has the following format:

type function_name (optional parameter list)

{

function code;

return value;

}

Return data type of function is in general the types of C++ variable types including

int, double, char etc.

The function does some processing and the calculated value is returned using the

return value.

In the main function or the other functions calling this function_name, the value

returned is used like the instruction: calling_value = function_name (parameters);

A function does not need to always return a value. A function not returning a value

can omit the return statement and the function type is void in this case.

Function prototype has the following format:

type function_name (list of variable types);

Examples are:

Example 1:

int compute_sum (int);

Page 51: c++ lab manual

51

Example 2:

void tryout ();

Function prototypes differ from the function definitions in two places: there is no

code (no {} with code in between) and the variable names do not follow the types.

A function prototype can return nothing, in which case void is the type returned; also

it may have no parameters at all like example 2 above.

The function prototype is declared before the main function with the function calls

inside the main function or the other functions calling this function.

The function definitions are put after the main function.

C++ Standard Library : is a collection of functions, which are written in the core

language and part of the C++ ISO Standard itself to provides several generic functions

that utilize and manipulate these containers, function objects, generic strings and

streams (including interactive and file I/O), support for some language features, and

everyday functions for tasks such as finding the square root of a number. Using sqrt

in <cmath> header file.

Example 3:

Pre-labs:

In order to do this lab, you should know how to write, compile, and run a C++ program, and

you should understand what functions are and how to invoke them. You should also be

familiar with an editor

Assessment tools:

The assessment is according to the student participation in the lab if the student solves the

exercise, he will get the participation mark for this lab.

Page 52: c++ lab manual

52

Lab Assignments:

• Lab assignment-1

Consider the following code that computes the sum of 1 + 2 + 3 + .. + 100 by a for

loop.

#include <iostream>

using namespace std;

int main ( ) {

int sum = 0;

for (int j = 1; j <= 100; j++)

sum += j;

cout << “The sum of 1 + 2 + 3 + .. + 100 is “ << sum <<

endl;

return 0;

}

This program shows how to compute a sum in a quick way. The program can be

easily modified to compute and display the sum of 1 + 2 + .. + n for a variable n (with

n = 100 as above).

Such code of (3 lines) computing the sum can be coded as one instruction in the main

function compute_sum (n) with the variable n as the parameter.

The function prototype is declared before the main function with the function calls

inside the main function or the other functions calling this function. The function

definitions are put after the main functionas follow:

int compute_sum (int x)

{ int sum = 0;

for (int j = 1; j <= x; j++)

sum += j;

return x;

}

Page 53: c++ lab manual

53

• Lab assignment-2:

Write a program to read three integers in the main and then send them to the function Max

which will return the maximum number of the them .

• Lab assignment-3: Write a recursive function that receives an integer consisting of any number of digits.

Your function should calculate and return the summation of the integer digits.

Lab Problems:

• Lab Problem-1

Write a function called Sum_even which takes as input two integers N and M entered by the

user from keyboard , and returns to the main function the summation of even numbers from

N to M. (note: N and M included if were even numbers) .

Page 54: c++ lab manual

54

• Lab Problem-2

Write a function called Is_Capital that has one parameter and receives a character and

returns true if the character received is a capital letter, and false otherwise. Then write a

main function that calls the Is_Capital function to test its correctness.(you may solve it

without using if-else statement).

• Lab Problem-3

Write a C++ function to receive an integer of 3 digits then calculates and returns the sum of

the MSD and the LSD. For example if your function received 345 it should return 8.

Page 55: c++ lab manual

55

Lab 8 Random numbers, scope rules, and default Arguments

Lab Objectives:

After performing this lab, the students should be able to:

• Solve problems that needs to generate random numbers

• Realize where an identifier can be referenced in a program and why

• Use default arguments when needed in a function

Background:

• Rand() is a function generates an unsigned integer between 0 and

RAND_MAX (a symbolic constant defined in header file <cstdlib>)

If we want a random number in the range [a, b] we can use the formula

a + rand() % (b – a + 1)

• Cube_volume = side_length * side_length * side_length

• If the cylinder has a radius r and length (height) h, then its volume is

given by

V = πr2h , π = 3.14

Pre-lab:

The student must know how to

• Write functions and call them

• Trace and try to find output

• Include the necessary header files if needed

Assessment tools:

• Notes will be taken during the lab time

• Quizzes

Lab Assignments:

Page 56: c++ lab manual

56

• Lab assignment-1

Write a void function with empty parameter list to print out 100

random numbers in the range 7 to 51 every 10 in a line. Then call

it from the main function.

#include <iostream>

#include <cstdlib>

using namespace std;

void printRandomly()

{

for(int i = 1; i<=100; i++)

{

cout<<7 + rand() % (51 -7 +1)<<"\t";

if( i % 10 == 0)

cout<<endl;

}

}

void main()

{

printRandomly();

}

• Lab assignment-2

Study the following code, discuss the scope rules and try it to see

and understand the results.

void main()

Page 57: c++ lab manual

57

{ // First Block

int var1 = 5;

int var2 = 8;

int var3 = 4;

{ // Second Block

int var1 = 6;

int var2 = 9;

{ // Third Block

int var1 = 7;

cout << "variable1 = " << var1 << "\n";

cout << " variable2 = " << var2 << "\n";

cout << " variable3 = " << var3 << "\n";

}

cout << " variable1 = " << var1 << "\n";

cout << " variable2 = " << var2 << "\n";

cout << " variable3 = " << var3 << "\n";

}

}

• Lab assignment-3

Page 58: c++ lab manual

58

Write a C++ function with a default value 1 to calculate and return

the volume of a cube then call your function from the main twice

once with a parameter and the other with no parameter value.

#include <iostream>

using namespace std;

double CubeVolume(double L =1.0);

void main()

{

cout<<CubeVolume()<<endl;

cout<<CubeVolume(5)<<endl;

}

double CubeVolume(double L )

{

return L*L*L;

}

Lab Problems:

• Lab Problem-1

Modify the implementation of the function in Lab assignment-1

to make it work for any given range (sent from the main).

• Lab Problem -2

Write a c++ program with the following specification

1. A global int variable num without a value

2. A function F1 that prints the value of global num and

then assigns the value 5 to it.

3. A function F2 that has a float parameter called num, the

function will return the square root of the variable num

to the main when call it.

Page 59: c++ lab manual

59

4. A main function that call F1 and F2 functions , then

define its local int num variable

5. Add the following statements in the main function

::num = ::num + 2* num;

cout<<"global num = "<<::num<<endl;

cout<<"local num = "<<num<<endl;

• Lab Problem -3

Write a C++ function with default values, 1 for the radius of the

base for a cylinder and 2 for height to calculate and return the

volume of a cylinder, and then call your function from the main

with and without arguments.

Hint: If the cylinder has a radius r and length (height) h, then its volume is given by

V = πr2h , π = 3.14

Page 60: c++ lab manual

60

Lab 9 Function Overloading and recursion

Lab Objectives:

After performing this lab, the students should be able to:

• Understand the idea of Overloading Functions and be able to write an

overloaded function.

• The student should be prepared to understand the idea of operator

overloading in general

• Understand the idea of recursion and compare it to the iterative paradigm

• Trace a recursive function

• The student should know how to write a recursive function

• Should be able to convert any program written using loops into a recursive

one

Background:

• Function signature is both the name and parameter list of that function

• To overload a function is to write at least two functions at the same

scope(workspace)with different signatures[i.e. the same name but with

different parameter list (make the parameters in every list differ in types

,number, or appearance) ]

• A recursive function is a function that calls itself.

Pre-lab:

The student must know how to

• Write functions and call them

• Trace and try to find output

Assessment tools:

Page 61: c++ lab manual

61

• Examples will be taken during the lab time

• Quizzes

Lab Assignments:

• Lab assignment-1

Write an overloaded function to calculate and return the area of a

square, a circle ,a rectangle. Then call it from the main function.

#include <iostream>

using namespace std;

double area(int r)

{ return r*r*3.14;}

double area(float s)

{

return s*s;

}

double area(int l,int w)

{

return l*w;

}

void main()

{

cout<<area(3);

cout<<area(3,4);

cout<<area(3.0);

}

• Lab assignment-2

Write a recursive function to calculate and return the factorial of any positive integer

number.

int factorial(int r)

{

if (r<=1)

return 1;

Page 62: c++ lab manual

62

else return factorial (r-1)*r;}

void main()

{

cout<<factorial(5);

}

• Lab assignment-3

Write a recursive C++ function to calculate and return the sum of

the following series then call your function from the main .

Sum=1+2+3+….+N

#include <iostream>

using namespace std;

int Sum(int n)

{ if (n==1)

retrun 1;

else

return n+Sum(n-1);}

void main()

{ cout<<Sum(5);}

• Lab assignment-4

#include <iostream>

using namespace std;

double Volume(double );

double Volume(double, double, double );

void main()

Page 63: c++ lab manual

63

{

cout<<Volume(5)<<endl;

cout<<Volume(5,5,7)<<endl;

}

double Volume(double L )

{// the volume of a Cube

return L*L*L;

}

double Volume(double L , double w, double h)

{// the volume of a Box

return L*w*h;

}

• Lab assignment-5

Write a recursive function to calculate and return the power of any2 positive integer

numbers.

int power(int base,int pwr)

{

if (pwr==0)

return 1;

else return power (base,pwr-1)*base;}

void main()

{

cout<<power(2,5);

}

Page 64: c++ lab manual

64

Lab Problems:

• Lab Problem-1

Modify the implementation of the program in Lab assignment-4

to make it calculate the volume of a sphere given its integer radius

(sent from the main).

• Lab Problem -2

Write a recursive C++ function to calculate and return:

Sum=1!+2!+3!+…+n!

then call your function from the main.

• Lab Problem -3

Write a C++recursive function to check out if any given integer is

prime or not.

• Lab Problem -4

Write a C++recursive function to calculate.

X*Y (the multiplication of X by Y where X,Y are integers)

Page 65: c++ lab manual

65

Lab 10 Arrays

Lab Objectives:

Learn how to use the array data structure to represent a set of related data

items.

Learn how to declare arrays, initialize arrays and refer to the individual

elements of arrays.

Learn how to pass arrays to functions.

Learn how to declare and manipulate Two-dimensional arrays.

Background:

Definition

Array: A collection of individual values, all of the same data type, stored in

adjacent memory locations.

One Dimensional Array: An array with a single variable index.

Using the array name together with an integral valued index in square

brackets refers to the individual values. The first array element always has

the subscript 0. The second array element has the subscript 1, etc.

The base address of an array is its beginning address in memory.

Declaring an Array:

Use the following syntax below.

DataType ArrayName [ConstIntExpression];

The example below shows the declaration of an integer array of size 10

with element 0 - 9.

const int MAXSIZE = 10; int array[MAXSIZE];

Arrays can be initialized during declaration by equating the array to a listing

of the array's members in brackets. For example

int array[MAXSIZE] = {2 , 4, 6, 8, 10, 12, 14,

16, 18, 20};

Passing Arrays as Function Parameters

In C++, arrays are always passed by reference by default. Whenever an

array is passed as a parameter, its base address is sent to the called function.

Generally, functions that work with arrays require 2 items of information as

actual parameters: the beginning address of the array (in memory), and the

number of elements to process in the array.

For example (Function PrintArray):

Page 66: c++ lab manual

66

void PrintArray(int Array[], int ArraySize) { for (int i = 0; i <= ArraySize - 1; i++) cout << "array[" << i << "] = "<<

Array[i] << endl; }

Declare and manipulate Two-dimensional arrays

Two-dimensional arrays store a tabular arrangement of values accessed by

two indexes, for example matrix[i][j], where i is the row index and j is the

column index.

To declare and initialize a two-dimensional arrays, Use the following

syntax below.

DataType ArrayName [row][column];

The example below shows the declaring two-dimensional array b

int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };

Assessment tools:

Lab exercises. Quizzes.

Page 67: c++ lab manual

67

Lab Assignments:

Lab assignment-1: Fill in the blanks

Complete the following program below by filling in the blanks. (Read

comments for assistance. )

// bubble.cpp #include <iostream> using namespace std;

void bubbleSort(int array[], int size); // bubble sort void swap(int &x, int &y); // helper function of bubbleSort void printArray(int array[], int size); // print array

int main() { const int MAX = 10;

/* Declare an array called value of size MAX with elements: 20, 15, 18, 19, 22, 11, 9, 7, 10, 3*/

cout << "Print array before sort: " << endl; // Place print array function call here.

// Place bubble sort function call here.

cout << "Print array after sort: " << endl; // Place print array function call here.

return 0; } void bubbleSort(int array[], int size) { for (int pass = 1; pass <= size - 1; pass++) for (int i = 0; i <= size - 2 ; i++) if (array[i] > array[i + 1]) swap(array[i], array[i + 1]); }

void swap (int &x, int &y) { int temp; temp = x; x = y; y = temp; }

void printArray(const int array[], int size) { for (int i = 0; i <= size - 1; i++) cout << array[i] << endl; cout << endl;}

Page 68: c++ lab manual

68

Lab assignment-2: Storing quiz scores

Write a program that allows a user to enter 6 quiz scores to calculate and print

the average for these quizzes.

#include <iostream> using namespace std;

int main() { int scores[6]; int total = 0;

cout << "Enter 6 scores to compute the average.\n";

for(int i = 0; i <6; i++){ cout << "Enter score[" << i << "]: "; cin >> scores[i]; cout << endl; }

for (i = 0; i <6; i++) total += scores[i];

cout << "The average was: " << total / .0 << endl; return 0; }

Lab assignment-3: store values in 2D arrays

Write a program that reads in random values from 1-100 for 2D array and

simply display, as output, the value of each cell.

#include <iostream> using namespace std; int main() { int myarr[2][3];

for(int r = 0; r < 2; r++){ for(int c = 0; c < 3; c++){ myarr[r][c] =1+rand()%100; } } for(r = 0; r < 2; r++){ for(int c = 0; c < 3; c++){ cout<<"myarr [" << r <<

]["<<c<<"]:"<<myarr[r][c]<<endl; } } return 0; }

Lab Problems:

Lab Problem-1: using array to CountDigit

Write a function CountDigit which receives two arguments: a char array and

the size of the array (of type int). This function counts the number of digit

letters in the char array, and returns the count (of type int).

Page 69: c++ lab manual

69

Lab Problem -2: search array for a key value

Write a function that searches an array for a "key value" and returns the array's

index for that element. If the element is not found, then the function should

return -1. Write a driver program that correctly tests this function. The driver

should print the array and show the value of the search result.

Lab Problem -3: Minimum array entry

With a function that take as parameters a 2D array and the capacity of the

array.your function has to find the minimum entry in a 2D array .write a driver

program that reads array values and finds the minimum entry using your

function.

Page 70: c++ lab manual

70

Lab 11 Using Pointers

Lab Objectives:

In this lab students will learn:

1. Memory concept of variables, pointers and how to use variable identifiers and

pointers to refer to the variable.

2. Pointer variable declarations and initialization.

3. Direct and indirect referencing a variable using the pointer operators.

4. Using * and address (&) operators.

Background:

When declaring a variable, it is located at a specific location in memory, the memory

address. The task of locating variables is automatically performed by the operating

system during runtime. In some cases we need to know the address where the variable

is being stored during runtime.

Variable which stores a reference to another variable is called a pointer. We can

directly access the value stored in the variable using a pointer which points to it.

Syntax:

1. Pointer Declaration:

Syntax: Pointer_type *Pointer_name;

Example: int *Ptr1; double *Ptr2;

2. Pointer initialization:

Syntax: Pointer_name=NULL;

Pointer_name=&variable_name;

Example: int *Ptr1, var;

Ptr1=&var;

Assessment tools:

Ptr

Address

Memory Locations

Page 71: c++ lab manual

71

1. Evaluation for lab exercises.

2. Quizzes.

Lab Assignments:

• Lab assignment-1:

Write a c++ program that defines an integer variable var1 and a pointer Ptr that

points to var1. Assign and print value to var1, then assign and print a new value to

var1 using Ptr.

Solution:

#include<iostream>

using namespace std;

void main()

{

int var1,*ptr;

ptr=&var1;

var1=10;

cout<<var1;

cout<<endl;

*ptr=20;

cout<<*ptr;

}

• Lab assignment-2: What will be the output of the following code?

#include<iostream>

using namespace std;

void main()

{

int nNumber;

int *pPointer;

nNumber = 15;

pPointer = &nNumber;

cout<<"nNumber: "<<nNumber

<<"\npPointer: "<<pPointer

<<"\n*pPointer: "<<*pPointer

<<"\n&nNumber: "<<&nNumber

<<"\n&pPointer: "<<&pPointer

<<"\n&*&*pPointer: "<<&*&*pPointer

<<"\n*&*&*pPointer: "<<*&*&*pPointer<<endl;

Page 72: c++ lab manual

72

}

Solution:

Lab Problems:

• Lab Problem-1: Correct the errors in the following program.

• Lab Problem -2: Write a c++ program that use pointers to swap two

integer values.

#include<iostream>

using namespace std;

void main()

{ int n,*ptr=&n;

cin>>n>>ptr;

*ptr=n-2;

if (*ptr>=0) *n++;

else

cout<<*ptr <<" IS NEGATIVE\n";

if (&n==ptr)

cout<<"CORRECT POINTER";

else

ptr=&n;

}

Page 73: c++ lab manual

73

Lab 12 Using files.

Lab Objectives:

• Teach the students the File I/O class fstream in C++ which is used for File Read/Write

operations

• Teach the students how to use file operations, use it to write and execute a simple

program.

• Teach the students how to create a file using simple program.

• Teach the students how to write in a file using simple program

• Teach the students how to read from a file using simple program

• Teach the students how to implement all previous application using file stream

Background:

Pre-lab:

Study / review how to use c++ statement in order to implement it by file process in C++.

Assessment tools:

The assessment is according to the student participation in the lab if the student solves the

exercise, he will get the participation mark for this lab.

Lab Assignments:

• Lab assignment-1

Create an empty text file using c++ program and set its location

#include<fstream.h>

int main()

{

fstream file_op("c:\\test_file.txt",ios::in);

file_op.close() ;

return 0;

}

• Lab assignment-2 Assign value to an empty text file using c++ program

#include<fstream.h>

int main()

Page 74: c++ lab manual

74

{

ofstream file_op("c:\\test_file.txt",ios::in);

int x=5;

file_op <<x;

file_op.close ();

return 0;

}

• Lab assignment-3

Read value from empty text file using c++ program

#include<fstream.h>

int main()

{

fstream file_op("c:\\test_file.txt",ios::in);

int x;

file_op >>x;

cout<<x;

file_op.close ();

return 0;

}

Lab Problems:

• Lab Problem-1:

Write a program to find the maximum digit throw any integer number and print the

value in text file

• Lab Problem -2

Write a program to read four integer numbers from file, then find and print the second

maximum one among these numbers.