0% found this document useful (0 votes)
161 views24 pages

C++ 4th Sem Pgms

The document contains 11 C++ programs covering topics such as: 1. Converting days to years, months, weeks and days 2. Temperature conversion using classes 3. Adding two complex numbers using classes 4. Sorting array elements in ascending order 5. Adding and multiplying matrices 6. Finding the transpose of a matrix 7. Calculating area of shapes using function overloading 8. Performing string operations using operator overloading 9. Creating base and derived classes for shapes and vehicles

Uploaded by

Jose Kurian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
161 views24 pages

C++ 4th Sem Pgms

The document contains 11 C++ programs covering topics such as: 1. Converting days to years, months, weeks and days 2. Temperature conversion using classes 3. Adding two complex numbers using classes 4. Sorting array elements in ascending order 5. Adding and multiplying matrices 6. Finding the transpose of a matrix 7. Calculating area of shapes using function overloading 8. Performing string operations using operator overloading 9. Creating base and derived classes for shapes and vehicles

Uploaded by

Jose Kurian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

C++ Programs

1.Write a program to convert given number of days into years, months , week and
days
#include<iostream>
using namespace std;
int main()
{
int y,d,w;

cout<<"Enter No. of days:";


cin>>d;

y=d/365;
d=d%365;
w=d/7;
d=d%7;

cout<<"\nYears: "<<y<<"\nWeeks: "<<w<<"\nDays: "<<d;


return 0;
}
2.Write a program for temperature conversion using class
#include <iostream.h>

float totalFahrenheit(float);
float totalCelsius (float);

float main(float)
{

float temp,result;
char choice;

cout<<"Type in the temperature: ";


cin>>temp;
cout<<"Press C to convert to Celsius and press F to convert to Fahrenheit: ";
cin>>choice;
if (choice=='c' || choice=='C'
{
result =totalFahrenheit(temp);
cout<<temp<<" Fahrenheit to Celsius is: << result
}
else if (choice=='F' || choice=='f')
{
result =totalCelsius(temp);
cout<<temp<<" degrees Celsius to Fahrenheit is: "<< result;
}
}

float totalFahrenheit(float temp){

return ((9/5*temp)+(32));
}

float totalCelsius (float temp){

return ((temp-32)*(5/9));
}
}
3.Write a program to add two complex numbers using class
#include <iostream>

using namespace std;

class complex
{
public :
int real, img;
};

int main()
{
complex a, b, c;

cout << "Enter a and b where a + ib is the first complex number.";


cout << "\na = ";
cin >> a.real;
cout << "b = ";
cin >> a.img;
cout << "Enter c and d where c + id is the second complex number.";
cout << "\nc = ";
cin >> b.real;
cout << "d = ";
cin >> b.img;

c.real = a.real + b.real;


c.img = a.img + b.img;

if ( c.img >= 0 )
cout << "Sum of two complex numbers = " << c.real << " + " << c.img << i";
else
cout << "Sum of two complex numbers = " << c.real << " " << c.img << "i";

return 0;
}
4.Write a program to sort array elements in ascending order
#include<iostream.h>
#include<conio.h>

void main()
{
int i,a[10],temp,j;
clrscr();
cout<<"Enter any 10 num in array: \n";
for(i=0;i<=10;i++)
{
cin>>a[i];
}
cout<<"\nData before sorting: ";
for(j=0;j<10;j++)
{
cout<<a[j];
}
for(i=0;i<=10;i++)
{
for(j=0;j<=10-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"\nData after sorting: ";
for(j=0;j<10;j++)
{
cout<<a[j];
}
getch();
}

5.Write a program to add two matrices

#include<iostream>
using namespace std;

void main()
{
int a[5][5],b[5][5],t[5][5],i,j,k,l,m,n,z,c[5][5],x,y; //declarations
clrscr();
//User inputs
cout<<"enter the order of the matrix > ";
cin>>x;
//Matrix1
cout<<endl<<"enter the 1st matrix elements > ";
for(i=0;i<x;i++)
{
for(j=0;j<x;j++)
{
cin>>a[i][j];
}
}
//Matrix2
cout<<endl<<"enter the 2nd matrix elements > ";
for(i=0;i<x;i++)
{
for(j=0;j<x;j++)
{
cin>>b[i][j];
}
}

//Sum Calculation
cout<<endl<<"SUM...."<<endl;
for(i=0;i<x;i++)
{
for(j=0;j<x;j++)
{
cout<<" "<<a[i][j]+b[i][j];
}
cout<<endl;
}

6. Write a program to find product of two matrices

#include<iostream>

using namespace std;

void main()
{
int a[5][5],b[5][5],t[5][5],i,j,k,l,m,n,z,c[5][5],x,y; //declarations
clrscr();
//User inputs
cout<<"enter the order of the 4 matrices > ";
cin>>k;
cin>>l;
cin>>m;
cin>>n;
cout<<endl<<"enter the 1st matrix elements > ";
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
cin>>a[i][j];
}
}
cout<<endl<<"enter the 2nd matrix elements > ";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>b[i][j];
}
}
//Product Calculation
if(l==m)
{
for(i=0;i<k;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
for(z=0;z<l;z++)
{
c[i][j]=c[i][j]+(a[i][z]*b[z][j]);
}
}
} }
else
{
cout<<"invalid data....";
}

//Display Result
cout<<endl<<"PRODUCT..."<<endl;
for(i=0;i<k;i++)
{
for(j=0;j<n;j++)
{
cout<<" "<<c[i][j];
}
cout<<endl;
}

7. Write a program to find transpose of a matrices

#include <stdio.h>

int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);

printf("Enter the elements of matrix\n");

for (c = 0; c < m; c++)


for(d = 0; d < n; d++)
scanf("%d",&matrix[c][d]);

for (c = 0; c < m; c++)


for( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];

printf("Transpose of entered matrix :-\n");

for (c = 0; c < n; c++) {


for (d = 0; d < m; d++)
printf("%d\t",transpose[c][d]);
printf("\n");
}

return 0;
}

8.Write a program to calculate area of circle, rectangle and triangle using function
overloading

using namespace std;


int area(int);
int area(int,int);
float area(float);
float area(float,float);
int main()
{
int s,l,b;
float r,bs,ht;
cout<<"Enter side of a square:";
cin>>s;
cout<<"Enter length and breadth of rectangle:";
cin>>l>>b;
cout<<"Enter radius of circle:";
cin>>r;
cout<<"Enter base and height of triangle:";
cin>>bs>>ht;
cout<<"Area of square is"<<area(s);
cout<<"\nArea of rectangle is "<<area(l,b);
cout<<"\nArea of circle is "<<area(r);
cout<<"\nArea of triangle is "<<area(bs,ht);
}
int area(int s)
{
return(s*s);
}
int area(int l,int b)
{
return(l*b);
}
float area(float r)
{
return(3.14*r*r);
}
float area(float bs,float ht)
{
return((bs*ht)/2);
}

9. c++ menu driven program to perform string operations using operator


overloading

#include<iostream>
#include<cstring>

using namespace std;

//class definition
class my_string{
private:
//character array to denote string
char str[30];
public:

//function declarations
void getdata();
void display();
void operator== (my_string str1);
int operator= (my_string str1);
void operator+ (my_string str1);

};

void my_string::getdata()
{
cout<<"\nEnter the string : ";
cin>>str;
}

void my_string::display()
{
cout<<"\n"<<str;
}
void my_string::operator== (my_string str1)
{
strcpy(str1.str,str);
cout<<"\n\tCopied String is : "<<str1.str;
}
int my_string::operator<= (my_string str1)
{
if(strcmp(str,str1.str)==0)
return 1; //strings are equal
elseif(strcmp(str,str1.str)<0)
return 2;
else
return 0;
}
void my_string::operator+ (my_string str1)
{
strcat(str,str1.str);
cout<<"\n\t--String After Concat is : "<<str;
}
//start of main function
int main()
{
int opt,c,opt1=1;

//object declaration
my_string a,b;

while(opt1==1 && opt!=8)


{

//displaying menu to the user


cout<<"\n\t\t\t---Main Menu---\n\t1.Equality\n\t2.String Copy\n\t3.Concat";
cout<<"\n\t8.Exit\n\t\t--Enter your choice-->";
cin>>opt;
switch(opt)
{
case 1:
cout<<"\nEnter the 1st string-\n";
a.getdata();
cout<<"\nEnter the 2nd string-\n";
b.getdata();
c=a=b;
if(c==1)
cout<<"\n\t---Strings are Equal---\n";
else if(c==1)
cout<<"\n\t---Strings 2 is larger---\n";

else
cout<<"\n\t---Strings 1 is larger---\n";
break;
case 2:
a.getdata();

a==b;
break;
case 3:
cout<<"\nEnter the 1st string-\n";
a.getdata();
cout<<"\nEnter the 2nd string-\n";
b.getdata();
a+b;
break;

case 4: return 0;

default: cout<<"Invalid choice..try again\n";


}
if(opt!=4){
cout<<"\n\n\tDo you want to continue(Press 1 to continue)";
cin>>opt1;}
}

return 0;
}
10. write a program to create a base class called shape and derive circle and
square from it. Define constructors for all these classes.

#include <iostream>
using namespace std;

class Shape {
protected:
int l;
public:
Shape( int a=0)
{
l = a;
}
int Find_Area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Square: public Shape{
public:
Square( int a=0):Shape(a)
{
}
int Find_Area()
{
cout << " Square class area :" <<endl;
return (l * l);
}
};
class Circle: public Shape{
public:
Circle( int a=0):Shape(a)
{
}
int Find_Area()
{
cout << " Circle class area :" <<endl;
return (3.14*l*l);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Square sqr(10);
Circle cir(5);
shape = &sqr;
shape->Find_Area();
shape = &cir;
shape->Find_Area();

return 0;
}
11. program to create a base class called vehicle and derive car and bike class
from it

#include<iostream.h>
class Cvehicle
{
protected:
int wheels;
int weight;
int amount;
public:
Cvehicle(int input_wheels, float input_weight, int input_amount)
{
wheels = input_wheels;
weight = input_weight;
amount=input_amount;
}
int get_wheels()
{
return wheels;
}
float get_weight()
{
return weight;
}
int get_amount()
{
return amount;
}

float wheel_load()
{
return (weight/wheels);
}
};
class Ccar : public Cvehicle
{
int passenger_load;
public:
Ccar(int input_wheels, float input_weight, int input_amount ,int people = 4)
{
passenger_load = people;
wheels = input_wheels;
weight = input_weight;
amount=input_amount;

}
int passengers()
{
return passenger_load;
}
};
class Cbike : public Cvehicle
{
int passenger_load;
int mileage;
public:
Cbike(int how_many = 2, int max_mileage = 40)
{
passenger_load = how_many;
mileage = max_mileage;
}
void efficiency(void)
{
Cout<<”mileageis”<<mileage;
}
int passengers(void)
{
return passenger_load;
}
};

void main()
{
Cvehicle unicycle(1,12.5,500000);
cout<<"Unicycle using the Cvehicle base class\n";
cout<<"--------------------------------------\n";

cout<<"Unicycle has "<<unicycle.get_wheels()<<" tire.\n";


cout<<"Unicycle wheel load is "<<unicycle.wheel_load()<<"kg on one tire.\n";
cout<<"Unicycle weight is "<<unicycle.get_weight()<<" kg.\n\n";
cout<<"Unicycle amount is "<<unicycle.get_amount()<<”\n";

Ccar sedan(4,3500.0,300000,5);

cout<<"Sedan car using the Ccar derived class\n";


cout<<"--------------------------------------\n";

cout<<"Sedan car carries "<<sedan.passengers()<<" passengers.\n";


cout<<"Sedan car weight is "<<sedan.get_weight()<<" kg.\n";
cout<<"Sedan amount is "<<sedan.get_amount()<<”\n";

cout<<"Sedan car wheel load is "<<sedan.wheel_load()<<"kg per tire.\n\n";

Cbike trail(18,40);

cout<<"Trail using the Cbike derived class\n";


cout<<"--------------------------------------\n";

cout<<"Trailer weight is "<<trail.get_weight()<<" kg.\n";


cout<<"Trailer efficiency is "<<trail.efficiency()<<"\n";

getch();
}
12. To find the m^n of int and float number using function over loading.
#include<iostream.h>
#include<conio.h>
#include<math.h>

//first function
int power(int n, int p=2)
{
int res = pow(n, p);
return res;
}

//second function
double power(double n, int p = 2)
{
double res;
res = pow(n,p);
return res;
}
void main()
{
int value, powr, result;
cout<< "\n Enter a value (any integer ) to find it's square:";
cin>> value;
// first function will be called
result = power(value);
cout<< "\n The square of " << value << " = " << result;
cout<< "\n Enter a value (any integer ) to find it's cube:";
cin>> value;
// first function will be called
result = power(value, 3);
cout<< "\n The cube of " << value < <" = " << result;
cout<< "\n Enter a value (any integer) :";
cin>> value;
cout<< "\n Enter its power (any integer) :";
cin>> powr;
// first function will be called
result = power(value, powr);
cout<< "\n The " << value < <" to the power of " << powr <<" is " << result;
int p;
float val, r;
cout<< "\n Enter a value :";
cin>> val;
cout<< "\n Enter its power ( integer):";
cin>> p;
//second function is called
r = power(val, p);
cout<< "\n The " << val << " to the power of " << p <<" is " << r;
cout<< "\n Enter a value :";
cin>> val;
// second function will be called
r = power(val);
cout<< "\n The square of " << val << " = " << r;
getch();
}

13.Write a program for exception handling Divide By Zero

ALGORITHM:

Step 1: Start the program.


Step 2: Declare the variables a,b,c.
Step 3: Read the values a,b,c,.
Step 4: Inside the try block check the condition.
a. if(a-b!=0) then calculate the value of d and display.
b. otherwise throw the exception.
Step 5: Catch the exception and display the appropriate message.
Step 6: Stop the program.

PROGRAM:

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
float d;
clrscr();
cout<<"Enter the value of a:";
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;

try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);
}
}

catch(int i)
{
cout<<"Answer is infinite because a-b is:"<<i;
}
getch();
}
14. To find the mean value of a given number using friend function.

ALGORITHM:
STEP 1: Start the program.

STEP 2: Declare the class name as Base with data members and member functions.

STEP 3: The function get() is used to read the 2 inputs from the user.

STEP 4: Declare the friend function mean(base ob) inside the class.

STEP 5: Outside the class to define the friend function and do the following.

STEP 6: Return the mean value (ob.val1+ob.val2)/2 as a float.

STEP 7: Stop the program.

PROGRAM:
#include<iostream.h>

#include<conio.h>

class base

int val1,val2;

public:

void get()

cout<<"Enter two values:";

cin>>val1>>val2;

friend float mean(base ob);

};

float mean(base ob)

return float(ob.val1+ob.val2)/2;

}
void main()

clrscr();

base obj;

obj.get();

cout<<"\n Mean value is : "<<mean(obj);

getch();

15. To count the object value using the storage keyword static.

ALGORITHM:
STEP 1: Start the program.

STEP 2: Declare the class name as Stat with data member s and member functions.

STEP 3: The constructor Stat() which is used to increment the value of count as 1 to to assign the
variable code.

STEP 4: The function showcode() to display the code value.

STEP 5: The function showcount() to display the count value.

STEP 6: Stop the program.

PROGRAM:
#include<iostream.h>

#include<conio.h>

class stat

int code;

static int count;

public:

stat()

{
code=++count;

void showcode()

cout<<"\n\tObject number is :"<<code;

static void showcount()

cout<<"\n\tCount Objects :"<<count;

};

int stat::count;

void main()

clrscr();

stat obj1,obj2;

obj1.showcount();

obj1.showcode();

obj2.showcount();

obj2.showcode();

getch();

16.tower of Hanoi

#include <iostream.h>
#include <conio.h>

void tower(int a,char from,char aux,char to){


if(a==1){
cout<<"\t\tMove disc 1 from "<<from<<" to "<<to<<"\n";
return;
}
else{
tower(a-1,from,to,aux);
cout<<"\t\tMove disc "<<a<<" from "<<from<<" to "<<to<<"\n";
tower(a-1,aux,from,to);
}
}

void main(){
clrscr();
int n;
cout<<"\n\t\t*****Tower of Hanoi*****\n";
cout<<"\t\tEnter number of discs : ";
cin>>n;
cout<<"\n\n";
tower(n,'A','B','C');
getch();
}

17.program to interchange value of class members using friend function

//program to swap the to value of two classes using the friend function
#include <iostream.h>
#include <conio.h>
class Second;
class First
{
private:
int x;
public:
void value1(int);
void display1();
friend void swap(First s1,Second s2); //friend function
};
void First::value1(int a)
{
x=a;
}
void First::display1()
{
cout<<x;
}

class Second
{
private:
int y;
public:
void value2(int);
void display2();
friend void swap(First s1,Second s2); //friend function
};
void Second::value2(int b)
{
y=b;
}
void Second::display2()
{
cout<<y;
}
void swap(First s1,Second s2) //friend function definition
{
int t;
t=s1.x;
s1.x=s2.y;
s2.y=t;
cout<<"Final values of class 1 after swapping (x) = "<<s1.x;
cout<<endl;
cout<<"Final values of class 2 after swapping(y) = "<<s2.y;
cout<<endl;
}
void main()
{

First f;
Second s;
f.value1(9);
s.value2(15);
cout<<"Initial values of class 1 (x) = ";
f.display1();
cout<<endl;
cout<<"Initial values of class 2 (y) = ";
s.display2();
cout<<endl;
swap(f,s); //function call-objects are passed as the parameter
getch();
}

18.Write a program to add 2 time values

#include<iostream>
using namespace std;
class time
{
int m,s;
public:
void st()
{
cout<< "Enter minutes & seconds"<<endl;
cin>>m>>s; }
void ts()
{
cout<<"Minutes = "<<m<<endl;
cout<<"Seconds = "<<s<<endl; }
friend time operator +(time,time);
};
time operator + (time t1,time t2)
{
time t3;
t3.m=(t1.m+t2.m)+(t1.s+t2.s)/60;
t3.s=(t1.s+t2.s)%60;
return t3;
}
int main()
{
time b1,b2,b3;
b1.st();
b2.st();
b3=b1+b2;
b3.ts();
}

19. Program to store numbers in a file and then read and display odd or even
numbers separately

#include<stdio.h>
#include<conio.h>

void main()
{
FILE *f1,*f2,*f3;
int number,i;
clrscr();

printf("Contents of DATA file\n\n");


f1 = fopen("DATA","w"); /* create a data file */
for(i=1;i<=30;i++)
{
scanf("%d",&number);
if(number==-1)break;
putw(number,f1);
}
fclose(f1);

f1 = fopen("DATA","r");
f2 = fopen("ODD","w");
f3 = fopen("EVEN","w");

while((number = getw(f1)) != EOF) /* Read from Data file */


{
if(number%2==0)
putw(number,f3);
else
putw(number,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);

f2 = fopen("ODD","r");
f3 = fopen("EVEN","r");

printf("\n\nContents of ODD file \n\n");


while((number = getw(f2)) != EOF)
printf("%4d",number);

printf("\n\nContents of EVEN file \n\n");


while((number = getw(f3)) != EOF)
printf("%4d",number);

fclose(f2);
fclose(f3);
getch();
}
20. c++ program to compare age using this pointer
#include <iostream>

using namespace std;

class Age
{
public:
// Constructor definition
Age(int h)
{
ag = h;
}
int compare(Age age)
{
return this->ag() > age.h();
}
private:
int ag;
};

int main(void)
{
Age A1(45); // Declare box1
Age A2(30); // Declare box2

if(A1.compare(A2))
{
cout << "A2 is smaller than A1" <<endl;
}
else
{
cout << "A2 is equal to or larger than A1" <<endl;
}
return 0;
}

21.Program to create book class….

You might also like