Computer Programming C++ Solved Labs
Computer Programming C++ Solved Labs
Programming
Practical Lab File
Submitted By:
Ehsan Awan
04 9/3/09 04 Loops
05 16/3/09 03 Arrays
07 13/4/09 04 Function-l
08 04 Function-ll
12 04 Pointers
Lab # 01
Flow Chart
Exercise no 01 (grades)
Draw a flowchart to read a student’s three grades, calculate the average of the grades, then display
the average grade.
Solution:
START
INPUT A
INPUT B
INPUT C
SUM =
A+B+C
DISPLAY
SUM
AVERAGE =
SUM/3
DISPLAY
AVERAGE
END
Exercise no 02 (volume)
Draw a flowchart for a program that reads the height, length, and width of a rectangular box,
calculates and displays the volume. Note: volume = lwh
Solution:
START
INPUT
HEIGHT(H)
INPUT
WIDTH
(W)
INPUT
LENGTH(L)
VOLUME =
H*W*L
DISPLAY
VOLUME
END
Solution:
START
INPUT A
NUMBER
X
VALUE IS
X=0 YES
0
NO
VALUE IS
X>0 YES END
+VE
NO
VALUE IS
X<0 YES
-VE
NO
INPUT ERROR
Exercise no 04 (Salary)
Solution:
START
INPUT
SALARYX
NO
NO
NO
INPUT ERROR
Exercise no 05 (Prediction)
We would like to predict the size of an insect population for the week 3 and 4 based on data for
week 1 and 2. The weekly rate of growth is a percentage of the population at the beginning of
the week. Draw flow chart of this problem.
Solution:
START
INPUT
X AND SUM = X+Y
Y
DISPLAY AVERAGE =
SUM SUM/2
DISPLAY W4= Y+
AVERAGE AVERAGE
W3 = X+ DISPLAY
AVERAGE W4
DISPLAY
END
W3
Lab # 02
Data Types
Question: Write a program that takes 3 values from user. Two values of
integer and one value of float data type. Print each result on one line.
Source code:
#include<iostream>
int main(){
int a,b;
float c;
cin>>a>>b>>c;
cout<<"Your Values Is "<<a<<" "<<b<<" "<<c;
return 0;
//output:
Question: Write a program that gets 2 integers input from user and store them
in variables. Do the five basic Arithmetic Operations (+ , - , *, /, %) of the two
numbers. Print the results of operations.
Source code:
#include<iostream>
using namespace std;
int main(){
int v1,v2,add,sub,mul;
float a,b,div,m;
add=v1+v2;
sub=v1-v2;
mul=v1*v2;
div=a/b;
m=v1%v2;
cout<<v1<<"+"<<v2<<"="<<add<<endl;
cout<<v1<<"-"<<v2<<"="<<sub<<endl;
cout<<v1<<"*"<<v2<<"="<<mul<<endl;
cout<<v1<<"/"<<v2<<"="<<div<<endl;
cout<<v1<<"%"<<v2<<"="<<m<<endl;
return 0;
}
Output:
Exercise 3: Percentage
Question: Write a program that prompt user to input course name, obtained
marks and total marks. Calculate the percentage using this formula marks
percentage = marks obtained / total * 100
and display.
Source Code:
#include<iostream>
using namespace std;
using std::string;
int main(){
float x,b,c;
c=x/b*100;
return 0;
}
//OUTPUT:
Question: Write a program that finds the value of X by using given formula. Take
value of a and b from user.
X= (a + b)2 – 2ab
Source Code:
#include<iostream>
using namespace std;
int main(){
float x,a,b;
x=(a+b)*2-2*a*b;
long y,c,d=2018;
string x;
cout<<"What is your name? : "<<x;
cin>>x;
string b;
cout<<"Name of University : "<<b;
cin>>b;
string z;
cout<<"Favourite hobby : "<<z;
cin>>z;
string a;
cout<<"Pet's name : "<<a;
cin>>a;
c=d-y;
cout<<"\"There live a person name "<<x<<" who is currently "<<c<<" year of ago.
"<<x<<" is studing at "<<b<<". It"
" is interesting because "<<x<<" like to "<<z<<" with "<<a<<" and they lived happily ever
after!\"";
return 0;
}
//output:
Exercise no 06
Question: Write a C++ program that prompt user to enter value of X and Y.
You have to calculate the value of Hypotenuse (h) and Area (a).
Source Code:
#include<iostream>
using namespace std;
#include<math.h>
int main(){
float x,a,b,c,d,h,y;
b=x*x;
c=y*y;
d=c+b;
h=sqrt(d);
a=x*y*1/2;
cout<<"Hypotenuse = "<<h<<endl;
cout<<"Area = "<<a;
return 0;
}
//output:
Lab # 03
Decision Statement
Exercise 01
Question: Write a C++ Program that read a float (amount) and an int (num) input
from user. Add both (amount and num) numbers and store them in two different
int (a) and float (b) variables. Display the outputs of a and b variables. Also if
outputs are greater than 16 print “value of a & b > 16” else print “value of a & b <
16”.
Source code:
#include<iostream>
using namespace std;
int main(){
int a,x;
float b;
float c;
c=a+b;
x=c;
if(c>16){
cout<<"value of a & b > 16";
}
else{
cout<<"value of a & b < 16";
}
return 0;
}
//output:
Exercise 02
Question: Write a C++ Program that read three input from user and returns the
smallest one.
Source code:
#include<iostream>
using namespace std;
int main(){
int x,y,z;
if(y<x&&y<z){
cout<<y<<" is smallest one";
}
if(z<x&&z<y){
cout<<z<<" is smallest one";
}
return 0;
}
//output:
Exercise 03
Question: Write a C++ Program that read an alphabet (e.g. a,b,c,d,…..z) and
display whether the input alphabet is a vowel (i.e. a, e, i, o, u) or consonant.
Source code:
#include<iostream>
using namespace std;
int main(){
char choice;
if(choice=='a'||choice=='e'||choice=='i'||choice=='o'||choice=='u'){
return 0;
}
//output:
Exercise 04
Question: Write a C++ Program that read a number from user .Test the user
entered number whether it is EVEN or ODD. Print the message that number is
EVEN or ODD.
Source code:
#include<iostream>
using namespace std;
int main(){
int x;
if(x%2==0){
cout<<"The number is even ";
}
else{
cout<<"This number is odd ";
}
return 0;
}
//output:
Exercise 05
Question: Write a C++ Program that read an integer input in between (1 to 12)
and store it month_of_year. Print the corresponding month of year. Use else if
statement. Example: Input is 4… Print “April”
Source code:
#include<iostream>
using namespace std;
int main(){
int a;
cout<<"Enter your number between (1 to 12): ";
cin>>a;
if(a==1){
cout<<"January";
}
else if(a==2){
cout<<"February";
}
else if(a==3){
cout<<"March";
}
else if(a==4){
cout<<"April";
}
else if(a==5){
cout<<"May";
}
else if(a==6){
cout<<"June ";
}
else if(a==7){
cout<<"July";
}
else if(a==8){
cout<<"August";
}
else if(a==9){
cout<<"September";
}
else if(a==10){
cout<<"October";
}
else if(a==11){
cout<<"November";
}
else if(a==12){
cout<<"December";
}
else if(a>12){
cout<<"Error"<<endl;
cout<<"Your enter value is not between 1 to 12 ";
}
return 0;
}
//output:
Exercise 06
Question: Rewrite exercise 5 using switch statement.
Source code:
#include<iostream>
using namespace std;
int main(){
int a;
cout<<"Enter your number between (1 to 12): ";
cin>>a;
switch (a)
{
case 1:
cout<<"January";
break;
case 2:
cout<<"February";
break;
case 3:
cout<<"March";
break;
case 4:
cout<<"April";
break;
case 5:
cout<<"May";
break;
case 6:
cout<<"June";
break;
case 7:
cout<<"July";
break;
case 8:
cout<<"August";
break;
case 9:
cout<<"September";
break;
case 10:
cout<<"October";
break;
case 11:
cout<<"November";
break;
case 12:
cout<<"December";
break;
default:
cout<<"Error"<<endl;
cout<<"Your enter value is not between 1 to 12 ";
}
return 0;
}
//output:
Exercise 07
Question: Write a C++ Menu driven program that allows a user to enter 3
numbers and then choose between findings the smallest, largest, sum or average.
Use else if statement to determine what action to take.
Sourcr code:
#include<iostream>
using namespace std;
int main(){
float a,b,c,x,y;
else if(b>a&&b>c){
cout<<"Your largest value is "<<b<<endl;
}
else if(c>b&&c>a){
cout<<"Your largest value is "<<c<<endl;
}
else if(b<a&&b<c){
cout<<"Your smallest value is "<<b<<endl;
}
else if(c<b&&c<a){
cout<<"Your smallest value is "<<c<<endl;
}
x=a+b+c;
y=x/3;
return 0;
}
//output:
Exercise 08
Question: Rewrite exercise 7 using swtich statement
Source code:
#include<iostream>
using namespace std;
int main(){
float a,b,c,x,y;
int d,e,f,g;
cout<<"Enter your 1st number : ";
cin>>a;
d=a>b&&a>c;
e=b>a&&b>c;
f=a<b&&a<c;
g=b<a&&b<c;
case 1:
cout<<"Your largest value is "<<a<<endl;
break;
case 0:
{switch(e)
{
case 1:
cout<<"Your largest value is "<<b<<endl;
break;
case 0:
cout<<"Your largest value is "<<c<<endl;
break;
}
}
}
//ye smallest value ka hai
switch(f)
{
case 1:
cout<<"Your smallest value is "<<a<<endl;
break;
case 0:
{switch(g)
{
case 1:
cout<<"Your smallest value is "<<b<<endl;
break;
case 0:
cout<<"Your smallest value is "<<c<<endl;
break;
}
}
x=a+b+c;
y=x/3;
return 0;
}
//output:
Lab # 04
Loops
Exercise: 01
Write a C++ program to print the following pattern on the screen. Ask user to enter a integer
value from 1 to 10. Use while loop.
Sourcecode:
#include <iostream>
using namespace std;
int main()
{
int a,i,j;
cout<<"enter an integer between 1 to 10"<<endl;
cin>>a;
i=a;
while(i>=1)
{ //for(i=a;i>=1;i--){
j=i;
while(j>=1) // for(j=i; j>=1; j--){
{
cout<<"x "; // cout<<"x ";
j--; //}
}
cout<<endl; // cout<<endl; }
i--;
}
return 0;
}
Output:
Exercise: 02
int main(){
int a=1,b=100;
while (a<=b){
cout<<a<<" ";
a++;
return 0;
Output:
B: Modify your program in part (a) to make it prints odd numbers within 1 to 100.
Sourcecode:
#include<iostream>
using namespace std;
int main(){
int a=1,b=100;
while (a<=b){
cout<<a<<" ";
a=a+2;
}
return 0;
}
Output:
C: Write a C++ Program that receives a positive integer (N) and prints a series of numbers from
1 to N (inclusive) in ascending order.
Sourcecode:
#include<iostream>
using namespace std;
int main(){
int a=1,b=100;
while (a<=b){
cout<<a<<" ";
a=a+1;
}
return 0;
}
Output:
D: Write a C++ Program that displays a series of alphabets in descending order from ‘Z’ to ‘A’.
Sourcecode:
#include<iostream>
int main(){
char a='Z';
while (a>='A'){
cout<<a;
a--;
return 0;
Output:
E: Modify your program in part (d) so that the program will display consonants only, no
vowels.
Sourcecode:
#include<iostream>
using namespace std;
int main(){
char a='Z';
while (a>='A'){
if(a!='A'&&a!='E'&&a!='I'&&a!='O'&&a!='U'){
cout<<a<<" ";
}
a--;
return 0;
}
Output:
F: Write a C++ program that receives start value and end value. Then, your program will
display a series of numbers from the start value to the end value inclusive.
Sourcecode:
#include<iostream>
using namespace std;
int main(){
int a,b;
while(a<=b)
{
cout<<a<<" ";
a++;
return 0;
}
Output:
Exercise: 03
Write a C++ program that take two numbers from user, min and max. Use do-while to make
sure that the user enters the smaller value first. Then your program will compute the sum of all
integer numbers from min to max. Use do While loop.
Sourcecode:
#include<iostream>
using namespace std;
int main(){
int a,b,c;
do{
c=c+a;
a++;
}while(a<=b);
cout<<c<<endl<<"Thank You!!";
}
else if(a>b){
cout<<" Wrong input please try again ";
}
return 0;
}
Output:
Exercise: 04
Write a C++ program that takes a positive integer from user and store it in variable
posNumber. Follow these conditions;
If the number is less than 1, print wrong input.
If it is 1, print its value.
If value is greater than 1, check the value is it Even or Odd.
If it is Even, half it and print.
If it is Odd, multiply it by 3 and print result.
Repeat the whole process until user enter 1.
Sourcecode:
#include<iostream>
int main(){
int a,b,c;
while(1>0){
if(a==1){
c=1;
if(c==1){
cout<<"Thank You";
break;
cin>>a;
if(a<1){
else if(a>1){
if(a%2==0){
b=a/2;
cout<<"value is "<<b<<endl;}
else if(a%2==1){
b=a*3;
cout<<"value is "<<b<<endl;
return 0;
Output:
Lab # 05
Arrays
EXERCISE 01
Write a C++ program that ask user to enter 10 integer values. Store those values in one
dimension array. Create another one dimension array of same size, and store the values of first
array in reverse order.
SOURCE CODE:
#include<iostream>
using namespace std;
int main(){
int a[10],i=0,b[10],j=0,d=9;
while(i<10){
cin>>a[i];
b[d]=a[i];
d--;
i++;
}
while(j<10){
cout<<a[j]<<" ";
j++;
}
cout<<endl;
cout<<" Matric A = Reverse "<<endl;
cout<<"================================================"<<endl;
cout<<" ";
d=0;
while(d<10)
{cout<<b[d]<<" ";
d++;
}
return 0;
}
OUTPUT:
EXERCISE 02
Write a C++ Program that checks whether the two arrays are equal or not. Declare two Integer
Arrays with 7 elements, and fill up the array with keyboard input. Test if every element in Array 1
is equal to corresponding element in Array 2. For example, the program should check A[0] =
B[0], A[0] = B[0], and so for.
SOURCECODE:
#include<iostream>
using namespace std;
int main(){
int a[7],i=0,b[7],j=0,d=0;
while(i<7){
cout<<"Element "<<i+1<<" in A : ";
cin>>a[i];
i++;
}
cout<<"===================="<<endl;
i=0;
while(i<7){
cout<<"Element "<<i+1<<" in B : ";
cin>>b[i];
i++;
}
for(i=0;i<7;i++)
{
if(b[i]==a[i]){
d++;
}
cout<<"===================="<<endl;
if(d==7){
cout<<"All Elements of arrays are same";
}
else if(d==0){
cout<<"No Elements of arrays are same";
}
else if(d>0){
cout<<d<<" arrays are same. (or are not same)";
}
return 0;
}
OUTPUT:
EXERCISE 03
Write a C++ Program, ask user to enter 10 integer values. Display its data graphically
by plotting each numeric value as a bar of asterisks (*).
SOURCECODE:
#include<iostream>
#include<iomanip>
int main(){
int a[10],i=0,j=1;
while(i<10){
cin>>a[i];
i++;
cout<<"===================="<<endl;
cout<<"Element\tValue\tHistrogram"<<endl;
i=0;
while(i<10)
cout<<i<<"\t"<<setw(1)<<a[i]<<"\t";
for(j=1;j<=a[i];j++){
cout<<"*";
cout<<endl;
i++;
return 0;
OUTPUT:
Lab # 06
Multi-dimensional Array
Exercise 01
Write a C++ Program that computes the sum of two matrices. Each matrix is of 2 rows and2
columns and will be created from user input.
Code:
#include<iostream>
int a[2][2],i=0,j=0,b[2][2],c[2][2];
while(i<2){
j=0;
while(j<2){
cin>>a[i][j];
j++;
i++;
cout<<"==========================="<<endl;
i=0;
while(i<2){
j=0;
while(j<2){
cin>>b[i][j];
j++;
i++;
}
i=0;
while(i<2){
j=0;
while(j<2){
c[i][j]=a[i][j]+b[i][j];
j++;
i++;
cout<<"A=\t"<<a[0][0]<<"\t"<<a[0][1]<<"\t"<<"+\t"<<"B=\t"<<b[0][0]<<"\t"<<b[0][1]
<<"\t"<<"=\tC=\t"<<c[0][0]<<"\t"<<c[0][1]<<"\t\n";
cout<<"\t"<<a[1][0]<<"\t"<<a[1][1]<<"\t\t"<<"\t"<<b[1][0]<<"\t"<<b[1][1]<<"\t"<<"\t\t
"<<c[1][0]<<"\t"<<c[1][1]<<"\t\n";
return 0;
}
output:
Exercise 02
Write a C++ program to calculate the result of three sections of a semester. Following are the
rules for result:
1. Three are 3 sections.
2. Each section has 8 students.
3. Each student takes 5 courses.Marks for each subject of every student of each section must be
taken from the user.Calculate the result of every student of each section as follows:
1. Obtained marks (Sum of all courses marks). Max. marks of each subject are 100
2. Percentage
Code:
#include<iostream>
using namespace std;
int main(){
int a[3][5][8],i,j,k,b,c,d;
float sum=0,per=0;
while(i<3){
j=0;
if(i==0){
cout<<"\n\tSection A Students Marks\n\n";
}
else if(i==1){
cout<<"\n\tSection B Students Marks\n\n";
else if(i==2){
cout<<"\n\tSection C Students Marks\n\n";
}
while(j<5){
k=0;
while(k<8){
cout<<"Enter Student "<<j+1<<" Marks of course "<<k+1<<" : ";
cin>>a[i][j][k];
while(a[i][j][k]>100){
cout<<"Error please enter Right number (which are
less and equal than 100)\n";
cout<<"Enter Student "<<j+1<<" Marks of course
"<<k+1<<" : ";
cin>>a[i][j][k];
}
k++;
}
cout<<endl;
j++;
}
c=0;
while(c<5){
d=0;
sum=0;
per=0;
while(d<8){
sum=sum+a[i][c][d];
d++;
}
cout<<endl;
cout<<"Obtaine Marks of student "<<c+1<<" is "<<sum<<" out of
800\n";
per=sum*100.0/800.0;
c++;
}
cout<<"\n============================================\n\n";
i++;
}
return 0;
}
Output
Exercise 03
Write a C++ program, that read 12 integer values from user, store values in Matrix of 4 X 3.
Create another Matrix of 4 X 3, divide each element of Matrix1 by five, and store the result
in the Matrix2.
Code:
#include<iostream>
using namespace std;
int main(){
int a[4][3],i=0,j=0,b[4][3];
while(i<4){
j=0;
while(j<3){
cout<<"Enter ["<<i<<"]["<<j<<"] of Matrix A: ";
cin>>a[i][j];
j++;
}
i++;
cout<<"\n\n\n==================================="<<endl;
cout<<"\tMatrix A – Original\n";
cout<<"===================================\n"<<endl;
i=0;
while(i<4){
j=0;
cout<<"\t";
while(j<3){
cout<<a[i][j]<<"\t";
j++;
}cout<<endl;
i++;
}
cout<<"\n==================================="<<endl;
cout<<"\tMatrix A – Divided by 5\n";
cout<<"===================================\n"<<endl;
i=0;
while(i<4){
j=0;
cout<<"\t";
while(j<3){
b[i][j]=a[i][j]/5;
cout<<b[i][j]<<"\t";
j++;
}cout<<endl;
i++;
return 0;
}
OUTPUT:
Lab # 07
Functions
Exercise: 01
Write a C++ Program that contains one user defined function month().
In main() function:
O Read an integer input in between (1 to 12) and store it month_of_year.
O Call month(month_of_year)
In month() function:
oPrint the corresponding month of year in month().
O Example: Value of parameter is 4... Print “April”.
Source Code:
#include<iostream>
using namespace std;
int month(int v1){
if(v1==1)
{cout<<" Jan ";
}
else if (v1==2)
{
cout<<" Feb ";
}
else if(v1==3)
{cout<<" Mar ";
}
else if(v1==4)
{cout<<" April ";
}
else if(v1==5)
{cout<<" May ";
}
else if(v1==6)
{cout<<" June ";
}
else if(v1==7)
{cout<<" July ";
}
else if(v1==8)
{cout<<" August ";
}
else if(v1==9)
{cout<<" September ";
}
else if(v1==10)
{cout<<" October ";
}
else if(v1==11)
{cout<<" November ";
}
else if(v1==12)
{cout<<" December ";
}
else if(v1>12)
{cout<<"Error "<<endl<<"your enter numeric value is above 12 you again learn month
names ";
}
int main(){
int a;
cout<<"enter your number : ";
cin>>a;
month(a);
Output:
Exercise: 02
Write a C++ Program that contains one user defined function cal_grades().
In main() function:
O Prompt user to enter obtained(0 -100) marks for one subject.
O Call cal_grades(marks_subject).
O Print the corresponding Grade with respect to Marks.
In user defined function
O Perform conditioning with else if statement return char value.
O Function must return value.
Source code:
#include<iostream>
using namespace std;
int b;
}
else if(marks_of_subject<60){
a='D';
}
else if(marks_of_subject<65){
a='C';
b=1;
}
else if(marks_of_subject<72){
a='C';
}
else if(marks_of_subject<79){
a='B';
}
else if(marks_of_subject<87){
a='B';
}
else if(marks_of_subject>=88){
a='A';
}
return a ;
int main(){
float a;
char c;
cout<<"enter your number : ";
cin>>a;
cout<<"Your Grade is ";
c=cal_grade(a);
cout<<c;
if(a>=80&&a<=86)
{
cout<<"+";
}
Output:
Exercise 03
Write a C++ Program that contains four user defined function(s) plus(), minus(), multiply(),
divide().
In main() function:
O Get two numbers from user
O Call four user defined fuctions
O Print the result from plus(), minus(), multiply(), divide().
In user defined functions:
O Plus and Minus function get two interger values and return interger.
O Multiply and Divide functions get two interge values and return float.
Source code:
#include<iostream>
return a+b;
return a-b;
return a*b;
return a/b;
int main(){
float a,b,c;
cin>>a;
cin>>b;
c=addition(a,b);
cout<<a<<"+"<<b<<"="<<c<<endl;
c=substract(a,b);
cout<<a<<"-"<<b<<"="<<c<<endl;
c=multiply(a,b);
cout<<a<<"*"<<b<<"="<<c<<endl;
c=divide(a,b);
cout<<a<<"/"<<b<<"="<<c;
Output:
Exercise 04
Write a C++ Program that calculates the power of a base by a user defined function as follows:
Take the power and the base from the user in the main function.
Calcuate the power of the base in a user defined function “MY_POWER” by passing power and
base from the main ( ) to the MY_POWER function.
Calculated value must return from the function to the main and display there.
Source code:
#include<iostream>
using namespace std;
if(b==0){
return 1;
}
else
return a*MY_POWER(a,b-1);
int main(){
int a,b,c;
cout<<"Enter your base : ";
cin>>a;
cout<<"Enter your power : ";
cin>>b;
c=MY_POWER(a,b);
cout<<"Answer : "<<c;
}
Output:
Lab # 08
Functions
Exercise 01
Write a C++ Program that calculates the power of a base by a user defined function as follows:
• Take the power and the base from the user in the main function.
• Calcuate the power of the base in a user defined function “MY_POWER” by passing
power and base from the main ( ) to the MY_POWER function.
Code:
#include<iostream>
#include<math.h>
using namespace std;
{
int c;
c=pow(a,b);
return c;
int main()
int power,base;
}
Output:
Exercise 02
Write a C++ Program that perform following task.
• Generate three random numbers ranged from 1 to 100.
• Calculate average of three numbers using a function avrg(int, int, int, int&).
• Calculate standard deviation and variance of three numbers. Print the results.
CODE:
#include<iostream>
#include <cstdlib>
#include <ctime>
#include<math.h>
using namespace std;
double x;
x=(a+b+c)/3;
return x;
double var1,sum,variance;
sum=x+y+z;
variance=var1;
cout<<"variance = "<<variance<<endl;
return var1;
int main()
int var1,var2,var3;
srand((unsigned int)time(0));
double c,i,d,z ;
c= rand()%100+1;
d= rand()%100+1;
variance(c,d,z);
return 0;
Output:
Exercise 03
Write a C++ Program that contains four user defined function(s) plus(int, int, int&),
minus(int, int, int&), multiply(int, int, int&), divide(int, int, float&).
• In main() function:
o Get two numbers from user o Call four user defined fuctions o Variable to
contain result should be decleared in main function and passed as reference
to the user defined function.
o Calculation must be done in the user defined function according to their
names, e.g. plus() should perfom addition of the two variables. Variable to
contain result shoud be updated in user defined function.
o Print the result from main()
Code:
#include<iostream>
using namespace std;
int main()
double a,b;
cout<<add(a,b);
cout<<endl;
cout<<sub(a,b);
cout<<endl;
cout<<multiply(a,b);
cout<<endl;
cout<<divide(a,b);
cout<<endl;
return z+y;
}
double sub(double &y,double &z)
return y-z;
return z*y;
return y/z;
}
Output:
Exercise 04
Write a C++ that calculate price of purchased fruits.
total = x * y ;
return total;
total = x * y ;
return total;
total = x * y ;
return total;
total = x * y ;
return total;
total = x * y ;
return total;
int main()
apple = 160;
banana =120;
mango = 110 ;
peach = 100;
grapes =130 ;
int a,b,c,d,e,total;
total = 0;
cin >> a ;
cin >> b ;
cin >> c ;
cin >> d ;
cin >> e ;
Output:
Lab # 09
Function-ll
DEPARTMENT OF COMPUTER SCIENCE
BAHRIA UNIVERSITY, KARACHI CAMPUS
Exercise 01
Write a C++ program for calculating grades of students.
int main():
• prompt user for the number of subjects for which he/she wants to
calculate the grade 2 or 3.
• prompt for marks with respect to their early selection call Cal
grades() according to their selection.
o For example Cal grades (s1,s2) // for two subjects.
o Cal grades(s1,s2,s3) // for three subjects.
Calgrades():
• Function(s) must be overloaded accordingly.
• These functions determine the grade of student on following criteria: A
grade : 87 - 100
B grade : 75 – 86
C grade : 65 – 74
D grade : 50 – 64 F grade : < 50
Code:
#include<iostream>
using namespace std;
void Calgrades(int x);
void Calgrades(int x,int y);
void Calgrades(int x,int y,int z);
int main()
{
int choice,marks1,marks2,marks3;
cout<<"Enter number of grades to calculate between 1 to 3."<<endl;
cin>>choice;
if (choice==1)
{
cout<<"Enter marks to calculate grade. ";
cin>>marks1;
Calgrades(marks1);
}
else if (choice==2)
{
cout<<"Enter marks to calculate grade ";
cin>>marks1;
cout<<"Enter marks to calculate grade. ";
cin>>marks2;
Calgrades(marks1,marks2);
}
else if (choice==3)
{
cout<<"Enter marks to calculate grade. ";
cin>>marks1;
cout<<"Enter marks to calculate grade. ";
cin>>marks2;
cout<<"Enter marks to calculate grade. ";
cin>>marks3;
Calgrades(marks1,marks2,marks3);
}
}
void Calgrades(int x)
{
if (x>=87 && x<=100)
cout<<"A grade";
else if (x>=75 && x<=86)
cout<<"B grade";
else if (x>=65 && x<=74)
cout<<"C grade";
else if (x>=50 && x<=64)
cout<<"D grade";
else if (x<50)
cout<<"F grade";
}
void Calgrades(int x,int y)
{
Calgrades(x);
cout<<endl;
Calgrades(y);
cout<<endl;
}
void Calgrades(int x,int y,int z)
{
Calgrades(x);
cout<<endl;
Calgrades(y);
cout<<endl;
Calgrades(z);
cout<<endl;
}
Output:
Exercise 02
Write a C++ that contains following functions:
int main():
• prompt user to enter numbers for comparison.
• Minimum numbers user can enter are 2 and maximum upto 4.
• call comparison() method with two, three and four parameters.
int comparison():
• this function determine the smallest and largest number
• print the smallest and largest number
• this function(s) must be overloaded
Code:
#include <iostream>
using namespace std;
void line();
void cal_comparison(int ,int);
void cal_comparison(int ,int,int);
void cal_comparison(int ,int ,int ,int);
int main()
{
int choice,n1,n2,n3,n4;
cout<<"Enter the the number for comparison between 1-3"<<endl;
cin>>choice;
switch(choice)
{
case 1 :
{
cout<<"Enter numbers "<<endl;
cin>>n1>>n2;
line();
cal_comparison(n1 , n2);
line();
break;
}
case 2 :
{
cout<<"Enter numbers "<<endl;
cin>>n1>>n2>>n3;
line();
cal_comparison( n1 , n2);
line();
cal_comparison(n1 , n2 ,n3);
line();
break;
}
case 3 :
{
cout<<"Enter numbers "<<endl;
cin>>n1>>n2>>n3>>n4;
line();
cal_comparison( n1, n2);
line();
cal_comparison( n1, n2 , n3);
line();
cal_comparison( n1 , n2 , n3 , n4);
line();
}
}
{
if(a>b && a>c)
cout<<"Largest among the first three is : "<<a<<endl;
else if(b>a && b>c)
cout<<"largest among the first three is : "<<b<<endl;
else if(c>a && c>b)
cout<<"largest among the first three is : "<<c<<endl;
}
{
if(a>b && a>c && a>d)
cout<<"Largest among in the list is : "<<a<<endl;
else if(b>a && b>c && b>d)
cout<<"Largest among in the list is : "<<b<<endl;
else if(c>a && c>b && c>d)
cout<<"Largest among in the list is : "<<c<<endl;
else if(d>a && d>b && d>c)
cout<<"Largest among in the list is : "<<d<<endl;
}
}
void line ()
{
for(int i=0; i<=37; i++)
{
cout<<"*";
}
cout<<endl;
}
Output:
Exercise 03
void re(int);
int main()
{ int n;
cout<<"Enter a N Number = ";
cin>> n;
re(n);
}
void re(int n)
{
if(n>0)
cout<<n<<" ";
return re(n-1);
}
Output:
Exercise 04
Write a C++ program that perform following task:
int main():
• ask user to enter a positive number, store it in variable N.
• You have to calculate 1+2+3+4+......+N with fuction int sum().
• Print the result. int sum():
• this function calculate the sum of series from 1 to N.
• this fuction must be recursion function.
Code:
#include <iostream>
using namespace std;
int sum(int);
int main()
{ int n;
cout<<"Entre a positive number = ";
cin>>n;
cout<<"The sum of positive N("<<n<<") is = "<<sum(n);
}
int sum(int n)
{
if (n>0)
return n+sum(n-1);
}
Output:
Exercise 05
Write a C++ program that perform following task:
int main():
• Ask user to enter a
positive number, store it in variable N.
• You have to calculate Fibonacci number with fuction int fab().
• Print the result. int fab():
• this function calculate the Fibonacci number.
o 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,..
o fab(0) = 0, fab(1) = 1 o fab(n) =fab(n-1) + fab(n-2) where n>1 this fuction must be recursive function.
Code:
#include <iostream>
using namespace std;
int fab(int );
int main()
{
int n;
cout<<fab(i)<<",";
}
int fab(int n)
{
if (n==0)
{
return n;
}
else if (n==1)
{
return n;
}
else if(n>1)
{
return fab(n-1)+fab(n-2);
}
Output:
Lab # 10
String And Structure
Exercise 01
Write a C++ that contain two strings:
String1= “This program is to test several string functions”.
String2 = “Testing”
Perform following operations on these strings:
• Print a new string “Testing: This program is to test several string function” using
concatenation of string 1 and strin2.
• Find the size of string1 and string2 using string function.
• Extract word “program” from string1 using string function.
• Insert a word “Program” in string2 like “Testing Program” using string function.
• Replace the word “Program” in string1 with string2 using string function. Delete word
“program” from string1 using string function
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1="This program is to test several string functions.";
string str2="Testing ";
string str3;
cout<<str1<<endl<<str2<<endl<<endl;
str3=str1.append(str2);
cout<<str3<<endl<<endl;
str3=str1.substr(5,7);
cout<<str3<<endl<<endl;
str3=str2.append(str1.substr(5,7));
cout<<str3<<endl<<endl;
cout<<str1.replace(5,8,str2)<<endl<<endl;
cout<<str1.erase(5,8);
return 0;
}
Output:
Exercise 02
Write a C++ program that maintain record of students. Student contains following details:
• ID
• Name
• Department
• Email
• Phone no
Create a structure of student. Ask user to enter record for 5 students. Store those details in
variables of students type. Print those records on screen.
Code:
#include <iostream>
#include <string>
struct student
{
int id;
string name;
string department;
string email;
int phone_no;
};
int main()
{
student s[5];
for(int i=0; i<=4; i++)
{
cout<<"Enter Record Of Student :
"<<i+1<<endl;
cout<<"ID : ";
cin>>s[i].id;
cout<<endl;
cout<<"Name : ";
cin>>s[i].name;
cout<<endl;
cout<<"Department : ";
cin>>s[i].department;
cout<<endl;
cout<<"E-mail : ";
cin>>s[i].email;
cout<<endl;
cout<<"Phone no : ";
cin>>s[i].phone_no;
cout<<endl;
}
Exercise 03
Write a C++ program to do the following:
- Set up a structure/record to store products; each product has a name, a model number and a
price.
- Choose appropriate types for these fields.
- Your program should contain a loop which allows entry via the keyboard of up to 10 products,
to be stored in an array.
- The loop can be stopped by entry of "quit" for the product name
- Your program should include a function to display all the products details after the entry loop
has finished.
Code:
#include<iostream>
using namespace std;
#include<string>
struct store_products{
string product_name;
double model_no;
double prize;
};
int main(){
int i=0;
store_products product[10];
while(i<11){
i++;
}
}
Output:
Exercise 04
Write a C++ program that compute Net Salary of Employee. Program contains two user
defined functions empSalary() and display().
Code:
#include<iostream>
using namespace std;
#include<string>
int empSalary();
void display();
struct employee{
string EmployeeNumber,Name;
double BasicSalary, HouseAllowance,MedicalAllowance,Tax,
GrossPay, NetSalary;
}a;
int main(){
string b;
cout<<"Enter the Employee Number : ";
cin>>a.EmployeeNumber;
int empSalary(){
a.HouseAllowance=a.BasicSalary*10.0/100.0;
a.MedicalAllowance=a.BasicSalary*5.0/100.0;
a.Tax=a.BasicSalary*4.0/100.0;
a.GrossPay=a.BasicSalary+a.HouseAllowance+a.MedicalAllow
ance;
a.NetSalary=a.GrossPay-a.Tax;
display();
}
void display(){
cout<<"*************************************\nEMPLO
YERS SALARY
DETAILS\n*************************************\n";
cout<<"Employee Number : "<<a.EmployeeNumber<<endl;
cout<<"Employee Name : "<<a.Name<<endl;
cout<<"Basic Salary : "<<a.BasicSalary<<endl;
cout<<"House Allowence : "<<a.HouseAllowance<<endl;
cout<<"Medical Allowence : "<<a.MedicalAllowance<<endl;
cout<<"Gross Salary : "<<a.GrossPay<<endl;
cout<<"Tax Deduction : "<<a.Tax<<endl;
cout<<"Net Salary : "<<a.NetSalary<<endl;
}
Output:
Lab # 11
Stream File Handling
struct student
{
char name[50];
int id;
string email;
char dep[25];
char no[11];
} s;
void line();
void student();
void filing();
int main()
{
char a='Y';
line();
student();
line();
filing();
cout<<"Do you want to Enter New Record (Y/N)"<<endl;
cin>>a;
cout<<endl;
}while(a=='Y');
return 0;
}
void student()
{
cout<<"Full Name : ";
cin.ignore();
cin.getline(s.name,50);
cout<<endl<<"ID : ";
cin>>s.id;
cout<<endl<<"E-mail : ";
cin.ignore();
getline(cin,s.email);
cout<<endl<<"Department : ";
cin.ignore();
cin.getline(s.dep,25);
cout<<endl<<"Phone no : ";
cin.getline(s.no,11);
void filing()
{
ofstream dfile;
dfile.open("student.txt",ios::app);
dfile<<s.name<<"\t"<<s.id<<"\t"<<s.email<<"\t"<<s.dep<<"\t"<<s.no<<endl;
dfile.close();
}
void line ()
{
for(int i=0; i<=37; i++)
{
cout<<"*";
}
cout<<endl;
}
Output:
Exercise 02
Refer to you Exercise 2.
Store data in file student.txt with proper formatting as follows:
Code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
struct student
char name[50];
int id;
string email;
char dep[25];
string no;
} s;
void line();
void student();
void filing();
int main()
char a='Y';
do
line();
student();
line();
filing();
cin>>a;
cout<<endl;
}while(a=='Y');
return 0;
void student()
cout<<endl<<"ID : ";
cin>>s.id;
cout<<"Full Name : ";
cin.ignore();
cin.getline(s.name,50);
cin.ignore();
cout<<endl<<"E-mail : ";
getline(cin,s.email);
cout<<endl<<"Department : ";
cin.getline(s.dep,25);
cout<<endl<<"Phone no : ";
getline(cin,s.no);
void filing()
ofstream dfile;
dfile.open("student.txt",ios::app);
dfile<<s.id<<"\t"<<s.name<<"\t"<<s.dep<<"\t"<<s.no<<"\t"<<s.email<<endl;
dfile.close();
void line ()
cout<<"*";
cout<<endl;
Output:
Exercise 03
Read the data from file student.txt (line by line) and print on you computer screen as follows:
Code:
#include <iostream>
#include <string>
#include <fstream>
ifstream readrecord("Student.txt");
string line;
while(!readrecord.eof())
getline(readrecord,line);
cout <<line<<endl;
Output:
Exercise 04
Write a C++ program that compute Net Salary of Employee. Program contains two user
defined functions empSalary() and display().
//rd<<"Empno"<<'\t'<<setw(10)<<"EmpName"<<'\t'<<setw(10)<<"EmpBS"<<'\t'<<setw
(10)<<"EmpHS"<<'\t'<<setw(11)<<"EmpMA"<<'\t'<<setw(11)<<"EmpGS"<<'\t'<<setw(11)<<"
EmpTX"<<'\t'<<setw(11)<<"EmpNTSL"<<endl;
void empsalary();
main ()
{
cout <<"Enter the Employee Number: ";
cin>> e.no;
cout <<endl;
cout <<"Enter the Employee Name: ";
cin >>e.name;
cout <<endl;
cout <<"Enter the Employee Salary: ";
cin >>e.salary;
cout <<endl;
empsalary();
ofstream saverecord("employee.txt",ios::app);
saverecord<<e.no<<'\t'<<setw(10)<<e.name<<'\t'<<setw(10)<<e.salary<<"\t"<<setw(10)<<e.ho
use<<'\t'<<setw(11)<<e.medical<<'\t'<<setw(11)<<e.gpay<<'\t'<<setw(11)<<e.tax<<'\t'<<setw(1
1)<<e.net<<endl;
}
void empsalary()
{
e.medical=0.05*e.salary;
e.tax=0.04*e.salary;
e.house=0.10*e.salary;
e.gpay=e.salary+e.house+e.medical;
e.net=e.gpay-e.tax;
}
Output:
Exercise 05
Write a C++ program for billing system of MovInPeak restaurant. The program should
perform following tasks:
• Show menu to customer for orders.
• Allow the customer to select more than one item from the menu.
• Calculate and print the bill.
Assume that the restaurant offers the following items (the price of each item is shown to the
right of the item):
• Omlet $1.45
• French Omlet $2.45
• Muffin $0.99
• French Toast $1.99
• Fruit Basket $2.49
• Cereal $0.69
• Coffee $0.75
• Tea $0.50 Notes:
Code:
#include<iostream>
#include<fstream>
#include<string>
#include <iomanip>
using namespace std;
struct menu
{
string item;
float price;
};
menu list[8];
float s[8]={0,0,0,0,0,0,0,0};
void showMenu();
void printCheck();
int main()
{
cout<<"
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"<<endl;
cout<<endl;
cout<<" Welcome to MovinPeak Restaurant"<<endl;
cout<<endl;
cout<<"
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"<<endl;
showMenu();
printCheck();
}
void showMenu()
{
char b;
list[0].item="Omlet";
list[0].price=1.45;
list[1].item="French Omlet";
list[1].price=2.45;
list[2].item="Muffin";
list[2].price=0.99;
list[3].item="French Toast";
list[3].price=1.99;
list[4].item="Fruit Basket";
list[4].price=2.49;
list[5].item="Cereal";
list[5].price=0.69;
list[6].item="Coffee";
list[6].price=0.75;
list[7].item="Tea";
list[7].price=0.50;
cout<<endl;
cout<<" Enter Your Choice To Select Items:"<<endl;
cout<<endl;
for(int i=0;i<8;i++)
{
cout<<list[i].item<<setw(10)<<"\t \t"<<list[i].price<<"\t
\t"<<setw(10)<<"["<<i+1<<"]"<<endl;
}
ofstream saverecord("price.txt",ios::app);
for(int i=0;i<8;i++)
{
saverecord<<list[i].price<<endl;
}
do{
int ch,q;
switch(ch)
{
case 1:
s[0]+=q;
cout<<" You selected "<<s[0]<<" "<<list[0].item<<endl;
break;
case 2:
s[1]+=q;
cout<<" You selected "<<s[1]<<" "<<list[1].item<<endl;
break;
case 3:
s[2]+=q;
cout<<" You selected "<<s[2]<<" "<<list[2].item<<endl;
break;
case 4:
s[3]+=q;
cout<<" You selected "<<s[3]<<" "<<list[3].item<<endl;
break;
case 5:
s[4]+=q;
cout<<" You selected "<<s[4]<<" "<<list[4].item<<endl;
break;
case 6:
s[5]+=q;
cout<<" You selected "<<s[5]<<" "<<list[5].item<<endl;
break;
case 7:
s[6]+=q;
cout<<" You selected "<<s[6]<<" "<<list[6].item<<endl;
break;
case 8:
s[7]+=q;
cout<<" You selected "<<s[7]<<" "<<list[7].item<<endl;
break;
default:
cout<<"Wrong choice try again.....";
}
cout<<endl;
cout<<"Continue...(Y/N)";
cin>>b;
cout<<endl;
}
while(b=='Y');
}
void printCheck()
{
float total=0;
float tax,due;
cout<<"*****************************************************************
*****"<<endl;
cout<<" Bill "<<endl;
cout<<"*****************************************************************
*****"<<endl;
ofstream saverecord("moveinpeak.txt",ios::app);
for(int i=0;i<8;i++)
{
if(s[i]>0)
{
cout<<list[i].item<<"\t \t" <<"No of Quantity "<<s[i]<<"\t "<<" $
"<<list[i].price<<endl;
total=total+(list[i].price*s[i]);
saverecord<<list[i].item<<" "<<s[i]<<" $
"<<list[i].price<<endl;
}
}
tax=total*5/100;
due=total+tax;
cout<<endl;
cout<<" Tax"<<"\t \t"<<" $ "<<tax<<endl;
cout<<endl;
cout<<"*****************************************************************
*****"<<endl;
cout<<"Amount Due "<<" $ "<<due<<endl;
cout<<"*****************************************************************
*****"<<endl;
saverecord<<endl;
saverecord<<"Tax= $ "<<tax<<" "<<"Total Price= $ "<<due<<endl;
saverecord<<endl;
}
Output:
Lab # 12
Pointers
Exercise 01
Initialize an integer array of 5 elements. Display values of all elements along with their
addresses using pointers.
Code:
#include <iostream>
using namespace std;
int main()
{
int array[5]={2,4,6,8,20};
int *pointer_test=array;
cout<<"\tAddress\t\tValue\n\n";
for (int i=0;i<5;i++)
{
cout<<"\t"<<pointer_test<<"\t"<<*pointer_test<<"\n";
pointer_test++;
}
}
Output:
Exercise 02
Suppose you are given addresses of two array elements at random. Write a program which
Code:
#include<iostream>
using namespace std;
int main()
{
int *a;
int *b;
int arr[]={4,3,1,6,7,7,7,7,7,7,8,8,8,8,8};
a=&arr[14];
b=&arr[0];
int c=0;
while(b!=a)
{
c++;
b++;
}
cout <<"Elements Between are : "<<(c-1);
}
Output:
Exercise 03
Write a program which passes the address of an integer array to a pointer variable declared
in a function Bubble sort that array with the help of that pointer variable and show result
from main().
Code:
#include<iostream>
using namespace std;
void bubble_sort_before(int *k);
void bubble_sort(int *p);
int main()
{
int abc[5]={12,22,13,74,5};
int *p;
p=abc;
bubble_sort_before(p);
bubble_sort(p);
cout<<endl;
cout<<"\nAfter Bubble sort :\n";
cout<<"===================\n\n";
for (int i=0;i<5;i++)
{
cout<<p[i]<<"\t";
}
}
Output:
Exercise 04
Initialize a char pointer with some text. Declare an array variable of type char. Copy the
statement from char pointer variable to the array variable.
Code:
#include<iostream>
using namespace std;
int main()
{
char a[5];
char b[]={'H','E','L','L','O'};
char *p;
p=&b[0];
for (int i=0;i<5;i++)
{
a[i]=*p++;
}
for (int i=0;i<5;i++)
{
cout<<a[i];
}
}
Output: