Professional Documents
Culture Documents
Lab Manual: Department of Electrical Engineering
Lab Manual: Department of Electrical Engineering
Lab Manual
CSL-112 Object Oriented Programming Lab
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.
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
Date: 15-07-21
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
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
2. Lab Viva
Performance
Sr.#
Indicator Exemplary (4-5) Satisfactory (2-3) Unsatisfactory (0-1)
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
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
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
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)
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 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
• Conditional Statements
• Control Structures
• Selection (IF-ELSE, NESTED IF)
• Rational and Logical (Boolean) Operators
• Selection (SWITCH)
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.
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:
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>
int main() {
char op;
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>
int main()
double hours;
double minutes;
float hourly_wage;
float computed_pay;
float overtime_pay;
cin>> last;
cout << "Employee: " << first << " " << last << endl;
<< ", " << minutes << " minutes" << endl;
return 0;
}
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
RIPHAH International University, Islamabad, Pakistan
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.
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:
do
statement
while (condition);
where
condition is the condition that must hold true for the loop to execute.
Lab Task 2:
Program & Execution:
In terms of structure, this loop differs from both the "while" and "do-while" loops.
Initialization.
Condition.
Increment or decrement.
Body of the loop.
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
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>
int main()
int N ;
cin>>N;
int M = N;
{
Huzaifa Bin Javaid Evaluation 2 23760
M++;
system("pause");
return 0;
}
Department of Electrical Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan
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.
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.
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.
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: 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(){
int i,j,sum,avg;
{
Huzaifa Bin Javaid Evaluation 3 23760
cout << "n[" << j << "] = " << n[j] << endl;
n[0] = n[i];
avg = sum / 10; // to take out the average of all elements of array//
return 0;
}
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
#include <iostream>
#include <iomanip>
int main ()
int A[4][4]={0};
int r, c;
}
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>
int main ()
int A[4][4]={0};
{
Huzaifa Bin Javaid Evaluation 4 23760
A[i][j]= 30;
else
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++) //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(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
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(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
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 << A[i][j] << " ";
}
cout << endl;
}
Huzaifa Bin Javaid Evaluation 4 23760
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 << 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 ;
}
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;
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
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>
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;
cin>> n;
cin>>a[i].name;
cin>>a[i].comid;
cin>>a[i].ageemp;
cin>>a[i].salary;
Huzaifa Bin Javaid Evaluation 5 23760
cout<<endl<<endl;
cin>> w;
if (a[i].comid == w){
return 0;
Conclution:
In this lab I have learnt about the structure what is it how to use it
• Value-Returning Functions
• Function calls
• Programming Example: Largest Number, Add, Subtract, Multiply of two numbers.
• Implementation of DeMorgon’s law
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;
1) F = y * y + x / y;
2) D = x / y - x * x;
3) G =x* y – x + y* y;
#include<iostream>
Huzaifa Bin Javaid Evaluation 6 23760
int main()
int x,y,s,d,m,sub,f,df,D,dd,g,dg;
cin>>x;
cin>>y;
s=sum(x,y);
sub=subtract(x,y);
d=div(x,y);
m=mul(x,y);
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));
return 0;
int total;
total=a+b;
return total;
int total;
total=a-b;
return total;
int total;
total=a/b;
return total;
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
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.
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
#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;
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
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>
• Function Overloading
• Default and Parameterized Constructor
• Copy constructor
void print(double y) {
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
• Public inheritance
• Private inheritance
• Protected inheritance
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:
};
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>
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
...........
};
...........
};
...........
};
Example
#include <iostream>
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
{
Polymorphism
Late binding and virtual function
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>
int main() {
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:
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count 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;
}
};
int main() {
Derived derived1;
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;
}
};
int main() {
Derived derived1;
// pointer of Base type that points to derived1
Base* base1 = &derived1;
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"; }
};
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
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.
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"
void erase();
};
void Triangle::draw()
cout << "Triangle::draw():Called draw method in the Triangle class." << endl;
}
void Triangle::erase()
cout << "Triangle::erase():Called erase function in the Triangle class." << endl;
//triangle.h
#include "figure.h"
void erase();
};
void Triangle::draw()
cout << "Triangle::draw():Called draw method in the Triangle class." << endl;
void Triangle::erase()
cout << "Triangle::erase():Called erase function in the Triangle class." << endl;
}
//rectangle.h
#include "figure.h"
void draw();
};
void Rectangle::erase()
{
cout << "Rectangle::erase():Called erase function in the Rectangle class. " << endl;
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()
Triangle tri;
tri.draw();
cout << "\nIn main, Derived class Triangle object calling "<< "center().\n ";
tri.center();
Rectangle rect;
rect.draw();
cout << "\nIn main, Derived class Rectangle object calling " << "center().\n ";
rect.center();
system("pause");
return 0;
}
Output
Triangle::draw():Called draw method in the Triangle class.
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
{
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);
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
#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
}
}
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;
}