Download as pdf or txt
Download as pdf or txt
You are on page 1of 156

Department of Electrical Engineering

Faculty of Engineering & Applied Sciences


Riphah International University, Islamabad,
Pakistan

Lab Manual
CSL-112 Object Oriented Programming Lab

Name: Huzaifa Bin Javaid


Roll Number: 20B36EE CMS: 23760
Semester: 2nd Group: B
Contents

I. Laboratory Safety Policies....................................................................................................... 3


1. General laboratory safety ..................................................................................................... 3
2. Clothing: .............................................................................................................................. 3
3. Disposal................................................................................................................................ 3
4. Equipment Failure ................................................................................................................ 3
5. Electrical safety.................................................................................................................... 4
6. Fire. ...................................................................................................................................... 4
7. Chemicals Spills................................................................................................................... 5
8. In Case of emergency........................................................................................................... 5
II. Safety Undertaking .................................................................................................................. 6
III. Grading Policy ..................................................................................................................... 7
Rubrics .......................................................................................Error! Bookmark not defined.
IV. Level of Inquiry ................................................................................................................... 7
V. Laboratory’s Course Learning Outcomes...............................Error! Bookmark not defined.
VI. List of Experiments ............................................................................................................ 15
I. Laboratory Safety Policies

1. General laboratory safety


 Never eat or drink while working in the laboratory.
 Read labels carefully.
 Do not use any equipment unless you are trained and approved as a user by your
supervisor.
 Wear safety glasses or face shields when working with hazardous materials and/or
equipment.
 Wear gloves when using any hazardous or toxic agent.
 Never do unauthorized experiments.
 Never work alone in laboratory.
 Keep your lab space clean and organized.
 Do not leave an on-going experiment unattended.
 Never taste anything. Never pipette by mouth; use a bulb.
 Never use open flames in laboratory unless instructed by TA.
 Check your glassware for cracks and chips each time you use it. Cracks could cause the
glassware to fail during use and cause serious injury to you or lab mates.

2. Clothing:
 When handling dangerous substances, wear gloves, laboratory coats, and safety shield or
glasses. Shorts and sandals should not be worn in the lab at any time. Shoes are required
when working in the machine shops.
 If you have long hair or loose clothes, make sure it is tied back or confined.
 Keep the work area clear of all materials except those needed for your work.

3. Disposal
 Students are responsible for the proper disposal of used material if any in appropriate
containers.

4. Equipment Failure
 If a piece of equipment fails while being used, report it immediately to Lab
Engineer/Assistant. Never try to fix the problem yourself because you could harm
yourself and others.
 If leaving a lab unattended, turn off all ignition sources and lock the doors.
 Clean up your work area before leaving.
 Wash hands before leaving the lab and before eating.

5. Electrical safety
 Obtain permission by the safety coordinator before operating any high voltage equipment
 Maintain an unobstructed access to all electrical panels.
 Avoid using extension cords whenever possible.
 Never, ever modify or otherwise change any high voltage equipment.
 Before attaching the power supply to your setup make sure there are no “live” wires
which can be touched.
 When attaching a high voltage power supply ALWAYS switch off the supply

6. Fire.
 If a person’s clothing catches on fire, he/she needs help.
 Prevent him/her from running.
 Make him/her lie down and smother the flames by rolling, wrapping with lab
coats, blankets, towels, etc.
 Never turn a carbon dioxide extinguisher on a person.
 If a fire breaks out, (if time allows) turn off all burners and remove solvents, place
the chemical and equipment safely to the nearest possible table/bench, exit the
building calmly.
 If you do not use the fire extinguisher, leave the room immediately to a safer
place possibly outside. There are carbon dioxide extinguishers in the building and
the positions and operation of these should be known.
 Point the extinguisher at the base of the flames.
 Very small fires can be put out with a damp towel by smothering.
 Only after the safety of all is assured should the matter of extinguishing the fire be
considered.
Because a few seconds delay can result in very serious injury, Laboratory staff will guide
you on what to do and how to exit during the case of such an emergency.
7. Chemicals Spills.

 Notify Lab Engineer/Assistant immediately and ask for help.


 Spills must be cleaned up promptly and thoroughly.
 Decontaminate equipment, clothing and personnel, including any victims, on site if
necessary
 If corrosive chemicals are spilled on the clothing, remove the affected clothing
immediately, and wash the area with water for 15 full minutes.
 If chemicals are spilled on the skin, wash them off with large volumes of water.
 Do not apply a burn ointment.
 If the chemical is spilled in the eye, it should immediately be washed out thoroughly
with water using the eyewash.
 If acid was involved, a weak solution of sodium bicarbonate in an eyecup should then be
used. If a base, boric acid is effective.
 If corrosive chemicals are spilled on the desk, dilute them with a large volume of water
and then neutralize with sodium bicarbonate if an acid, or dilute acetic acid if a base.
 Go to First AID Room immediately if required.

8. In Case of emergency
 Report the location of the emergency; give your name, telephone number, and building
and floor number.
 Report the nature of the emergency whether an explosion has occurred and whether there
has been a chemical or electrical fire.
RESCUE: 1122
Police Emergency Control Room: 9203333
Army Control Room: 0332-8581614
Army Quick Response Force: 0322-5170958
Police Station (NOON): 051-9243681
Chief Security Officer (Riphah): 0321-5216311
Administrator: 0321-5216301
II. Safety Undertaking

I HAVE READ ALL OF THE ABOVE, AND I AGREE TO CONFORM TO


ITS CONTENTS.

Name: Huzaifa Bin Javaid Course: CSL-112

Student ID: 23760@student.riphah.edu.pk Section: A

Signature: Huzaifa Room:

Date: 15-07-21

Lab Instructor: ___________________


III. Grading Policy
Lab performance 20%
Lab report 20%
Lab Evaluation 20%
Lab Viva 40%

Lab Assessment
Assessment of all the Labs will be done through the Lab Rubrics. A rubric can be a scoring tool to
evaluate given problems. With the help of a rubric the assigned work is divide into parts. Such a divided
work based on rubrics provides clear descriptions of the all the work associated with each part of
problem. All of the labs in the department of Electrical Engineering for 8th semester will have the
following rubrics for assessments and evaluations.

1. The Rubrics for online assessment of Lab Performance and Lab Reports are given below;
1. Lab Performance

Performance
Exemplary (5) Proficient (3-4) Average (2) Poor (1)
indicators

Fully understands Has very good Has good Has poor


the software tools understanding understanding understanding
including its of the of the of the
purpose and quite software software software
able to conduct the tools tools tools
entire experiment including its including its including its
with negligible help purpose and purpose and purpose and
from lab instructor able to able to unable to
after the online conduct conduct conduct
Ability to session to experiment experiment on experiment on
accomplish the lab with some help his own but his own and
Conduct tasks. taken from lab lab instructor on instructor
Experiment instructor on provided help help
whatsApp/text after the
messaging/ online session .provided after
the online
telephonic to accomplish
session to
medium after the task as on
accomplish the
the online the demand of task.
session to student,
accomplish the
lab tasks.
Individual Work Demonstrates the Demonstrates the Demonstrates Demonstrates
ability to manage time, ability to manage some ability to minimal or no
Contributions Designated jobs are time. Designated manage time, ability to manage
and accomplished by jobs are Designated jobs time, Designated
Time deadline; completed accomplished are jobs not
work is carefully and by deadline accomplished by completed
Management: meticulously prepared completed work deadline; by deadline
Ability to carry out
and meets all meets completed work
individual
requirements. requirements. meets most
Responsibilities with Time
Management.
requirements.

Demonstrates an Proposes
Demonstrates a Demonstrates
Propose/Create skillful ability to
ability to propose
some ability to
solutions
Multiple multiple solutions that indicate
propose multiple propose a few
that minimal or no
Solutions solutions that solutions that
indicate comprehension
Ability to propose Indicate a deep indicate some
comprehension of of
solutions to understanding of comprehension
the problem. the problem.
address the problem the problem. Skillful of
Ability to Minimal ability to
and/or ability to create/play the problem.
create/play with create/play
create/play with solutions with new and Some ability to
new with new
innovative solutions create/play with
solutions solutions.
new solutions

2. Lab Report

Performance
Exemplary (5) Proficient (3-4) Average (2) Poor (1)
indicators

Information is Information is Information is Unable to submit


presented in a presented in presented in the lab report.
logical, interesting somewhat logical quite less
way, which is easy manner. All continuity and
Organization / to follow. All sections are in a less logical
sections are in a correct order as manner.
Structure correct order and directed and Sections are not
submitted on a submitted on a in proper order
time. time. as directed and
unable to follow
the submission
deadline.
Results and Results and Results and Unable to submit
conclusion are conclusion are conclusion are the lab report.
stated and reflect stated and reflect stated but reflect
complete acceptable little knowledge
knowledge of the knowledge of the of the
experiment. experiment. experiment.
Presents data very Presents data very Presents data
Calculations with appropriate with appropriate with improper
& Data outputs/ screen outputs/ screen output/results.
Presentation shot are attached. shot are attached. Calculations of
Calculations of all
Calculations of all all
theoretical/rated
theoretical/rated theoretical/rated
values have been
done. Also values have been values have
percentage errors done. Also been not been
b/w theoretical & percentage errors done. Also
experimental values b/w theoretical & percentage
have been experimental values errors b/w
calculated and have been theoretical &
correct conclusions calculated and experimental
have been drawn correct conclusions values have
based on these have been drawn been not been
calculations based on these calculated and
calculations the conclusions
drawn were not
linked with the
calculations.

2. Lab Viva

Performance
Sr.#
Indicator Exemplary (4-5) Satisfactory (2-3) Unsatisfactory (0-1)

Responds well, Generally Non-responsive.


quick and very Responsive and
1 Responsiveness to accurate all the accurate most of
Questions/Accuracy time. the times.

Demonstration of At ease with No grasp of


full knowledge of content and able information. Clearly no
knowledge of subject
the subject with to elaborate and matter. No questions
Level of
explanations and explain to some are answered. No
2 understanding of the interpretation made.
elaboration. degree.
learned skill
Guidelines for lab engineer/evaluator regarding online viva:
 Assessment of online lab viva as per defined in the set of Rubrics.
 Online viva will be taken by using Zoom/Microsoft team software.
 Students can be evaluated in online viva either on individual call or groups call
(maximum 4 students in a group).
 Online Viva on Zoom/MS Teams may include the online examination of students
regarding the tool usage for short type tasks.
 Evaluator must keep the audio/video recording of online viva of all students for future
reference.
 Those students who have the internet issue, may appear for online lab viva through phone
call/WhatsApp.

3. LAB PROJECT

Sr. # Performance
Indicator Exemplary (5) Satisfactory (4-3) Developing(2-1)
Unsatisfactory (0)
Project is completed with Project is completed
Project is completed quite less technical but not working The project is not
without any external assistance from the properly. implemented or not
assistance and is instructor or others in completed with
Implementation working properly. order to complete the Or implementation in
1 and Completion project and is working initial phase only.
properly. Project is completed
Or and working
properly but with
Project is completed
unreasonable
with no external
amount of technical
assistance at all but is
assistance from the
not working properly.
instructor or others
in order to complete
the project.
Student chose an Student choose a Student choose a Student chose a
innovative, complex project with project with simple project with
challenging project good technical acceptable scope limited scope that
challenges that required required very little
that required an that solves a
innovative problem creative
effort that exceeds solving and engineering. technical problem
the normal and required some development or
2 technical expertise.
expectations for the technical expertise
course project. in hardware and/or
Problem software.
Analysis
and
Designing
Solution
Student
Student developed a Student demonstrated the Student was able to demonstrated little or
good systematic ability to test hardware identify the problems no ability to
procedure for testing and/or software in order in hardware and/or troubleshoot
hardware and/or to identify technical software but hardware and/or
software that allowed problems, and was able required some software for the
for quick identification to solve any problems assistance in fixing project.
3 of technical problems. with little or no some of the
Testing and Student was very good assistance. problems.
Analysis at analyzing and
quickly solving all
technical problems.
Project Report
Information is presented in a Information is Information is presented Sequence of
logical, interesting way, presented in in quite less continuity information is
which is easy to follow. All somewhat logical and less logical manner. difficult to
sections are in a correct manner. All sections Sections are not in follow. No
order and submitted on a are in a correct order proper order as directed logical manner
time. as directed and unable to follow the or continuity.
submitted on a time. submission deadline. Objective,
1 Organization results and
Conclusion are
/Structure not stated.
Clearly discusses what Generally clear Limited discussion of Reader canor
results mean and what discussion of results results and conclusions. gain very little
conclusions may be drawn and conclusions, but Little or no reference to information
Unable to
from them. Cites published may miss some published standards or about
submitwhy
the the
lab
standards or other related points. Some use of other reports. project
report. was
reports. references and . done and what
2 published standards. the results
may mean. No
reference to
Literature other studies.
Review

Collected a great deal of Collected some basic Collected very little Did not collect
information--all relates to the information--most information--some any
topic. relates to the topic. relates to the topic information
that relates to
the topic

3
Project Viva
Results and
Discussion
Responds well, quick Generally Responsive Responsive but evasive Non-
and very accurate all and accurate most of or inaccurate most of the responsive.
1 Responsiveness the time. the times. times.

to Questions/

Accuracy
2 Demonstration of full At ease with content Only basic concepts No grasp of
Depth of knowledge of the and able to elaborate are demonstrated information.
Knowledge project with and explain to some and interpreted. Clearly no
explanations and degree. knowledge of
elaboration. subject matter.
No questions
are answered.
No
interpretation
made.

Teamwork

Cooperation was on
1 Cooperation for Everyone worked Some team members average but one person No
together by listening were cooperating but did all the work and the cooperation at
Effective
to each other having some were not. There arguing among the among the
Teamwork no arguing among were few arguments members was not few, team members
each other. As a among the members resulting on somewhat at all, as the
result they met their resulting the effective effective teamwork. team members
goal with most teamwork. did their own
effective teamwork. things. There
was lot of
arguing among
the team
members,
resulting on
No effective
team work.
4. Home task/online lab participation

Note: 20% marks of home task/online lab participation will be assessed through the performance
indicator (Online Work Contributions and Time Management) mention in the table given above.

Performance
Exemplary (5) Proficient (3-4) Average (2) Poor (1)
indicators

Demonstrates the Demonstrates the Demonstrates Demonstrates


Online Work ability to manage time, ability to manage some ability to minimal or no
Contributions Designated jobs are time. Designated manage time, ability to manage
and accomplished by jobs are Designated jobs time, Designated
deadline always; accomplished are jobs not
Time completed work is by deadline accomplished by completed
Management: carefully and completed work deadline; by deadline.
Ability to carry out meticulously prepared and meets completed work Attended the
individual and meets all requirements of meets some of online sessions
Responsibilities with Time requirements of online online lab the with no
Management. lab sessions. sessions. requirements of attendance.
online lab
sessions subject

IV. Level of Inquiry


Level Problem/ Question Procedure/ Method Solution
0 Provided to student Provided to student Provided to student
1 Provided to student Provided to student Constructed by student
2 Provided to student Constructed by student Constructed by student
3 Constructed by student Constructed by student Constructed by student

Level of Description
inquiry
0 The problem, procedure, and methods to solutions are provided to the
student. The student performs the experiment and verifies the results with
the manual.
1 The problem and procedure are provided to the student. The student
interprets the data in order to propose viable solutions.
2 The problem is provided to the student. The student develops a procedure
for investigating the problem, decides what data to gather, and interprets
the data in order to propose viable solutions.
3 A “raw” phenomenon is provided to the student. The student chooses (or
constructs) the problem to explore, develops a procedure for investigating
the problem, decides what data to gather, and interprets the data in order
to propose viable solutions

Object Oriented Programming Lab


Laboratory’s Course Learning Outcomes

Course Title : CSL-112 Object Oriented Programming


Laboratory : Control and Instrumentation Lab
Instructor : Engr. Faisal Saleem
Designation : Lab engineer, Engineering & Applied Sciences
E-mail : Faisal.saleem@riphah.edu.pk

Phone (Off.) : +92-51-8446000-8 (EXT: 241)

Students will be able to:


CLO 1: Imitate technical skills in using code block software for C++ programing. P2
CLO 2: Differentiate the application of various programing models/techniques to solve complex
engineering problem. P3
CLO 3: Design small to moderate level C++ programs using the acquired knowledge to solve
complex engineering problem. P5
Mapping of Course Learning Outcomes (CLO) to Program Learning Outcomes (PLO) / Graduate
Attribute

Course CLOs/ PLO PLO PLO


PLO1 PLO2 PLO3 PLO4 PLO5 PLO6 PLO7 PLO8 PLO9
Code PLOs 10 11 12

CLO 1 X
CLO 2 X
CS-112
CLO 3 X
PLO1: Engineering Knowledge PLO8: Ethics
PLO2: Problem Analysis PLO9: Individual and Team Work
PLO3: Design/Development of Solutions PLO10: Communication
PLO4: Investigation PLO11: Project Management
PLO5: Modern Tool Usage PLO12: Lifelong Learning
PLO6: The Engineer and Society
PLO7: Environment and Sustainability

Department of Electrical Engineering


Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering


Semester: II
Subject: CSL-112 Object Oriented Programming

I. List of Experiments
Level of
Sr No. Title
Inquiry
Revision of Programming Fundamentals:
Conditional Statements
Experiment No: 1
Control Structures I: 1
 Selection (IF-ELSE, NESTED IF)
Rational and Logical (Boolean) Operators
 Selection (SWITCH)

Revision of Programming Fundamentals:


Logic operations, Arithmetic Operators, Type Conversion, and Loop statements
Control Structures II: Repetition ( while, do while)
 Designing while Loops
Experiment No: 2  do...while Looping (Repetition) Structure
2
 Choosing the Right Looping Structure, break and continue Statements
Control Structures II: Repetition ( for, Nested for)
 Understanding for Looping (Repetition) Structure by Counter-
Controlled, Sentinel-Control and by drawing different stars Pattern.

Arrays
 Accessing Array Components
 Processing One-Dimensional Arrays
Experiment No: 3  Array Initialization During Declaration
2
 Integral Data Type and Array Indices
 Searching an Array for a Specific Item

Experiment No: 4
2-Dimentional Arrays
 Accessing Array Components
 Two-Dimensional Array Initialization During Declaration
 Print 2-D Array
 Input 2-D Array 2
 Sum of Array by Row
 Sum of Array by Column
 Largest Element in Each Row and Each Column

Structures
 Accessing Struct Members
 Assignment 2
Experiment No: 5
 Comparison (Relational Operators)
 Input /Output
 Struct Variables and Functions

Pre-defined Functions
User Defined Function
 Value-Returning Functions
Experiment No: 6  Function Call
2
 Programming Example: Largest Number, Add, Subtract, Multiply of
two numbers, Implementation of Demergarn’s law.

Pointers
 Pointer Data Type and Pointer Variables 794
 Declaring Pointer Variables
 Address of Operator (&)
 Dereferencing Operator (*) 1
Experiment No: 7
 Operation On Pointers
 Initializing Pointer Variables
 Dynamic Variables
 Operator new
 Operator delete
Objects and Classes
 Objects and declaring objects.
 Access Controls in classes
Experiment No: 8  Defining class and object 1
 Accessing Data Members
 Member Functions in class

Types of Member Functions


 Simple functions
 Static functions
Experiment No: 9  Const functions 1
 Inline functions
 Friend functions

Member Functions in class


 Function Overloading
 Constructor
 Default Constructor 1
Experiment No: 10
 Parametrized Constructor
 Copy Constructor
 Destructor
Inheritance
Introduction to Inheritance
o public inheritance,
Experiment No: 11 o Private inheritance 2
o Protected inheritance

Types of Inheritance
 Single Inheritance
 Multiple Inheritance
Experiment No: 12 1
 Hierarchical Inheritance
 Multilevel Inheritance
 Hybrid Inheritance (also known as Virtual Inheritance)
Polymorphism
 Function Overriding
Experiment No: 13  Virtual Functions
 Abstract class and Pure Virtual Functions 1
 Virtual Destructors

Experiment No: 14 File handling in OOP using C++ 2


Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 1: Revision of Programming Fundamentals
OBJECTIVES:

Students will learn about:

• Conditional Statements
• Control Structures
• Selection (IF-ELSE, NESTED IF)
• Rational and Logical (Boolean) Operators
• Selection (SWITCH)

Name: Huzaifa Bin Javaid SAP ID: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Introduction:
We will study the basic functions of programming using code blocks and understand
at all about conditional statements in this lab. So, using the software of that sort, we'll go through each
of the lab's tasks one by one.

Conditional Statements:
The software has some requirement for a block of its statement in which
execution follows the shift inside it. We'll go over the various forms of conditional statements one by
one.

• The “if” statement


• The “if-else” statement
• The “Nested-if-else” statement

The “if” statement:


After checking a condition, the "if statement" is used to execute (or ignore) a
sequence of statements. The "if statement" defines whether or not a condition exists. If the condition is
valid, the statement (or collection of statements) after the "if statement" is executed. If the given
statement is false, the statement (or set of statements) following the "if statement" condition is ignored,
and power is passed to the next statement.

The syntax of the “if statement” is:

if (condition)

Statement – 1;

Statement – 2;

In the above syntax, only statement-1 will be executed if the given condition is true otherwise the
control shifts to Statement-2 that comes after the Statement – 1.
Program & it’s Execution:

The “if-else” statement:


This is a variation of the "if statement." It's a tool for making two-sided
decisions. One condition and two blocks of statements are provided in this statement. Following the
evaluation of a condition, one of the two statement blocks is executed. The "if-else" condition is used to
evaluate a given relational condition. The first block of the sentence is executed if the condition is valid.
If the argument is false, the first block of the statement is skipped over, and the second block after the
else is executed.

The syntax of “if-else” statement is:

if (condition)

Statement – 1;

else

Statement – 2;
Lab task 1
Program & Execution:

Lab task 2
Program & Execution:
The “nested-if-else” Statement:
It's called a "nested-if-else" structure when a "if-else" structure is
nested within another "if-else" structure. It is used to pick different items.
Its general syntax is:

If (condition – 1)

Statement – 1;

else if (condition – 2)

Statement – 2;

else if (condition – 3)

Statement – 3

else if (condition – m)

Statement – m

else

Statement – n;

Lab task 3
Program & Execution:
Conclusion:
We learned the various tasks in this lab depending on the lab's objectives. We've also
gone through some of the previous programming commands that we've learned. As a result, we were
able to independently write and compile a program.
Huzaifa Bin Javaid Evaluation 1 23760

Lab Task 1: Write a program of calculator using switch, in which two integers add, subtract,
multiply, divide by detecting operator if operator is “+” then add, if operator is “-” then
subtract and so on…

#include <iostream>

using namespace std;

int main() {

char op;

float num1, num2;

cout << "Enter an arithemetic operator(+ - * /)\n";

cin >> op;

cout << "Enter two numbers as operands\n";

cin >> num1 >> num2;

switch(op) {

case '+':
Huzaifa Bin Javaid Evaluation 1 23760
cout << num1 << " + " << num2 << " = " << num1+num2;

break;

case '-':

cout << num1 << " - " << num2 << " = " << num1+num2;

break;

case '*':

cout << num1 << " * " << num2 << " = " << num1*num2;

break;

case '/':

cout << num1 << " / " << num2 << " = " << num1/num2;

break;

default:

cout<<"ERROR";

return 0;

}
Huzaifa Bin Javaid Evaluation 1 23760

Lab Task 2: Write a program that determines an employee’s weekly wages. If the hours
worked exceed 40, wages include overtime payment

#include <iostream>

#include <string>

using namespace std;

int main()

// Declared Variables Block

string first, last;

double hours;

double minutes;

float hourly_wage;

float computed_pay;

float overtime_pay;

double max_hours = 40;


Huzaifa Bin Javaid Evaluation 1 23760
// Input Statements Block

cout << "Enter the Employee's first name: ";

cin >> first;

cout << "Enter the Employee's and last name: ";

cin>> last;

cout << "Enter Hours worked: ";

cin >> hours;

cout << "Enter Minutes worked: ";

cin >> minutes;

cout << "Enter hourly wage: ";

cin >> hourly_wage;

// Output Statements Block

cout << "\n";

cout << "---------- Employee Information -----------" << endl;

cout << "Employee: " << first << " " << last << endl;

cout << "Time worked: " << hours << "hours"

<< ", " << minutes << " minutes" << endl;

cout << "Hourly wage: $" << hourly_wage << endl;

cout << "\n";

if (hours <= 40)

computed_pay = hourly_wage * hours;

cout << "The computed pay is: " << computed_pay;

cout << "\n";


Huzaifa Bin Javaid Evaluation 1 23760
}

else (hours >40);

overtime_pay = (hours - 40) * 1.5 * hourly_wage;

computed_pay = max_hours * hourly_wage+ (hourly_wage/60*minutes) + overtime_pay;

cout << "The computed pay is: $" << computed_pay;

cout << "\n";

return 0;

}
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
RIPHAH International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 2: Revision of Programming Fundamentals
OBJECTIVES:

Students will learn about:

 Logic operations, Arithmetic Operators, Type Conversion, and Loop statements


 Control Structures II: Repetition (while, do while)
 Designing while Loops
 do...while Looping (Repetition) Structure
 Choosing the Right Looping Structure, break and continue Statements
 Control Structures II: Repetition (for, Nested for)
 Understanding for Looping (Repetition) Structure by Counter-Controlled, Sentinel-Control and
by drawing different stars Pattern

Name: Huzaifa Bin Javaid SAP ID: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Introduction:
By understanding logic operators, arithmetic operators, type translation, and loop
statements, we will be able to apply what we learned in the previous topic in this lab. We'll also explain
and run a few programs to make sure we're on board for our tests. Any of the tasks that will be covered
in today's lab are mentioned below.

Loops:
A loop is a statement or group of statements that is replicated over and over again. The
statements in a loop are repeated until a certain amount of times or until a condition is satisfied.

In C++, there are three kinds of loop statement. These are:

 The “while” loop.


 The “for” loop.
 The “do-while” loop.
The “while” Loop:
It's a conditional statement. It's used to execute a statement or a group of
statements as long as the stated condition is satisfied.

The syntax of the “while” loop is:

while (Condition)

Statement;

Where

Condition has a relational expression. If it is valid, the while loop's statement (or set of statements) is
executed.

Statement The body of the loop is defined by it. Braces are used to surround a compound statement or
a series of statements.
Lab Task 1:
Program & Execution:

The “do-while” loop:


The "do-while" loop is a conditional loop statement. It works similarly to a while
loop, with the exception that the state is evaluated after the loop's statement has been executed.

The syntax of the “do-while” is:

do

statement

while (condition);

where

do is a C++ keyword. It represents the beginning of the do-while loop.

The body of the loop is defined by a statement enclosed in braces.

condition is the condition that must hold true for the loop to execute.
Lab Task 2:
Program & Execution:

The “for” Loop:


The "for loop" statement is used to continuously run a sequence of statements. A
counter loop is a term used to describe this type of loop.

In terms of structure, this loop differs from both the "while" and "do-while" loops.

It has the following parts:

 Initialization.
 Condition.
 Increment or decrement.
 Body of the loop.

The general syntax of the “for loop” is:

for (initialization; condition; increment/decrement)


Lab Task 3:
Program & Execution:

The Nested Loops:


The word "nested loop" refers to a loop structure that is completely enclosed
within the body of another loop structure.

The concept of nested loops has been explained in the following program.

Lab Task 4:
Program & Execution:
Lab Task 5:
Program & Execution:

Conclusion:
In this lab we looked at conditional and iterative control structures. while, do-while, for and
nested loops by doing some examples now we are able to execute loops in program. Almost any
nontrivial program will need to make some kind of decision based on input data
Huzaifa Bin Javaid Evaluation 2 23760

Lab Task 1: Write a Program in which user input different numbers on the output window, if
user put -999 then program stops and give sum, average of all previous numbers. Also give
the largest number from all of the previous number.

#include <iostream>
using namespace std;
int main()
{
int sum, avg, i, a, n, large;
sum=0;
large=0;
n=0;
for(i=0; i<=n; i++)
{
Huzaifa Bin Javaid Evaluation 2 23760

cout<<"Enter number "<<i+1<<endl;


cin>>a;
sum=sum+a;
n++;
if(a>large)
{large=a;}
if (a==-999)
{
break;
}
}

avg=(sum+999)/(n-1);
cout<<"sum = "<<sum+999<<endl;
cout<<"average = "<<avg<<endl;
cout<<"The largest number is "<<large;
return 0;
}
Huzaifa Bin Javaid Evaluation 2 23760

Lab Task 2: Write a program in which user put any value on output window, and program give
the counting up to that number using do…while loop.

#include <iostream>
using namespace std;
int main()
{
cout << "Please Enter The Number" << endl;
int i=1,n;
cin>> n;
while (i<=n){
cout<< i<<""; ++i;
}
return 0;
}
Huzaifa Bin Javaid Evaluation 2 23760

Lab Task 3: Write a program that creates the following pattern using Nested for:
*
**
***
****
*****

#include <iostream>

using namespace std;

int main()

int N ;

cout<<"Enter the digit of your choice : ";

cin>>N;

int M = N;

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

{
Huzaifa Bin Javaid Evaluation 2 23760

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

cout << "*";

cout << endl;

M++;

system("pause");

return 0;

}
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 3: Arrays
OBJECTIVES:

Students will learn about:

 Accessing Array Components


 Processing One-Dimensional Arrays
 Array Initialization During Declaration
 Integral Data Type and Array Indices
 Searching an Array for a Specific Item

Name: Huzaifa Bin Javaid Sap ID: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Introduction:
We will discuss arrays and perform some tasks regarding different types of arrays in this
object-oriented programming lab to better understand the purpose of arrays in programming. We'll
write some programs to see if we understand arrays and their forms correctly.

Arrays:
A sequence of objects of the same data type is called an array. The elements of an array are the
objects that make up the array.

A sequence of storage locations represents an array in computer memory. A single


variable called array name refers to all of these positions. An array's location in the array is used to
reference each element.

Accessing Array Component:


The subscript value of an array element is used to access it. The
subscript or index value is enclosed in a pair of square brackets [ ] along with the array's name. The
name of the array and the index value of the variable are used to reference an array element.

Arrays are used to handle vast amounts of data of various types. The knowledge is kept
in an array. A single variable name is used to navigate the list. Individual elements of the collection are
accessed using the index value. To process data in an array, you'll need a few statements. As a result
When arrays are used in a program, the program's size is reduced.

Types of Arrays:
There are two types of arrays:

 One-dimensional arrays.
 Multi-dimensional arrays.

One-dimensional Arrays:
One-dimensional array is also known as a list or a linear array. It
consists of only one column or one row.

Declaring One-Dimensional Arrays:


An array, like other variables, is declared. Declaring an array is the
process of defining the array's name, form, and total number of elements. When an array is declared, a
memory block with the requisite number of locations in the computer memory is set aside for storing
data into the array's elements.

The general syntax to declare a one-dimensional array is:

type array_name [n];

where

‘n’ is an assigned integer value. It represent the total number of elements of the array.
Accessing Data in One-Dimensional Arrays:
The index of each element in an array is used to refer to it.
Element in an array of n elements has an index value. The first element's index is 0 and the last
element's index is n-1.

The index value is written within square brackets after the array name.

Initializing One-Dimensional Arrays:


The values in the elements of an array, like other variables, can be
allocated when the array is declared. Initializing an array refers to the process of assigning values to its
elements at the time of its declaration.

Sorting Arrays:
Sorting is the method of organizing data in a particular order. Data of the numerical
form may be organized in ascending or descending order. Similarly, data of the character form can be
ordered alphabetically.

There are different methods to sort data into a list. The most commonly used methods are:

 Bubble Sort
 Selection Sort

Bubble Sort:
The bubble sort method is used to arrange values of an array in ascending or in descending
order.

Two adjacent elements are contrasted to organize an array in ascending order. The two
elements are swapped if one is larger than the other. The larger value progressively floats or bubbles to
the top as elements are exchanged. Similarly, when an array is arranged in ascending order, the smaller
value gradually rises to the top.

The bubble sort method is a time-consuming technique. It's only good for sorting small amounts
of data. This method is simple to program.

Selection Sort:
This method can also be used to sort arrays either ascending or descending. If an array
has n elements, sorting it needs n-1 iterations.

Lab task 1: Accessing Array Elements


Lab Task 2: Average of Array Elements

Lab Task 3: Finding Minimum & Maximum value in array


Lab Task 4: Element Separators
Conclusion:
We learned about the various types of arrays and how to use them in a program in this lab.
We also cover the lab's goal with the aid of the activities we completed in the lab.
Huzaifa Bin Javaid Evaluation 3 23760

Lab Task 1: Declare an array of type int that having a length of 10 elements.
Lab Task 2: Read data into array: Write a code in which user put values on output window
for each location in the array. Note: using for loop.
Lab Task 3: Print array: Write a code to display each element of array. Note: using while
loop.
Lab Task 4: Sum and average all elements: Write a code that gives the sum and average
of all elements of the array.
Lab Task 5: Greater number in array: Write a code that finds greater number in the array.

#include <iostream>

int main(){

using namespace std;

int n[10]; // declaring n as an array of 10 integers //

int i,j,sum,avg;

// initializing elements of array n //

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

{
Huzaifa Bin Javaid Evaluation 3 23760

cout << "Enter value of n[" << i << "]"<< endl;

cin >> n[i];

sum += n[i]; //used for sum up all the elements of array//

// printing the values of elements of array //

for (j = 0; j < 10; j++ )

cout << "n[" << j << "] = " << n[j] << endl;

// Loop to store largest number

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

if(n[0] < n[i])

n[0] = n[i];

cout << "Largest element = " << n[0] << endl;

avg = sum / 10; // to take out the average of all elements of array//

cout << "Sum of all element = "<< sum<< endl;

cout << "Average = " << avg;

return 0;

}
Huzaifa Bin Javaid Evaluation 4 23760

Department of Electrical Engineering


Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 4: Arrays (Two dimensional)
OBJECTIVES:

Students will learn about:

• Two-Dimensional Array Initialization During Declaration


• Input 2-D array
• Sum of Array by Row & by Column
• Largest Element in Each Row and Each Column

Name: …………………………… Roll No: ………………………………

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Huzaifa Bin Javaid Evaluation 4 23760

Theory:
An array is a collection of elements of the same type placed in contiguous memory
locations that can be individually referenced by using an index to a unique identifier. Five values
of type int can be declared as an array without having to declare five different variables

Lab Task 6: Declare an array of type int of size 4 by 4.


Lab Task 7: Initialize all location of array to zero by following command; i.e int A[4][4]={0};
Lab Task 8: Display the above array by following code:
That is: for
for (row = 0; row < NUMBER_OF_ROWS; row++)
{
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
cout << setw(5) << matrix[row][col] << " ";
cout << endl;
}

// lab task 6,7,8

#include <iostream>

#include <iomanip>

using namespace std;


Huzaifa Bin Javaid Evaluation 4 23760

int main ()

int A[4][4]={0};

int r, c;

for (int i = 0; i < 4; i++)

for (int j = 0; j < 4; j++)

cout << setw(5) << A[i][j] << " ";

cout << endl;

}
Huzaifa Bin Javaid Evaluation 4 23760

Lab Task 9: Insert the number 30 on the mark locations of the array by command (A [0][1]=30;).

//lab task 9

#include <iostream>

#include <iomanip>

using namespace std;

int main ()

int A[4][4]={0};

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

for (int j = 0; j < 4; j++)

{
Huzaifa Bin Javaid Evaluation 4 23760

if (i == 0 && j == 1 || i == 0 && j == 3 ||i == 2 && j == 1 || i == 3 && j == 2)

A[i][j]= 30;

cout << setw(5) << A[i][j] << " ";

else

cout << setw(5) << A[i][j] << " ";

cout << endl;

Lab Task 10: Write a code using nested for in which user input data on output window in each
location of the matrix.

// lab task 10
#include <iostream>
Huzaifa Bin Javaid Evaluation 4 23760

#include <iomanip>
#include<fstream>
using namespace std;

int main ()
{
int A[4][4]={0};

for (int i = 0; i < 4; i++)


{
for (int j = 0; j < 4; j++)
{
cout << "Enter element for " << i + 1 <<" - "<< j + 1 << " : ";
cin >> A[i][j];

}
}
for(int i=0; i<4; i++) //This loops on the rows.
{
for(int j=0; j<4; j++) //This loops on the columns
{
cout << A[i][j] << " ";
}
cout << endl;
}
Huzaifa Bin Javaid Evaluation 4 23760

Lab Task 11: Write a code that finds the sum of first row’s elements.

// lab task 11
#include <iostream>
#include <iomanip>
#include<fstream>
using namespace std;

int main ()
{
int A[4][4]={0};
int i,j,r,c,sum,sr;

for ( i = 0; i < 4; i++)


{
Huzaifa Bin Javaid Evaluation 4 23760

for ( j = 0; j < 4; j++)


{
cout << "Enter element for " << i + 1 <<" - "<< j + 1 << " : ";
cin >> A[i][j];

}
}
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}

cout << "Enter row number to sum (1,2,3,4): ";


cin >> sr ;

for(i = 0; i < sr; i++)


{
r = 0;
for(j = 0; j < 4; j++)
{

r = r + A[i][j];
}
Huzaifa Bin Javaid Evaluation 4 23760

}
cout << "\nThe Sum of Items in row "<<sr<<" = " << r ;

Lab Task 12: Write a code that finds the sum of third column’s elements.

// lab task 11
#include <iostream>
#include <iomanip>
#include<fstream>
using namespace std;

int main ()
{
int A[4][4]={0};
int i,j,r,c,sum,sr,sc;

for ( i = 0; i < 4; i++)


{
Huzaifa Bin Javaid Evaluation 4 23760

for ( j = 0; j < 4; j++)


{
cout << "Enter element for " << i + 1 <<" - "<< j + 1 << " : ";
cin >> A[i][j];

}
}
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}

cout << "Enter column number to sum (1,2,3,4): ";


cin >> sr ;

for(i = 0; i < sr; i++)


{
c = 0;
for(j = 0; j < 4; j++)
{

c = c + A[j][i];
Huzaifa Bin Javaid Evaluation 4 23760

}
}
cout << "\nThe Sum of Items in Column "<<sr<<" = " << c ;

Lab Task 13: Write a code that finds the sum of all elements of the array.

// lab task 13
Huzaifa Bin Javaid Evaluation 4 23760

#include <iostream>
#include <iomanip>
#include<fstream>
using namespace std;

int main ()
{
int A[4][4]={0};
int sum;

for (int i = 0; i < 4; i++)


{
for (int j = 0; j < 4; j++)
{
cout << "Enter element for " << i + 1 <<" - "<< j + 1 << " : ";
cin >> A[i][j];

}
}
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
Huzaifa Bin Javaid Evaluation 4 23760

for(int i=0; i<4; i++)


{
for(int j=0; j<4; j++)
{
sum=sum+A[i][j];
}
}
cout<<"sum of array is : "<< sum;
return 0;
}

Lab Task 14: Write a code that finds the greater number from first row.

//lab task 14
#include <iostream>
#include <iomanip>
Huzaifa Bin Javaid Evaluation 4 23760

#include<fstream>
using namespace std;

int main ()
{
int A[4][4]={0};
int largest,r,max;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << "Enter element for " << i + 1 <<" - "<< j + 1 << " : ";
cin >> A[i][j];
}
}
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
cout << "Enter row number to find its largest element (1,2,3,4): ";
cin >> r ;
for (int i = 0; i < r; i++)
{
Huzaifa Bin Javaid Evaluation 4 23760

max = A[i][0];
for (int j = 1; j < 4; j++)
{
if (A[i][j] > max)
{
max = A[i][j];
}
}
}
cout<<"The largest element in this row is "<<max;
return 0;
}

Lab Task 15: Write a code that finds the greater number from third column.

//lab task 14
#include <iostream>
Huzaifa Bin Javaid Evaluation 4 23760

#include <iomanip>
#include<fstream>
using namespace std;

int main ()
{
int A[4][4]={0};
int largest,r;

for (int i = 0; i < 4; i++)


{
for (int j = 0; j < 4; j++)
{
cout << "Enter element for " << i + 1 <<" - "<< j + 1 << " : ";
cin >> A[i][j];

}
}
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
Huzaifa Bin Javaid Evaluation 4 23760

cout << "Enter row number to find its largest element (1,2,3,4): ";
cin >> r ;

for (int j = 0; j < r; j++)


{
largest = A[0][0];
for (int i = 0; i < 4; i++)
{

if (A[i][j] > largest)


{
largest = A[i][j];
}
}

}
cout<<"The largest element in this column is "<<largest;
return 0;
}
Lab Task 16: Write a code that finds the greater number from the whole array.
Huzaifa Bin Javaid Evaluation 4 23760

#include <iostream>
#include <iomanip>
#include<fstream>
using namespace std;

int main ()
{
int A[4][4]={0};
int largest,r,rpos,cpos;

for (int i = 0; i < 4; i++)


{
for (int j = 0; j < 4; j++)
{
cout << "Enter element for " << i + 1 <<" - "<< j + 1 << " : ";
Huzaifa Bin Javaid Evaluation 4 23760

cin >> A[i][j];


}
}
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
largest = A[0][0];

for(int i=0; i<4; i++)


{
for(int j=0; j<4; j++)
{
if(A[i][j]>largest) {
largest = A[i][j];
}
rpos = i;
cpos = j-i+1;
}
}
cout<<"The largest element in the array is "<<largest<< " on " <<rpos<<" - "<<cpos;
return 0;
}
Huzaifa Bin Javaid Evaluation 4 23760

Conclusion:
After this lab I have better understanding of two-dimensional Arrays
1) Array stores data elements of the same data type.
2) Maintains multiple variable names using a single name. Arrays help to maintain
large data under a single variable name. This avoid the confusion of using multiple
variables.
3) Arrays can be used for sorting data elements.
4) Arrays can be used for performing matrix operations. Many databases, small and
large, consist of one-dimensional and two-dimensional arrays whose elements are
records.
Huzaifa Bin Javaid Evaluation 5 23760

Department of Electrical Engineering


Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 5: Structures
OBJECTIVES:

Students will learn about:

• Accessing Struct Members


• Assignment and input/output
• Comparison (Relational Operators)
• Struct Variables and Functions

Name: Huzaifa Bin Javaid Roll No: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Huzaifa Bin Javaid Evaluation 5 23760

Structure is a group of variables of different data types represented by a single


name. Let’s take an example to understand the need of a structure in C
programming.

Let’s say we need to store the data of students like student name, age, address,
id etc.

Lab Task : Write a program in which you create an array of structure, read information
into it and display the information of an employee depending upon the given employee
number.

#include <iostream>

using namespace std;

struct rec

int comid;

int ageemp;
Huzaifa Bin Javaid Evaluation 5 23760

float salary;

char name[25];

};

int main()

rec a[9];

char k[25];

int i,w,n;

cout<<"Please enter the number of employees registrations"<<endl;

cin>> n;

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

cout<<"Please enter employee name"<<endl;

cin>>a[i].name;

cout<<"Please enter company ID"<<endl;

cin>>a[i].comid;

cout<<"Please enter the age of employee"<<endl;

cin>>a[i].ageemp;

cout<<"Please enter the total salary"<<endl;

cin>>a[i].salary;
Huzaifa Bin Javaid Evaluation 5 23760

cout<<endl<<endl;

cout<<"Please enter Company ID to Print Record ";

cin>> w;

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

if (a[i].comid == w){

cout<<"Name of employee is : "<<a[i].name<<endl;

cout<<"ID of Company is "<<a[i].comid<<endl;

cout<<a[i].name<<" is "<<a[i].ageemp<< " Years old "<<endl;

cout<<"his total salary is "<<a[i].salary<<endl;

return 0;

Conclution:
In this lab I have learnt about the structure what is it how to use it

• It is good for defining abstract data types.


• Implementation details are hidden from other modules and other modules has a clearly
defined interface.
• It is easy to maintain and modify existing code as new objects can be created with small
differences to existing ones.
Huzaifa Bin Javaid Evaluation 6 23760

Department of Electrical Engineering


Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 6: Pre-defined Functions and User Defined Functions
OBJECTIVES:

Students will learn about:

• Value-Returning Functions
• Function calls
• Programming Example: Largest Number, Add, Subtract, Multiply of two numbers.
• Implementation of DeMorgon’s law

Name: …………………………… Roll No: ………………………………

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Huzaifa Bin Javaid Evaluation 6 23760

Functions
A function is a block of code which only runs when it is called. You can pass data, known as parameters,
into a function.

Functions are used to perform certain actions, and they are important for reusing code: Define the code
once, and use it many times.

Lab Task 2: Write a code in which user input two numbers in variable x and y, and program gives the
sum of two numbers, and call it in the main. Note: use functions

Lab Task 3: Make a function that subtracts the two numbers in lab task 2, and call it in the main.

Lab Task 4: Make a function that multiplies the two numbers in lab task 2, and call it in the main.

Lab Task 5: Make a function that divides the two numbers in lab task 2, and call it in the main.

Lab Task 6: Implement the following equation in main in lab task 2 without using any operator or sign.
Note: use Demorgarn’s law

For example:

z= x + y/ x * x;

z= div (sum(x, y), multi(x, x));

1) F = y * y + x / y;

2) D = x / y - x * x;

3) G =x* y – x + y* y;

Verify the answer with using sign operators.

#include<iostream>
Huzaifa Bin Javaid Evaluation 6 23760

using namespace std;

int sum(int, int);

int subtract(int, int);

int div(int, int);

int mul(int, int);

int main()

int x,y,s,d,m,sub,f,df,D,dd,g,dg;

cout<<"Enter first number X : ";

cin>>x;

cout<<"Enter second number Y : ";

cin>>y;

s=sum(x,y);

sub=subtract(x,y);

d=div(x,y);

m=mul(x,y);

cout<<"Sum is : "<<s<<"\nDifference is "<<sub<< "\nDivition is "<<d<<"\nMultipication is "<<m;

f = y * y + x / y;

D = x / y - x * x;

g = x* y - x + y* y;

df = sum(div(x,y),mul(y,y));

dd = subtract(div(x,y),mul(x,x));

dg = sum ( subtract ( mul ( x , y ) , x) , mul ( y , y ) ) ;

cout<<"\nF with operators = "<<f;

cout<<"\nF without operators = "<<df;

cout<<"\nD with operators = "<<D;

cout<<"\nD without operators = "<<dd;

cout<<"\nG with operators = "<<g;


Huzaifa Bin Javaid Evaluation 6 23760

cout<<"\nG without operators = "<<dg;

return 0;

int sum(int a, int b)

int total;

total=a+b;

return total;

int subtract(int a, int b)

int total;

total=a-b;

return total;

int div(int a, int b)

int total;

total=a/b;

return total;

int mul(int a, int b)

int total;

total=a*b;

return total;

}
Huzaifa Bin Javaid Evaluation 6 23760

Conclution:
In this lab I have learned the syntax, use, and scope of C++ functions and variables. In
particular I learned:
How C++ uses function prototypes
How using default function arguments can save you time
What it means to overload a function
How to use the keyword inline to speed up programs
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
RIPHAH International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 7: Pointers
OBJECTIVES:

Students will learn about:

• Pointer Data Type and Pointer Variables


• Declaring Pointer Variables.
• Address of Operator (&) and Dereferencing Operator (*)
• Operation on Pointers.

Name: Huzaifa Bin Javaid Sap ID: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: ………………………


Theory
Pointers
A pointer is a variable in C++ that keeps track of the address of another variable. Pointers have a
data form like normal variables. A pointer of type integer, for example, may be used to store the
address of an integer variable. A character-type pointer can be used to store the address of a
character-type variable.
A pointer can be thought of as a symbol for a memory address. Programs can mimic call-by-
reference using pointers. They can also use complex data structures to construct and manipulate. A
pointer variable in C++ is a variable that points to a particular location in memory that is pointed to
by another variable.

Addresses in C++
You must first understand how computers store data in order to grasp C++ pointers.
When you build a variable in C++, it is given some memory space. The assigned position stores
the value of this variable.
The & (reference) operator in C++ is used to find the location in computer memory where the
data is stored. The address of a variable is returned by this operator.

Pointer Declaration Syntax


The declaration of C++ takes the following syntax:
datatype *variable_name;

Reference operator (&) and Deference operator (*)


The address is returned by the reference operator (&).
The dereference operator (*) is used to retrieve a value from a memory address. As an illustration:
If we have a variable called num, which is stored at 0x234 and has the value 28, we can use it.
0x234 will be returned by the reference operator (&).
The dereference operator (*) will give you a value of 5.
Lab Evaluation
#include <iostream>
using namespace std;
int main() {
int *p;
int x = 37;
cout << "Line 1: x = " << x << endl; //Line 1
p = &x; //Line 2
cout << "Line 3: *p = " << *p
<< ", x = " << x << endl; //Line 3
*p = 58; //Line 4
cout << "Line 5: *p = " << *p
<< ", x = " << x << endl; //Line 5
cout << "Line 6: Address of p = " << &p << endl; //Line 6
cout << "Line 7: Value of p = " << p << endl; //Line 7
cout << "Line 8: Value of the memory location "
<< "pointed to by *p = " << *p << endl; //Line 8
cout << "Line 9: Address of x = " << &x << endl; //Line 9
cout << "Line 10: Value of x = " << x << endl; //Line 10
return 0;
}

Conclusion
We learned about pointers in this lab. The pointer data type and pointer variable have been
discussed. Following that, we learned how to decode a pointer variable. Following that, we
learned about the reference and dereference operators. Finally, we learned how to use the
pointer to perform various operations.
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 8: Objects and Classes
OBJECTIVES:

Students will learn about:

• Objects and declaring objects


• Access Controls in classes
• Defining class and object
• Accessing Data Members

Name: Huzaifa Bin Javaid Sap ID: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Objects and declaring objects:
An Object is the instance of a Class. When a class is defined, no memory is allocated; however,
when it is instantiated, memory is allocated (that is, when an object is formed).
Declaration of the Object: When a class is defined, it only specifies the requirements of the object;
no memory or storage is allocated. To use the data and access the features described in the class,
you must create objects.
Syntax:
Class Name, Object Name;
Example:

#include <iostream>
using namespace std;
class football
{
public:
int a;
};
int main() {
football obj1; // Declare an object of class foptball

obj1.a = 34;

cout<<obj1.a;
return 0;
}
Access Controls in classes
The access limitations for class members are defined by the elements of the class body labeled
public, private, and protected. The keywords public, private, and protected are used as access
specifiers.

Example 1:
#include <iostream>
using namespace std;
class Student
{
private: // private data member
int rollno;
public: // public accessor functions
int getRollno()
{
return rollno;
}
void setRollno(int i)
{
rollno=i;
}
};
int main()
{
Student A;
A.rollono=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}

Figure 1 Error Because “int rollno” is in Private Class Because The class members declared as
private can be accessed only by the functions inside the class.

Example 2:
#include <iostream>
using namespace std;
class student {
public: // public accessor functions
int rollno;
int getRollno()
{
return rollno;
}
void setRollno(int i)
{ rollno=i;
}
};
int main() {
student A;
A.rollno=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}

Figure 2 Adding "int rollno" in public function because All the class members declared under public will
be available to everyone.
Defining class and object
A class is the basic building component of Object-Oriented programming in C++. It's a user-
defined data type with its own set of data members and member functions that may be accessed
and utilized once a class instance is created. A C++ class is equivalent to the blueprint of an
object.
For Example:
Take, for example, the Automobile Class. There may be many various types of cars with
different names and brands, but they all have the same basic features, such as four wheels, a
speed restriction, and a range of kilometers. Here, the class is car, and the qualities are wheels,
speed limits, and mileage.
class car
{ };

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
Syntax:
ClassName ObjectName;
Example:
class football
{

};
int main() {
// Declare an object of class football

football ob1;

return 0;
}
Accessing Data Members
The dot(‘.') operator with the object can be used to access the data members and member
functions of the class.
Example:
class Student
{
public:
int rollno;
string name;
};
int main()
{
Student A;
Student B;

// setting values for A object


A.rollno=1;
A.name="Adam";

// setting values for B object


B.rollno=2;
B.name="Bella";

cout <<"Name and Roll no of A is: "<< A.name << "-" << A.rollno;
cout <<"Name and Roll no of B is: "<< B.name << "-" << B.rollno;
}
Conclusion:
I learned about objects and classes in this lab. In addition, I learnt how to work with objects and
classes. An object is a collection of data and functions. All of an object's properties are given in
classes. Its purpose and how to declare object and class values, as well as object and class data
type initialization. Only the object specification is defined when a class is defined; no memory is
defined; no memory or storage is allocated. To use the data and access functions defined in the
class, you need to create objects. Classes help in simplifying the complexity of the program. The
execution speed of a program improves. By this lab work, I gain more skill to program execution
in classes.
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 9: Classes and Member Functions in class
OBJECTIVES:

Students will learn about:

• Types of Member Functions


• Simple, static, and const functions
• Inline functions
• Friend function
Name: Huzaifa Bin Javaid Sap ID:23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Types of Member Functions
C++ has a large number of member functions as compared to other object-oriented programming
languages. Other programming languages have only one or two types of member functions,
whereas C++ includes six.
• Simple member functions
• Static member functions
• Const member functions
• Inline member functions
• Friend member functions

Simple, Static Const Functions


Simple Member Function:
Simple member functions are those that are specified in a class but do not provide a type (as will
be detailed later). A simple member function has the following syntax.
data_type function_name (parameters)
{
statement(s);

}

Static Member Function:


If a class's member function is designated static, it can be called directly from the main function
or from the class's objects.
Example:
#include <iostream>
using namespace std;
class person {
public:
static void speak(){
cout<<"Huzaifa"<<endl;
}
};
int main(){
person a;
a.speak(); //calling through object//
person::speak(); //calling without object//
return 0;
}
Const Member Function:
A member function's inability to change the values of data members is occasionally required. In
this case, we define const member functions.
Example:

class Person

{
public:
string country;
void speak() const
{
//It will use all the data members as constants
//Values of data members cannot be changed here

};
Inline Functions
It can help to speed up processing if applied appropriately. They are short functions defined
within the body of the class. They must be prefixed with the keyword "inline" if they are
specified outside of the class boundary.
Example
#include <iostream>

using namespace std;


inline int Min(int a, int b) {
return (a < b)? a : b;
}
// Main function for the program//
int main() {
cout << "Min (10,25): " << Min(10,25);
cout << "\nMin (100,30): " << Min(100,30);
cout << "\nMin (50,70): " << Min(50,70);
return 0;
}
Friends Functions
A friend function is an exception to the restriction that private data members cannot be
accessed outside of the class. Despite the fact that the friend function is not a member of the
class, it has access to all of the data members, including secret data members.
Example:
#include <iostream>
using namespace std;
class person{
private:
string country;
friend void speak ();
};
void speak(){
person p;
p.country ="Pakistan";
cout<<"I live in "<<p.country <<endl;
}
int main()
{
speak();
return 0;
}
Conclusion:
Member functions were introduced to me in this lab. I also learned how to use the functions of
members. Find more about the many varieties of it as well. Simple, Static, Constant, Inline, and
Friend are the different types of functions. How to declare the values of member functions, and
how to initialize member functions using data types. To manipulate data members, the member
functions are utilized. Only once you've created an object can you use the member functions.
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 10: Member Functions in class
OBJECTIVES:

Students will learn about:

• Function Overloading
• Default and Parameterized Constructor
• Copy constructor

Name: Huzaifa Bin Javaid Sap ID: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Function Overloading:
In C++, procedure stacking enables system or even more procedures to share the same name but
have distinct parameters. Function overloading occurs when a function name is overloaded with
several responsibilities.
The “Function” name should be the same in Component Overload, but the input should be variable.
Polymorphism is a C++ feature that enables overloading of operations.
Following is a simple C++ example to demonstrate function overloading.
#include <iostream>

using namespace std;

void print (int x) {

cout << " Here int is " << x << endl;

void print(double y) {

cout << " Here float is " << y << endl;

void print(char const *z) {

cout << " Here char is " << z << endl;

int main() {

print(10);

print(10.10);

print("ten");

return 0;

}
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class addition
{
public: // public accessor functions
int sum (int x, int y)
{
cout << x+y;
}
int sum(int x, int y, int z)
{
cout << x+y+z;
}
};
int main()
{
addition num1; num1.sum (10,20); // sum() with 2 parameter will be called
num1.sum(10,20,30); //sum() with 3 parameter will be called
getch();
return 0; }
#include <iostream>
using namespace std;

class Addition
{ public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(double a, double b)
{
cout<<a+b;
}
};
int main()
{
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(1.5, 2.3);
return 0;
}
Default and Parameterized Constructor
Manufacturers are new membership functions in C++ that are generated when a function is called
or declared, and their objective is to establish that class's object. Because it creates the entries of the
class's data members, it's called a constructor.
Default constructor
If no constructor is declared in the class, the compiler creates one for the program. When a user-
defined constructor does not exist, the compiler creates a default constructor that does not take any
parameters.
Syntax:
class class_name
{
.........
public:
class_name() { }; //default constructor
.........
};

Parameterized constructor
Parameterized constructors, to put it another way, are constructors that can take parameters. We
typically need to initialize the various data sections of the various objects with changing values
while building objects in actual applications. The arguments are supplied to the constructor
functions when the object is created.
Example:
#include <iostream>
using namespace std;
class xyz
{
private:
int length,breadth,x;
public:
xyz (int a,int b) //parameterized constructor to initialize l and b
{ length = a;
breadth = b;
}
int area( ) //function to find area
{
x = length * breadth;
return x;
}
void display( ) //function to display the area
{
cout << "Area = " << x << endl;
}
};
int main()
{
xyz c(8,4); //initializing the data members of object 'c' implicitly
c.area();
c.display();
xyz c1= xyz(4,9); // initializing the data members of object 'c' explicitly
c1.area();
c1.display();
return 0;
}
Copy Constructor:
In most cases, a value parameter in a constructor cannot be an object from the same class. On the
other hand, the class's own object can be used as a reference parameter. Constructors with a
reference to an object of their own class are known as copy constructors.
Example:
#include <iostream>
using namespace std;
class clone
{
private:
int x;
public:
clone (int a) //parameterized constructor to initialize l and b
{
x = a;
}
clone( clone &b) //copy constructor with reference object argument
{
x = b.x;
}
int display( ) //function to display
{
return x;
}
};
int main()
{
clone c1(2); //initializing the data members of object 'c' implicitly
clone c2(c1); //copy constructor called
clone c3 = c1;
clone c4 = c2;
cout << "clone 1 = " << c1.display() << endl;
cout << "clone 2 = " << c2.display() << endl;
cout << "clone 3 = " << c3.display() << endl;
cout << "clone 4 = " << c4.display() << endl;
return 0;
}
Conclusion:
With default, parameterized, and duplicated constructors, this experiment taught me about Function
Overloading. Overloading of constructors, including default, parameterized, and redundant
constructors, was also handled. The constructor is a feature of programming languages that is used
to make programs more effective and efficient. It's also feasible to think of it as a special kind of
method that has the same name as the class and can be called whenever an object of that class is
created. Depending on the constructor's requirements, one can choose between the default and
parameterized constructors.
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
RIPHAH International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 11: Introduction to Inheritance
OBJECTIVES:

Students will learn about:

• Public inheritance
• Private inheritance
• Protected inheritance

Name: Huzaifa Bin Javaid Sap ID: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: ………………………


Public Inheritance
The limited elements of the header file remain protected in the derived class, while the public
components of the base class become public.
Example:
// C++ program to demonstrate the working of public inheritance
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
// function to access private member
int getPVT() {
return pvt;
}
};
class PublicDerived : public Base {
public:
// function to access protected member from Base
int getProt() {
return prot;
}
};
int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.pub << endl;
return 0;
}
Private Inheritance
Private inheritance in the derived class makes the public and protected members of the base class
private.
Example:
#include <iostream>
using namespace std;
class Base { private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
// function to access private member
int getPVT() {
return pvt;
} };
class PrivateDerived : private Base { public:
// function to access protected member from Base
int getProt() { return prot;
}
// function to access private member
int getPub() {
return pub;
} };
int main() {
PrivateDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl; cout << "Public = " << object1.getPub() << endl;
return 0;
}
Protected Inheritance
The public and protected members of the base class are kept in the derived class thanks to protected
inheritance.
Example:
#include <iostream>
using namespace std;
class Base { private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
// function to access private member
int getPVT() {
return pvt;
} };
class ProtectedDerived : protected Base { public:
// function to access protected member from Base
int getProt() { return prot;
}
// function to access public member from Base
int getPub() {
return pub;
} };
int main() { ProtectedDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Conclusion:
This lab experiment taught me a lot about inheritance, particularly the distinctions between public,
protected, and private inheritance. One of the most significant parts of inheritance is inheritance
hierarchies. Inheritance is one of the most important components of object-oriented programming.
This lab demonstrates how to share variables and member functions using Public, Protected, and
Private variables and member functions.
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 12: Types of Inheritance
OBJECTIVES:

Students will learn about:

Single and multiple Inheritance


Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance

Name: M. Huzaifa Javaid Roll No: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Single and multiple Inheritance:
Single inheritance is one in which the derived class inherits the single base class either publicly,
privately or protected. In single inheritance, the derived class uses the features or members of the
single base class. These base class members can be accessed by derived class or child class
according to the access specifier specified during inheriting the parent class or base class.
Syntax:
Class DerivedClass_name : access_specifier Base_Class
{
//Class's Body
};

Example:

#include<iostream>
using namespace std;
class A {
public:
int k = 7000;
float salary = 600;
};
class B : public A {
public:
float bonus = 4000;
void ts()
{
cout<<"Total salary : "<<(salary + bonus)<<endl;
}
};
int main()
{
B b1;
cout<<"Salary : "<<b1.salary<<endl; cout<<"Bonus : "<<b1.bonus<<endl; b1.ts();
return 0;
}
Multiple Inheritance is one in which the derived class acquires two or more base classes.
In multiple inheritance, the derived class are allowed to use the joint features of the inherited
base classes. Every base class is inherited by the derived class by notifying the separate access
specifier for each of them. The base class members can be accessed by derived class or child class
according to the access specifier specified during inheriting the parent class or base class.
Syntax
Class DerivedClass_name : access_specifier Base_Class1, access_specifier Base_Class2
{
//Class's Body
};
Example

#include<iostream>
using namespace std;
class A {
public:

float salary = 10000;

};
class B {
public:
float bonus = 13000;
};
class C : public A, public B {
public:
void ts()
{
cout<<"Total salary : "<<(salary + bonus)<<endl;
}
};
int main()
{
C b1; b1.ts();
return 0;}

Hierarchical Inheritance:
When several classes are derived from common base class it is called hierarchical inheritance.
In C++ hierarchical inheritance, the feature of the base class is inherited onto more than one sub-
class.
Syntax
class A // base class
{
..............
};
class B : access_specifier A // derived class from A
{
...........
};
class C : access_specifier A // derived class from A
{
...........
};
class D : access_specifier A // derived class from A
{
...........
};

Example
#include <iostream>

using namespace std;

class A
{
public:
int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n"; cin >> x >> y;
}
};
class B : public A
{
public:
void product()
{
cout << "\nProduct= " << x * y;
}
};
class C : public A
{
public:
void sum()
{
cout << "\nSum= " << x + y;
}
};
int main()
{
B obj1; C
obj2;
obj1.getdata();

obj1.product();
obj2.getdata();
obj2.sum();
return 0;
}
Multilevel Inheritance:
If a class is derived from another derived class then it is called multilevel inheritance. So in
C++ multilevel inheritance, a class has more than one parent class.
Syntax
class A // base class

...........

};

class B : acess_specifier A // derived class

...........

};

class C : access_specifier B // derived from derived class B

...........

};
Example
#include <iostream>

using namespace std;

class base
{
public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
}
};
class derive1 : public base
{
public:
int y;
void readdata()
{
cout << "\nEnter value of y= "; cin >> y;
}
};
class derive2 : public derive1
{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= "; cin >> z;
}
void product()
{
cout << "\nProduct= " << x * y * z;
}
};
int main()
{
derive2 a;
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;
}
Hybrid Inheritance:
The inheritance in which the derivation of a class involves more than one form of any inheritance
is called hybrid inheritance. Basically C++ hybrid inheritance is combination of two or more types
of inheritance. It can also be called multi path inheritance.
Syntax
class A
{
.........
};
class B : public A
{
..........
};
class C
{
...........
};
class D : public B, public C
{
...........
};

Example
#include <iostream>
using namespace std;

class A
{

public:
int x;
};
class B : public A
{
public: B()
{

x = 11;
}
};
class C
{

public: int y; C()


{
y = 7;
}
};
class D : public B, public C
{
public:
void sum()
{
cout << "Sum= " << x + y;
}
};
int main()
{
D obj1; obj1.sum(); return 0;
}
Conclusion:
This lab task teaches me about inheritance. One of the most significant aspects of object-oriented
programming is inheritance, and hierarchies of inheritance classes are one of the most important
aspects of inheritance. The concept of inheritance being employed with the base or parent class
via the derived class must now be obvious. There are several types of inheritance, including
single, multiple, multilevel, hierarchical, and hybrid inheritance. implemented and learn by doing
of this lab work.
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 13: Introduction to Polymorphism
OBJECTIVES:

Students will learn about:

Polymorphism
Late binding and virtual function

Name: M. Huzaifa Javaid Roll No: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism, a person at the same time can have different characteristics. Like a man
at the same time is a father, a husband, an employee. So the same person possess different behavior
in different situations. This is called polymorphism. Polymorphism is considered as one of the
important features of Object Oriented Programming.
Implement polymorphism in C++ using the following ways:
Function overloading
Operator overloading
Function overriding
Virtual functions

Function Overloading:
In C++, we can use two functions having the same name if they have different parameters (either
types or number of arguments).
And, depending upon the number/type of arguments, different functions are called.

Example

#include <iostream>

using namespace std;

// Function with 2 int parameters


int sum(int num1, int num2)
{
return num1 + num2;

// Function with 2 double parameters


double sum(double num1, double num2) {
return num1 + num2;

// Function with 3 int parameters


int sum(int num1, int num2, int num3) {

return num1 + num2 + num3;

int main() {

// Call function with 2 int parameters


cout << "Sum 1 = " << sum(5, 1) << endl;

// Call function with 2 double parameters


cout << "Sum 2 = " << sum(6.9, 6.8) << endl;

// Call function with 3 int parameters


cout << "Sum 3 = " << sum(1, 3, 9) << endl;

return 0;

}
Operator Overloading:
In C++, we can overload an operator as long as we are operating on user-defined types like objects
or structures.
We cannot use operator overloading for basic types such as int, double, etc.
Operator overloading is basically function overloading, where different operator functions have
the same symbol but different operands.
And, depending on the operands, different operator functions are executed.

Example
// C++ program to overload ++ when used as prefix

#include <iostream>
using namespace std;

class Count {
private:
int value;

public:

// Constructor to initialize count to 5


Count() : value(5) {}

// Overload ++ when used as prefix


void operator ++() {
value = value + 1;
}

void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;

// Call the "void operator ++()" function


++count1;

count1.display();
return 0;
}

Function Overriding:
In C++ inheritance, we can have the same function in the base class as well as its derived classes.
When we call the function using an object of the derived class, the function of the derived class is
executed instead of the one in the base class.
So, different functions are executed depending on the object calling the function.
Example
// C++ program to demonstrate function overriding

#include <iostream>
using namespace std;

class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// Call print() function of Derived class


derived1.print();

return 0;
}
Virtual Functions:
In C++, we may not be able to override functions if we use a pointer of the base class to point to
an object of the derived class.
Using virtual functions in the base class ensures that the function can be overridden in these cases.
Thus, virtual functions actually fall under function overriding.

Example
// C++ program to demonstrate the use of virtual functions

#include <iostream>
using namespace std;

class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;
// pointer of Base type that points to derived1
Base* base1 = &derived1;

// calls member function of Derived class


base1->print();

return 0;
}
Late binding and virtual function:
Late Binding: (Run time polymorphism) In this, the compiler adds code that identifies the kind
of object at runtime then matches the call with the right function definition. This can be achieved
by declaring a virtual function.
Example
// CPP Program to illustrate late binding
#include<iostream>
using namespace std;

class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base


{
public:
void show() { cout<<"In Derived \n"; }
};

int main(void)
{
Base *bp = new Derived;
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}
Conclusion:
I learned about polymorphism and its several kinds as a result of this lab work. The major subject of
this lab activity is code implementation and fundamental grasp of core ideas. Polymorphism is when
one item has many traits at the same time. Function overloading, operator overloading, function
overriding, and virtual functions are some of the kinds of polymorphism. After this, go through Late
binding concept which is achieved by virtual function.
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: II


Subject: CSL-112 Object Oriented Programming Date: …………….
Experiment 14: Inheritance and Polymorphism [Open Ended]

Name: Huzaifa Bin Javaid Roll No: 23760

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Individual Work 5 Organization/Structure 5
Contributions and
Time Management
Propose/Create 5 5
Multiple Calculations & Data
Solutions Presentation
Total Marks obtained

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………


Inheritance:
In object-oriented programming, inheritance is the mechanism of basing an object or
class upon another object (prototype-based inheritance) or class (class-based inheritance),
retaining similar implementation. An inherited class is called a subclass of its parent class or
super class.

Polymorphism:
Polymorphism means, the same entity ( function or object ) behaves differently in
different scenarios. Consider this example: The “ +” operator in c++ can perform two specific
functions at two different scenarios i.e when the “+” operator is used in numbers, it performs
addition.
Question:
Consider a graphics system that has classes for various figures—say, rectangles, squares, triangles,
circles, and so on. For example, a rectangle might have data members height, width, and center point,
while a square and circle might have only a center point and an edge length or radius, respectively. In
a well-designed system, these would be derived from a common class, Figure. You are to implement
such a system. The class Figure is the base class. You should add only Rectangle and Triangle classes
derived from Figure. Each class has stubs for member functions erase and draw. Each of these
member functions outputs a message telling what function has been called and what the class of the
calling object is. Since these are just stubs, they do nothing more than output this message. The
member function center calls erase and draw to erase and redraw the figure at the center. Because
you have only stubs for erase and draw, center will not do any “centering” but will call the member
functions erase and draw. Also, add an output message in the member function center that
announces that center is being called. The member functions should take no arguments.

There are three parts to this project:

Part a: Do the class definitions using no virtual functions. Compile and test.
Part b: Make the base class member functions virtual. Compile and test.
Part c: Explain the difference in results.

//figure.h
#include "figure.h"

using namespace std;

//Class definition of Triangle

class Triangle: public Figure

public: void draw();

void erase();

};

//Method definition of draw in Triangle class

void Triangle::draw()

cout << "Triangle::draw():Called draw method in the Triangle class." << endl;
}

//Method definition of erase in Triangle class

void Triangle::erase()

cout << "Triangle::erase():Called erase function in the Triangle class." << endl;

//triangle.h
#include "figure.h"

using namespace std;

//Class definition of Triangle

class Triangle: public Figure


{

public: void draw();

void erase();

};

//Method definition of draw in Triangle class

void Triangle::draw()

cout << "Triangle::draw():Called draw method in the Triangle class." << endl;

//Method definition of erase in Triangle class

void Triangle::erase()

cout << "Triangle::erase():Called erase function in the Triangle class." << endl;

}
//rectangle.h

#include "figure.h"

using namespace std;

//Class definition of Rectangle

class Rectangle: public Figure

public: void erase();

void draw();

};

//Method definition of erase in Rectangle class

void Rectangle::erase()

{
cout << "Rectangle::erase():Called erase function in the Rectangle class. " << endl;

//Method definition of draw in Rectangle class

void Rectangle::draw()

cout << "Rectangle::draw():Called draw method in the Rectangle class. " << endl;

//Main CPP
#include "figure.h"

#include "rectangle.h"
#include "triangle.h"

using std::cout;

//main method

int main()

//Create a Triangle Class's object

Triangle tri;

//Call the method, draw

tri.draw();

//Prompt and call the method, center

cout << "\nIn main, Derived class Triangle object calling "<< "center().\n ";

tri.center();

//Create a Rectangle Class's object

Rectangle rect;

rect.draw();

//Prompt and call the method, center

cout << "\nIn main, Derived class Rectangle object calling " << "center().\n ";

rect.center();

//Pause the sytem for a while

system("pause");

return 0;

}
Output
Triangle::draw():Called draw method in the Triangle class.

In main, Derived class Triangle object calling center().

Figure: center(): Called center function in the Figure class.

Triangle::erase():Called erase function in the Triangle class.

Triangle::draw():Called draw method in the Triangle class.

Rectangle::draw():Called draw method in the Rectangle class.

In main, Derived class Rectangle object calling center().

Figure: center(): Called center function in the Figure class.

Rectangle::erase():Called erase function in the Rectangle class.

Rectangle::draw():Called draw method in the Rectangle class.


Huzaifa Bin Javaid OOP Evaluation 23760

Question 1: Implement a base class Appointment and derived classes Onetime, Daily, Weekly,
and Monthly. An appointment has a description (for example, “see the dentist”) and a date and
time. Write a virtual function occurs_on(int year, int month, int day) that checks whether the
appointment occurs on that date. For example, for a monthly appointment, you must check
whether the day of the month matches. Then fill a vector of Appointment* with a mixture of
appointments. Have the user enter a date and print out all appointments that happen on that date.

#include <iostream>
#include <string>
#include <ctime>
#include <vector>
using namespace std;
const int DAYS_PER_MONTH = 30;
class Time
{
public:
Time(int hour, int min, int sec);
Time();
int get_hours() const;
int get_minutes() const;
int get_seconds() const;
int seconds_from(Time t) const;
void add_seconds(int s);
private:
int time_in_secs;
};
int remainder(int i, int k)
{
if (i >= 0)
{
return i % k;
Huzaifa Bin Javaid OOP Evaluation 23760

}
else
{
return k - 1 - (-i - 1) % k;
}
}
Time::Time(int hour, int min, int sec)
{ time_in_secs = 60L * 60 * hour + 60 * min + sec;
}
Time::Time()
{
time_in_secs = 0;
}
int Time::get_hours() const
{
return time_in_secs / (60 * 60);
}
int Time::get_minutes() const
{
return (time_in_secs / 60) % 60;
}
int Time::get_seconds() const
{
return time_in_secs % 60;
}
int Time::seconds_from(Time t) const
{
return time_in_secs - t.time_in_secs;
Huzaifa Bin Javaid OOP Evaluation 23760

}
void Time::add_seconds(int s)
{
const int SECONDS_PER_DAY = 60 * 60 * 24;
time_in_secs = remainder(time_in_secs + s, SECONDS_PER_DAY);
}
class Date
{
public:
Date();
Date(int y, int m, int d);
void print() const;
bool equals(Date other) const;
private:
int day;
int month;
int year;
};
Date::Date()
{
day = 1;
month = 1;
year = 1;
}
Date::Date(int y, int m, int d)
{
day = d;
month = m;
Huzaifa Bin Javaid OOP Evaluation 23760

year = y;}
void Date::print() const
{
cout << year << "/" << month << "/" << day;
}
bool Date::equals(Date other) const
{
return day == other.day && month == other.month
&& year == other.year;
}
class Appointment
{
public:
Appointment();
Appointment(string desc, Time s, Time e);
void print() const;
void read();
virtual bool occurs_on(int year, int month, int day) const;
private:
string description;
Time start;
Time end;
};
Appointment::Appointment()
{
}
Appointment::Appointment(string desc, Time s, Time e)
{
Huzaifa Bin Javaid OOP Evaluation 23760

description = desc;
start = s;
end = e;
}
void Appointment::print() const
{
cout << " " << start.get_hours() << ":";
if (start.get_minutes() < 10) cout << "0";
cout << start.get_minutes()
<< " - " << end.get_hours() << ":";
if (end.get_minutes() < 10) cout << "0";
cout << end.get_minutes() << " " << description << "\n";
}
void Appointment::read()
{
int sh;
int sm;
int eh;
int em;
cout << "Enter start_hours start_minutes end_hours end_minutes description:\n";
cin >> sh >> sm >> eh >> em;
getline(cin, description); start = Time(sh, sm, 0);
end = Time(eh, em, 0);
}
bool Appointment::occurs_on(int year, int month, int day) const
{
return false;
}
Huzaifa Bin Javaid OOP Evaluation 23760

class Onetime : public Appointment


{
public:
Onetime();
Onetime(string desc, Date d, Time s, Time e);
void read();
virtual bool occurs_on(int year, int month, int day) const;
private:
Date when;
};
Onetime::Onetime()
{
}
Onetime::Onetime(string desc, Date d, Time s, Time e)
: Appointment(desc, s, e)
{
when = d;
}
void Onetime::read()
{
Appointment::read();
cout << "Enter year month day: ";
int year;
int month;
int day;
cin >> year >> month >> day;
when = Date(year, month, day);}
bool Onetime::occurs_on(int year, int month, int day) const
Huzaifa Bin Javaid OOP Evaluation 23760

{
return when.equals(Date(year, month, day));
}
class Daily : public Appointment
{
public:
Daily();
Daily(string desc, Time s, Time e);
virtual bool occurs_on(int year, int month, int day) const;
};
Daily::Daily()
{
}
Daily::Daily(string desc, Time s, Time e)
: Appointment(desc, s, e){
}
bool Daily::occurs_on(int year, int month, int day) const
{
return true;
}
class Monthly : public Appointment
{
public:
Monthly();
Monthly(string desc, int d, Time s, Time e);void read();
virtual bool occurs_on(int year, int month, int day) const;
private:
int day;
Huzaifa Bin Javaid OOP Evaluation 23760

};
Monthly::Monthly()
{
}
Monthly::Monthly(string desc, int d, Time s, Time e)
: Appointment(desc, s, e)
{
day = d;
}
void Monthly::read()
{
Appointment::read();
cout << "Enter day: ";
int d;
cin >> d;
day = d;
}
bool Monthly::occurs_on(int year, int month, int d) const
{
return day == d;
}
int main()
{
vector<Appointment*> schedule(7);

schedule[0]= new Daily("brush my teeth", Time(6,0,0),


Time(6, 5, 0));
schedule[1]= new Daily("Morning Excercise", Time(7,0,0),
Huzaifa Bin Javaid OOP Evaluation 23760

Time(7, 30, 0));


schedule[2]= new Daily("Daily office Meeting", Time(8,0,0),
Time(8, 30, 0));
schedule[3]= new Daily("lunch Meeting", Time(14,0,0),
Time(14, 30, 0));
schedule[4]= new Onetime("Doctor`s Appointment",
Date(2021, 12, 5),
Time(15, 30, 0), Time(16, 30, 0));
schedule[5]= new Daily("Meet with friends ", Time(20,0,0),
Time(22, 0, 0));

schedule[6]= new Monthly("clean the house", 5,


Time(19,0,0), Time(19, 30, 0));

cout << "please enter date to check your appointments (yyyy mm dd): ";
int year;
int month;
int day;
cin >> year >> month >> day;
cout << " your appointments for the day are : " << "\n"; for (int i = 0; i < schedule.size(); i++)
{
if (schedule[i]->occurs_on(year, month, day))
{
schedule[i]->print();
}
}
return 0;
}
Huzaifa Bin Javaid OOP Evaluation 23760

Question 2: Implement a class StreetAddress. An address has a house number, a street, an


optional apartment number, a city, a state, and a postal code. Supply two constructors: one with
an apartment number and one without. Supply a print member function that prints the address
with the street (and optional apartment number) on one line and the city, state, and postal code
on the next line. Supply a member function comes_before that tests whether one address comes
before another when the addresses are compared by postal

#include<iostream>
using namespace std;
class StreetAddress
{
private:
int houseNumber[3];
int street[3];
int apartmentNum[3];
string city;
string state;
int postalCode[3];
public:
Huzaifa Bin Javaid OOP Evaluation 23760

StreetAddress(int n)
{
apartmentNum [3]= n;
}
StreetAddress() {
}
void setAddress(int apart, int house, int str, string ct, string st, int code,int i)
{
cout << str << endl;
apartmentNum [i] = apart;
houseNumber[i] = house;
city = ct;
street[i] = str;
state = st;
postalCode[i] = code;
}
void printAddress(int i)
{
cout << "Street is: " << street[i] << " , apartment is: " << apartmentNum[i] <<", House Number
is: " << houseNumber[i] << endl;
cout << "Street is: " << street[i] << ", House Number is: " << houseNumber[i]
<< endl;
cout << "City: " << city << " , State: " << state << " , postalCode: " <<
postalCode[i] << endl <<endl;}
void checkAddressFirstCome()
{
cout << "Now we checking that which address comes first and also checking that which postal
code is larger. "<< endl<<endl;
int max = postalCode[0];
Huzaifa Bin Javaid OOP Evaluation 23760

int ind = 123;


for (int i = 0; i < 3 ;i++)
{
if (max < postalCode[i])
{
max = 47040;

}
}
cout << "Larger postal code is " << max << endl;
cout << "house number comes first is 123" << endl;
}
};
int main()
{
StreetAddress S1;
int aprt[3] = { 311,723,345 }, houseN[3] = { 721,123,421 }, strt[3] = { 10,7,25 }, postalCode[3]=
{ 31143,47040,28028 };
string cit, cit2, cit3, stat;
StreetAddress S2;
StreetAddress S3;
cit = "Wah Cantt";
cit2 = "Rawalpindi";
cit3 = "Sialkot";
stat = "Punjab";
S1.setAddress( aprt[0], houseN[0], strt[0], cit, stat, postalCode[0],0);
S1.printAddress(0);
S2.setAddress( aprt[1], houseN[1], strt[1], cit2, stat, postalCode[1], 1);
Huzaifa Bin Javaid OOP Evaluation 23760

S2.printAddress(1);
S3.setAddress( aprt[2], houseN[2], strt[2], cit3, stat, postalCode[2], 2);S3.printAddress(2);
S2.checkAddressFirstCome();
system("pause");
return 0;
}

Question 3: Find the mistakes in the following code. Not all lines contain mistakes. Each line
depends on the lines preceding it. Watch out for uninitialized pointers, NULL pointers, pointers
to deleted objects, and confusing pointers with objects.
Huzaifa Bin Javaid OOP Evaluation 23760

Question 4: Write a program that prints a paycheck. Ask the program user for the name of the
employee, the hourly rate, and the number of hours worked. If the number of hours exceeds 40,
the employee is paid “time and a half”, that is, 150 percent of the hourly rate on the hours
exceeding 40. Be sure to use step wise refinement and break your solution into several functions.
Use the int name function to print the dollar amount of the check. #include <iostream>

#include<string.h>
using namespace std;
float hours;
float hourly_wage;float total_pay;
float overtime_pay;
float max_hours=40;
string fname;
void user_data();
void calculations();
int name();
int main()
{
cout<< "Please enter your name : ";
cin>>fname;
cout<< "Enter the hours worked in a week : ";
cin>>hours;
cout<< "Enter hourly wage : $";
cin>>hourly_wage;
user_data();
calculations();
name();
Huzaifa Bin Javaid OOP Evaluation 23760

system ("pause");
return 0;
}
void user_data()
{ cout<<"\n";
cout<< "------------------Employee Information--------------"<<endl;
cout<< "Name : "<<fname<<endl;
cout<< "Time worked by employee in one week : "<<hours<<endl;
cout<< "Hourly wage of employee : $ "<< hourly_wage<<endl;
}
void calculations ()
{
if (hours>40)
{
cout<< "Overtimed hours in week : "<<hours-40<< " hours" <<endl;
cout<< "Actual Salary : $"<< max_hours*hourly_wage<<endl;
cout<< "Overtime Salary : $"<< (hours-40)*(1.5*hourly_wage)<<endl;
overtime_pay=(hours-40)*(1.5*hourly_wage);
total_pay=max_hours*hourly_wage+overtime_pay;
cout<< "Total pay is : $"<<total_pay<<endl;
} else if (hours<=40)
{
cout<< "Actual Salary : $"<< hours*hourly_wage<<endl;
cout<< "Overtime hours : "<< endl;
total_pay=hourly_wage*hours;
cout<< "Total pay is : $"<< total_pay<<endl;
}
}
Huzaifa Bin Javaid OOP Evaluation 23760

int name ()
{
cout<< "<-----------------<Pay Check>----------------->"<<endl;
cout<< "\n";
cout<< "Employee Name : "<<fname<<endl;
cout<< "Total Salary : $"<< total_pay<<endl;
cout<< "\n";
cout<< "--------------------GOOD BYE------------------"<<endl;
return 0;
}

You might also like