[go: up one dir, main page]

0% found this document useful (0 votes)
97 views56 pages

Priya PDF

The document contains 14 C++ programs with their source code and output. The programs include printing text, calculating ASCII values, finding sum/average of numbers, compound interest, swapping values, checking Armstrong/prime numbers, reversing numbers, finding largest number in a list, printing tables, calculating factorials and more basic programs.

Uploaded by

NARENDER
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)
97 views56 pages

Priya PDF

The document contains 14 C++ programs with their source code and output. The programs include printing text, calculating ASCII values, finding sum/average of numbers, compound interest, swapping values, checking Armstrong/prime numbers, reversing numbers, finding largest number in a list, printing tables, calculating factorials and more basic programs.

Uploaded by

NARENDER
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/ 56

1. WriteaC++programtoprint"HELLO".

#include<iostream.h>
#include<conio.h>in
t main()
{
{
clrscr();
cout<<"HELLO"·
'
getch();
}
returnO;
}

Output:
HELLO
2. WriteaC++programtoprintASCIIvalueofdigits,
uppercaseandlowercasealphabets.

#include<iostream.h>
#include<conio.h>in
t main()
{
{
clrscr();
Cout<<"ASCIIvaluesofdigits:"<<endl;
for(int i=48; i<=57; i++)
{
Cout<<"ASCIIvaluesof"<<char(i)<<"is"<<i<<endl;
}
Cout<<endl;
Cout<<"ASCII valuesofuppercase alphabet :"<<endl;
for(int i=65; i<=90; i++)
{
Cout<<"ASCIIvaluesof"<<char(i)<<"is"<<i<<endl;
}
Cout<<endl;
Cout<<"ASCIIvaluesoflowercasealphabet:"<<endl;
for(int i=97; i<=122; i++){
Cout<<"ASCIIvaluesof"<<char(i)<<"is"<<i<<endl;
}
getch();
}
returnO;
}
Output: ASCIIvalueofdigits:

ASCIIvalue of 0 is:48

ASCIIvalue of 1is:49

ASCIIvalueof 2is:50

ASCII valueof 3is:51

ASCII value of 4is:52

ASCIIvalueof 5 is:53

ASCII valueof 6is:54

ASCIIvalue of 7is:55

ASCIIvalue of 8is:56

ASCIIvalue of 9is:57

ASCIIvalueofuppercasealphabets:

ASCII value of A is:65

ASCII value of Bis:66

ASCII value of Cis:67

ASCII value of D is:68

ASCII value of E is:69

ASCII value of F is:70

ASCII value of Gis:71

ASCII value of His:72

ASCII value of I is:73

ASCII value of J is:74

ASCII value of K is:75

ASCII value of L is:76

ASCIIvalueof M is:77

ASCII value of Nis:78

ASCIIvalue of Ois:79

ASCIIvalueofPis:80

ASCII value of Qis:81

ASCIIvalue of R is:82

ASCII value of S is:83

ASCII value ofTis:84


ASCII value of U is:85

ASCII value of V is:86

ASCIIvalueof Wis:87 ASCII

value of X is:88 ASCII

value of Y is:89 ASCII

value of Z is:90

ASCIIvalueoflowercasealphabet:

ASCII value of a is:97

ASCII value of b is:98

ASCII value of c is:99

ASCII value of dis100

ASCII value of e is:101

ASCII value offis:102

ASCII value of g is:103

ASCII value of h is:104

ASCII value of i is:105

ASCII value of j is:106

ASCII value of k is:107

ASCII valueof mis:109

ASCII value of n is:110

ASCII value of o is:111

ASCII value of p is:112

ASCII value of q is:113

ASCII value of r is:114

ASCII value oftis:116

ASCII value of u is:117

ASCII value of v is:118

ASCII value of w is:119

ASCII value of x is:120

ASCII value of y is:121

ASCII value of z is:122


3. Write c++ program tofind sum, average of three
numbers.

#include<iostream.h>
#include<conio.h>in
t main()
{
{
clrscr();
float a, b, sum, average;
cout<<"enterthreenumbers="·
'
cin>>a;
cin>>b;
cin>>c;
sum=a+b+c;
average:sum/3;
cout<<"sum="<<sum<<"\n";
cout<<"average="<<average<<"\n;
getch();
}
returnO;
}

Output:
Entertwonumbers=56

89

67

Sum=212

Average:167.3333333333
4. Writeac++programto findcompoundinterest.

#include<iostream.h>#
include<conio.h>int
main()
{
{
clrscr();
doubleprincipal,rate,time,compoundlnterest;

cout <<"Enter the principal amount: ";


cin >> principal;

cout <<"Enter the annual interest rate (as a percentage): ";


cin >> rate;

cout <<"Enter the time period in years: ";


cin >> time;
rate=rate/100.0;
compoundlnterest= principal * pow(l+rate/1,time) -principal;
cout<<"Thecompoundinterestis:"<<compoundlnterest<<endl;

getch();
}
return0;
}

Output:

Principal:1200

Time:2

Rate:5.4

Compound interest=133.099243
5. Writec++programtofindsumoftwonumbers.

#include<iostream.h>
#include<conio.h>
#include<maths.h>
intmain()
{
{
clrscr();
float a,b,sum;
cout<<"enter two numbers=";
cin>>a;
cin>>b;
sum=a+b·
'
cout<<"sum="<<sum<<"\n";
getch();
}
returnO;
}

Output:
Entertwonumbers=56

89

Sum=145
6. Write c++ program to swap two numbers without
using temp variable.

#include<iostream.h>
#include<conio.h>
int main()
{
{
clrscr();
int a=5,b=10;

cout<<"Beforeswapping:"<<endl;
cout<<"a="<<a<<"b="<<b<<endl·
' '

II Swapping numbers without using atemporaryvariable


a=a+b; II a= 15 (5 + 10)
b = a- b; II b =5 (15 -10)
a=a-b;IIa= 10(15-5)

cout<<"Afterswapping:"<<endl;
cout<<"a="<<a<<" b="<<b<<endl·
' '
getch();
}
return0;
}

Output:

Beforeswapping:

a=5,b=10

Afterswapping:

a=10,b=5
7. Writeac++programtofindwhetheranumberis
Armstrong or not.

#include<iostream.h>#include<c
onio.h>
intmain()
{
{
clrscr();
int power(int base, int exponent) {
int result = 1;
for(inti=0;i<exponent;i++){
result*=base·
'
}
returnresult;
}
boolisArmstrong(intnum){
int originalNum= num; int
digits = 0;
int sum=
0;while(num>0){
digits++;
numI=10;
}

num=originalNum;

// Calculate the sum of digits raised to the power of the number


ofdigits
while(num>0){
int digit = num %10;
sum+=power(digit, digits);
num I= 10·,
}

//Checkifthesumisequaltotheoriginal number return


(sum== originalNum);
}

int main()
{ intnumbe
r;
cout <<"Enter anumber: "; cin
>>number;

if(isArmstrong(number)){
cout<<number<< isanArmstrongnumber. <<endl;
11 11

}else{
cout<<number<< isnotanArmstrongnumber. <<endl;
11 11

}
getch();
}
returnO;
}

Output:

Run1

Enteranumber:153

153isanArmstrongnumber.

Run2

Enteranumber:120

120isnotanArmstrongnumber.
8. Writeac++programtoreverseanumber.

#include<iostream.h>
#include<conio.h>
int main()
{
{
clrscr();
int reverseNumber(int num)
{ int reversedNum = O;
while(num!=0){
intlastDigit=num %10;
reversedNum=reversedNum*10+ lastDigit;
numI=IO·
'
}
returnreversedNum;
}
int main()
{ intnumbe
r;
cout <<"Enter a number: ";
cin >> number;
intreversedNumber=reverseNumber(number);
cout <<"The reversed numberis:"<<reversedNumber<<endl;
getch();
}
returnO;
}

Output:

Enteranumber:12345
Thereversednumberis:54321
9. Writeac++programtofindlargestnumbersofalistof
numbers entered through keyboard.

#include
<iostream.h>#include
<conio.h> intmain()
{
{
clrscr();
intnum,largest,count;
bool firstNum = true;

cout <<"Enter the number of values you want to input: ";


cin >> count;

for (inti=O;i<count; i++)


{ cout <<"Enter a number: ";
cin >> num;

if (firstNum IInum > largest)


{ largest = num;
firstNum=false;
}
}

cout<<"Thelargestnumberis:"<<largest<<endl;
getch();
}

returnO;

Output:

Enter the number of values you want to input: 5

Enter a number: 10

Enteranumber:25

Enter a number: 8

Enteranumber:19

Enteranumber:30

Thelargestnumber is:30
10. Writea c+programtoprinttableofanynumber.

#include<iostream.h>
#include<conio.h>int
main()
{
{
clrscr();
int vowel, consonant; cout<<"\
nEnterthelimit:"; cin>>n;
cout<<"\nEnterthetablenumber:";
cin>>a;
for(i=l;i<=n;i++)
{
cout<<"\n"<<i<<"*"<<a<<i*a;
}
getch();
}
returnO;
}

Output:
Enterthelimit:10

Enterthetablenumber:2

2*1=1

2*2=4

2*3=6

2*4=8

2*5=10

2*6=12

2*7=14

2*8=16

2*9=18

2*10=20
11. Writeac++programtoprintyourname10times.

#include
<iostream.h>#include
<conio.h> #include
<string.h> int main()
{
{
clrscr();
string name= "Your Name";
int count = 1O;

for (int i =O; i<count; i++)


{ cout<<name<<endl;
}
getch();
}
returnO;
}

Output:

POOJ

APOO

JAPO

OJAP

OOJA

POOJ

APOO

JAPO

OJAP

OOJA

POOJ

APOO
12. Write a c++ programto calculateand print the sum of
even and odd integer of the the first n natural number.

#include
<iostream.h>#include<
conio.h>
intmain()
{
{
clrscr();
intn,sumEven=0,sumOdd=O;

cout <<"Enter the value of n: ";


cin >> n;

//Calculatethesumofevenandoddintegers for
(inti= 1; i <= n; i++) {
if(i%2 ==0){
sumEven+=i;//AddevennumberstosumEven
}else{
sumOdd+=i; //AddoddnumberstosumOdd
}
}

//Print theresults
cout <<"Sum of even integers: "<< sumEven << endl;
cout <<"Sum of odd integers: "<< sumOdd << endl;
getch();
}
returnO;
}

Output:

Enter the value of n:10

Sumofevenintegers:30

Sum of odd integers: 25


13. Writeac++programtofindnumberprimeornot.
#include<iostream.h>
#include<conio.h>int
main()
{
{
clrscr();
int n,i;
cout<<"Enter anumber="·
'
cin>>n;
i=2;
while(i<=n/2)
{
if(n%i==0)
{
cout<<"Notprime";
goto end;
}
i++·
'
}
cout<<"Primenumber"·
'
end:
getch();
}
returnO;
}

Output:

Enteranumber=S Not

prime

Or

Enteranumber=6

Prime number
14. Write a c++ program to calculate factorial of any
number.

#include<iostream.h>
#include<conio.h>int
main()
{
{
clrscr();
inti, fact=l, n;
cout<<"Enteranumber="·
'
cin>>n;
for(i=l;i<=n;i++)
fact=fact*l •
'
cout<<"factorialof'<<n<<"is="<<fact<<endl;
getch();
}
returnO;
}

Output:

Enter a number=6

Factorial is=720
15. Write a C++ program to check whether a year is leap
year or not.

#include<iostream.h>#in
clude<conio.h>
intmain()
{
{
clrscr();
intyear;
cout<<"enterayeartocheck";
cin>>year;
if(year%4==0)
cout<<"isaleapyear\n"<<year; else
cout<<"isnotaleapyear\n"<<year; getch();
}

returnO;
}

Output:

Enterayeartocheck=2004i

s a leap year

Or

Enter a year tocheck=2003

is nota leap year


16. Writeaprogramtofindnumberisoddoreven.

#include<iostream.h>
#include<conio.h>int
main()
{
{
clrscr();
int n;
cout<<"Enteranumber="·
'
cin>>n;
if(n%2==0)
cout<<"Numberiseven="·
'
else
cout<<"Numberisodd="·
'
getch();
}
returnO;
}

Output:

Enteranumber=2

Number is even

Or

Enteranumber=3 Number

is odd
17. Write a c++ program to find L.C.M and H.C.F of two
numbers.

#include<iostream.h>#include<conio.h
>
int main()
{
{
clrscr();
int a, b, x, y, temp, gcd,1cm;
cout<<"Enter first number=";
cin>>a;
cout<<"Entersecondnumber=";
cin>>b;
x=a;
y=b;
while(b!=0)
{
temp=b;
b=a%b;
a=temp;
}
gcd=a;
lcm=(x*y)/gcd;
cout<<"\ngcd:"<<gcd<<"\n";
cout<<"\nlcm:"<<lcm<<"\n";
getch();
}
returnO;
}

Output:

Enter first number =6

Entersecondnumber=10

gcd=2

lcm=30
18. Write a c++ program to demonstratethe usage of
scope resolution operator.

#include
<iostrearn.h>#include<
conio.h>
intx=10;IIGlobalvariable
intmain(){
{
Clrscr();
intx=20;IILocal variable
cout <<"Value of global x: "<< ::x << endl; II Accessingglobal x
cout<<"Value oflocalx: "<<x << endl;II Accessinglocalx
II Calling aglobal
functionglobalFunction();
getch();
}
return0;
}
voidglobalFunction(){
cout<<"InsideglobalFunction()"<<endl; int
x= 30; II Local variable
cout <<"Value of global x: "<< ::x <<endl; II Accessing global x
cout<<"Valueoflocalx:"<< x << endl;II Accessinglocalx
}

Output:
Value of global x: 10

Value of local x: 20

InsideglobalFunction()

Value of global x: 10

Value of local x: 30
19. Write a c++programto accept and displaythe details of
the student using class.

#include <iostream.h>
#include <conio.h>
#include <string.h>
class Student {private:
stringname;
int age;
stringgrade;

public:
IIConstructor
Student(stringn,inta,stringg)
{ name= n;
age= a;
grade=g;
}
string getName()
{ return name;
}
int getAge()
{ return age;
}
string getGrade()
{ return grade;
}
voidsetName(stringn){ name=
n;
}
void setAge(int a)
{ age= a;
}
voidsetGrade(stringg){
grade= g;
}
};
int main()
{
{
Clrscr();
string studentName, studentGrade;
int studentAge;

cout <<"Enter student's name: ";


getline(cin, studentName);

cout <<"Enter student's age: ";


cin >>studentAge;

cout<<"Enterstudent'sgrade:";
cin.ignore();II Ignore the newline character left in the input buffer
getline(cin, studentGrade);

IICreateaStudentobject
Studentstudent(studentName,studentAge,studentGrade);

IIDisplaystudentdetails
cout<<"\nStudentDetails:"<<endl;
cout<<"Name: "<<student.getName()<<endl;
cout <<"Age: "<< student.getAge() <<endl;
cout<<"Grade:"<<student.getGrade()<<endl;
getch();
}
returnO;
}

Output:

Enter student's name: john

Enter student's age: 18

Enter student's grade: A+

StudentDetails:

Name: John

Age:18

Grade:A+
20. Write aprogram toacceptanddisplay thedetailsofa
employee using class.

#include<iostream.h>#i
nclude<conio.h>class
Employee { private:
stringname;
int id;
string department;
double salary;
public:
Employee(string n, inti, string d,doubles)
{ name= n;
id=i·
'
department=d;
salary= s;
}
string getName()
{ return name;
}
intgetld()
{ return id;
}
string getDepartment()
{ return department;
}
double getSalary()
{ return salary;
}
Setterfunctions
voidsetName(stringn){
name= n;
}
voidsetld(inti)
{ id=i;
}
void setDepartment(string d)
{ department= d;
}void setSalary(doubles) {
salary= s;
}
};
intmain()
{
{
Clrscr();
string employeeName, employeeDepartment;
int employeeid;
doubleemployeeSalary;
cout <<"Enter employee's name: ";
getline(cin, employeeName);
cout <<"Enter employee's ID: ";
cin >>employeeid;
cout<<"Enteremployee'sdepartment:";
cin.ignore();IIIgnorethenewlinecharacterleftintheinputbuffer
getline(cin, employeeDepartment);
cout<<"Enteremployee'ssalary:"; cin
>>employeeSalary;
IICreateanEmployeeobject
Employee employee(employeeName, employeeld,
employeeDepartment,employeesalary);

IIDisplayemployeedetails
cout<<"\nEmployeeDetails:"<<endl;
cout<<"Name:"<<employee.getName()<<endl; cout
<<"ID: "<<employee.getld() << endl;
cout<<"Department:"<<employee.getDepartment()<<endl; cout
<<"Salary: $"<< employee.getSalary() << endl;
getch();
}
returnO;
}

Output:

Enteremployee'sname:JohnDoe

Enter employee's ID: 1234

Enter employee's department: IT

Enteremployee'ssalary:5000.50

EmployeeDetails:

Name: John Doe

ID:1234

Department: IT

Salary: $5000.50
21. Write ac++ program tosortanarray inascending
order.

#include<iostream.h>
#include<conio.h>int
main()
{
{
voidbubbleSort(intarr[],intn){ for
(int i = O; i<n -1;i++){
for (int j = O; j <n -i-1;j++) { if
(arrUJ> arru+ l]){
IISwaparru]andarru+1]
int temp= arru];
arrUJ=arru+1];
arru+1]=temp;
}
}
}
}
intmain(){
{
Clrscr();
int n;
cout <<"Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout <<"Enter the elements of the array:";
for (int i = O; i < n; i++) {
cin>>arr[i];
}
cout<<"Originalarray:";
for (inti= O; i <n; i++)
{ cout <<arr[i] <<"";
}
cout <<endl;
bubbleSort(arr,n);
cout<<"Sortedarrayinascendingorder:"; for
(inti= O; i <n; i++) {
cout<<arr[i]<<"";
}
cout <<endl;
getch();
}
returnO;
}

Output:

Enter the number of elements inthe array: 5

Enter the elements of the array: 3 1 4 2 5

Originalarray:31425

Sortedarrayinascendingorder:1 2345
22. Write a c++ program to demonstratethe usage of
inline function.
#include
<iostream.h>#include<conio.h>
inlineintmax(intx,inty){
return(x>y)?x:y;
}
inline int cube(int n)
{ return n * n * n;
}
intmain(){{
Clrscr();
inta=5,b=7;
intmaxVal,cubeVal;
maxVal= max(a, b); II Call to inline function max
cout <<"Maximum value: "<<maxVal << endl;
cubeVal= cube(a);II Callto inline functioncube
cout <<"Cube of"<<a<<"is: "<<cubeVal<<endl; cubeVal =
cube(b); II Call to inline functioncube
cout <<"Cube of"<< b <<"is: "<<cubeVal<< endl;
getch();}
returnO;
}

Output:

Maximumvalue:7

Cubeof5is:125

Cubeof7is:343
23. Write a c++ program to demonstratethe simple
inheritance.

#include
<iostream.h>#include<
conio.h>#include
<string.h>
// Base class
class Vehicle {
protected:
stringbrand;
int year;
public:
Vehicle(stringb,inty):brand(b), year(y){} void
displaylnfo() {
cout<<"Brand:"<<brand<<endl; cout
<<"Year: "<<year<< endl;
}
};
//Derivedclass
class Car : public Vehicle {
private:
string model;
public:
Car(string b,inty,stringm):Vehicle(b,y),model(m){} void
displayDetails() {
displaylnfo();//Callthebaseclassfunction
cout <<"Model: "<<model<< endl;
}
};
intmain(){
{
Clrscr();
II Create an object of the derived class
Car myCar("Toyota", 2020, "Corolla");
II Call the derived class function
myCar.displayDetails();
getch();
}
return0;
}

Output:

Brand: Toyota Year: 2020 Model:Corolla


2JL W['nu:eaIl]['tDlg['amu:t0@emomt§U:['au:eu:llnell.Il§age1IDJf
CIIDll1l§U:['ll.Il(C[tD)['2lll1l@@e§U:['ll.Il(C[tD)['Ililllaclla§§o

#include<iostream.h>
#include<conio.h>
classPerson{
private:
stringname;
int age;
public:
II Defaultconstructor
Person(){
cout<<"Defaultconstructorcalled"<<endl;
name="Unknown";
age= O;
}

IIParameterizedconstructor
Person(stringn,inta){
cout<<"Parameterized constructor called"<< endl;
name= n;
age=a;
}

II CopyconstructorPerson(constPer
son&other){
cout<<"Copy constructor called"<<endl; name
= other.name;
age=other.age;
}
IIDestructor
~Person(){
cout<<"Destructorcalledfor"<<name<<end];
}
II Getterfunctions
string getName() canst
{ returnname;
}
intgetAge()canst
{ returnage;
}
};
intmain()
{
{

Clrscr();

II Defaultconstructor
Personpl;
cout<<"Name:"<<pl.getName()<<",Age:"<<pl.getAge()
<<endl;
II Parameterizedconstructor
Personp2("JohnDoe",30);
cout<<"Name:"<<p2.getName()<<",Age:"<<p2.getAge()
<<endl;
II Copyconstructor
Personp3(p2);
cout<<"Name:"<<p3.getName()<<",Age:"<<p3.ge
tAge();
getch();
returnO;
}

Output:

Default constructor called

Name: Unknown, Age: 0

Parameterized constructor called

Name: John Doe, Age: 30

Copy constructor calledName:

John Doe, Age: 30 Destructor

calledfor JohnDoe Destructor

calledfor JohnDoe

DestructorcalledforUnknown
25. Write a c++ program to demonstratethe usage of
friend function.

#include<iostream.h>#
include<conio.h>Clas
s sample
{
int a;
int b;
public:
void setvalue() {a=25;b=40;}
friend float mean (samples);
};
floatmean(samples)
{
returnfloat(s.a+s.b)/2.0;
}
int main()
{
Clrscr();
Sample x;
x.setvalue();
cout<<"mean value="<<mean(x)<<"\n";
getch();
returnO;
}

Output:

Meanvalue =32.5
26. Write a c++ program to demonstratethe usage of endl
and setw.

#include <iostream.h>
#include <conio.h>int
main() {
{
Clrscr();
stringname="JohnDoe";
int age= 25;
doublesalary=5000.75;
//Usingsetwforformattingoutput
cout <<setw(l5) <<"Name"<<setw(l0) <<"Age"<<setw(l5) <<"Salary"<<
endl;
cout << setw(l5) <<name<< setw(l0) <<age<< setw(l5)
<<salary<<endl;
//Usingendlfornewline
cout<<"Hello"<<endl<<"World"<<endl·,
//Usingendltoflushtheoutputbuffer cout
<<"Printing numbers: ";
for(inti=1;i<=5;i++)
{ cout<<i<<"",·
cout.flush();//Flushtheoutputbuffer
}
cout<<endl;
getch();
}
return0;
}

Output:

NameAge Salary

JohnDoe25 5000.75

Hello World
Printingnumbers:12345
27. Write a c++ program to display employee information
using multiple inheritance.

#include <iostream.h>
#include <conio.h>
//Baseclassforpersonalinformation
class Personallnfo {
protected:
stringname;
int age;
public:
Personallnfo(stringn,inta):name(n),age(a){} void
displayPersonallnfo() {
cout <<"Name: "<<name<< endl;
cout <<"Age: "<<age<< endl;
}
};
//Baseclassforemployeedetails
class EmployeeDetails {
protected:
string department;
double salary;
public:
EmployeeDetails(stringd,doubles) :department(d),salary(s){}
void displayEmployeeDetails() {
cout <<"Department:"<< department<< endl;
cout<<"Salary:$"<<salary<<endl;
}
};
//DerivedclassinheritingfrombothPersonallnfoandEmployeeDetails class
Employee :public Personallnfo, public EmployeeDetails{
public:
Employee(stringn,inta,stringd,doubles)
:Personallnfo(n,a),EmployeeDetails(d,s){} void
displayEmployeelnfo() {
displayPersonallnfo();
displayEmployeeDetails();
}
};
intmain(){
Employeeemp("JohnDoe",35,"IT",5000.0);
emp.displayEmployeelnfo();
getch();
}
return0;
}

Output:

Name:JohnDoe

Age:35

Department: IT

Salary:$5000.00
28. Write a program to demonstrate multilevel
inheritance.

#include<iostream.h>#
include<conio.h>Clas
s student
{
protected:
int roll_number;
public:
void get_number(int);
void put_number(void);
};
Voidstudent::get_number(inta)
{
Roll_number=a;
}
Voidstudent::put_number()
{
Cout<<"rollnumber:"<<roll_number<<"\n";
}
Classtest:publicstudent
{
protected:
float subl;
floatsub2;
public:
void get_marks(float,float);
void put_marks(void);
};
Voidtest::get_marks(floatx,floaty)
{
Subl=x·
'
Sub2=y;
}
Voidtest::put_marks()
{
Cout<<"marks insubl="<<subl<<"\n";
Cout<<"marksinsub2="<<sub2<<"\n";
}
Classresult:publictest
{
floattotal;
public:
voiddisplay(void);
};
Voidresult::display(void)
{
Total=sub1+sub2;
put_number();
put_marks();
Cout<<"total="<<total<<"\n";
}
intmain()
clrscr();
{
result studentl;
studentl.get_number(l11);
studentl.get_marks(75.0,59.5);
studentl.display();
getch();
returnO;
}
Output:

Roll number:111

Marks in subl:75

Marksinsub2:59.5

Total=134.5
29. Write a c++ program to overload+ operator toadd
two complex numbers.

#include
<iostream.h>#include
<conio.h>class
Complex { private:
double real;
doubleimag;
public:
IIConstructor
Complex(doubler=0.0,doublei=0.0):real(r),imag(i){}

IIOverloaded+operator
Complexoperator+(constComplex& other){
Complex result;
result.real=real+other.real;
result.imag=imag +other.imag;
return result;
}

IIOverloaded<<operatorforoutput
friendostream&operator<<(ostream&out,constComplex&c);
};

IIOverloaded<<operatorforoutput
ostream& operator<<(ostream& out, const Complex& c)
{ out<< c.real <<"+" << c.imag <<"i";
returnout;
}

intmain(){
{
Clrscr();
Complexcl(3.0,4.0);
Complexc2(1.5,2.5);
Complexc3=c1+c2;IIOverloaded+operator

cout<<"cl="<<cl<<endl·
'
cout<< c2= <<c2<<endl·
11 11

'
cout<< c3 =cl +c2 = <<c3<<endl;
11 11

getch();
}
returnO·
'
}

Output:

cl=3+4i

c2=1.5+2.5i

c3=cl+c2 =4.5+6.Si
30. Write a c++ program tofind the sum of natural
numbers using for loop.

#include
<iostream.h>#include
<conio.h>
intmain(){
{
clrscr();
intn,sum=O;
cout <<"Enter the number of natural numbers to sum: ";
cin >> n;
for(inti=1;i<=n;i++){
sum+=i·
'
}
cout <<"The sumof thefirst"<< n <<" natural numbers is: "<<sum<<endl;
getch();
}
returnO;
}

Output:

Enter the number of natural numbers to sum:10

The sum of the first 10 natural numbers is: 55


31. Writeaprogramtoimplementconceptofconstructor.

#include <iostream.h>
#include <conio.h>
class Person {
private:
stringname;
int age;
public:
II Default constructor
Person() {
name="Unknown"·
'
age=O;
cout<<"Defaultconstructorcalled"<<endl;
}
IIParameterized constructor
Person(stringn, int a) {name
=n;
age=a;
cout<<"Parameterizedconstructorcalled"<<endl;
}
II Copy constructor
Person(const Person& p)
{ name = p.name;
age=p.age;
cout<<"Copyconstructorcalled"<<endl;
}
voiddisplaylnfo(){
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};

intmain(){
II Creating objects using different constructors
Person p1; II Default constructor
Person p2("John", 25);II Parameterized constructor
Person p3(p2); II Copy constructor
// Displaying object information
pl.displaylnfo();
p2.displaylnfo();
p3.displaylnfo();

returnO;
}

Output:

Default constructor called

Parameterized constructorcalled

Copy constructor called

Name:Unknown,Age:0

Name: John, Age: 25

Name: John, Age: 25


32. Writeaprogramtoimplementconceptofdestructor.

#include<iostream.h>
#include<conio.h>int
count=O;
classalpha
{
public:
alpha()
{
Count++;
Cout<<"\nno.ofobjectcreated"<<count;
}
~alpha()
{
Cout<<"\nno.ofobject destroyed"<<count;
Count--·
'
}
};
int main()
{
Cout<<"\n\nEnter Main\n";
alpha Al,A2,A3,A4;
{
Cout<<"\n\nEnterblockl\n";
Alpha AS;
}
{
Cout<<"\n\nEnter block2\n";
Alpha A6;
}
Cout<<"\n\nRe-entermain\n";
getch();
returnO;
}
Output:
Entermain

No.of object created1

No.of object created 2

No.of object created 3

No.of object created 4

Enter blockl

No. of object createdS

No.ofobjectdestroyedS

Re-enter main

No.of object destroyed 4

No.of object destroyed 3

No.ofobject destroyed 2

No.ofobjectdestroyed1
33. Write a program to implement concept of copy
constructor.

#include<iostream.h>#i
nclude<conio.h>Class
code
{
int id;
public:
code(){}
code(int a) {id=a;}
code(code &x)
{
id=x.id;
}
Voiddisplay(void)
{
Cout<<id;
}
};
intmain()
{
Clrscr();Code
A(lOO); Code
B(A);
Codec=A·
'
CodeD;
D=A;
Cout<<"\nidofA:"A.display();
Cout<<"\n idofB:"B.display();
Cout<<"\n id of c:"c.display();
Cout<<"\nidofD:"D.display();
getch();
returnO;
}
Output:

idofA:100

idofB:100

id ofc:100

idofD:100
34. Write a program to implement concept of
parametrized constructor.

#include <iostream.h>
#include <conio.h>
class Student {private:
stringname;
int age;
double gpa;
public:
Student(stringn,inta,doubleg)
{ name= n;
age= a;
gpa=g;
}
voiddisplaylnfo(){
cout<<"Name:"<< name<<",Age:"<<age<<",GPA:"<<gpa<<endl;
}
};
intmain()
{
Clrscr();
Studentsl("John",20,3.8);
Students2("Alice",22,3.5);
Students3("Bob",19,4.0);
sl .displayInfo();
s2.displayInfo();
s3.displaylnfo();
getch();
return0;
}
Output:

Name: John,Age:20,GPA:3.8

Name:Alice,Age:22,GPA:3.5

Name:Bob,Age:19,GPA:4.0
35. Write a program to implement concept of template
class.

#include
<iostream.h>#include
<conio.h>
IITemplateclass
template <class T>
class Box {private:
Tdata;
public:
Box(T value)
{ data = value;
}
TgetData()
{ return data;
}
void setData(T value)
{ data = value;
}
};
intmain() {
clrscr();
II Creating objects of Box class for different data types
Box<int> intBox(42);
Box<double> doubleBox(3.14);
Box<string>stringBox("Hello, World!");
IIAccessingdatamembers
cout <<"Integer Box: "<<intBox.getData() << endl;
cout<<"DoubleBox:"<<doubleBox.getData()<<endl;
cout <<"String Box: "<< stringBox.getData() <<endl;

II Modifying data members


intBox.setData(l00);
doubleBox.setData(2.718);
stringBox.setData("C++ Templates");

IIAccessingdatamembersaftermodification
cout<<"IntegerBox(modified):"<<intBox.getData()<<endl;
cout <<"Double Box (modified): "<<doubleBox.getData() <<endl; cout
<<"String Box (modified): "<<stringBox.getData() <<endl; getch();
returnO;
}

Output:

IntegerBox:42

DoubleBox:3.14

String Box: Hello, World!

Integer Box (modified): 100

DoubleBox(modified): 2.718

StringBox(modified):C++Templates
36. Writeaprogramtoimplementconceptoftemplatefunction.

#include
<iostream.h>#include
<conio.h>
IITemplatefunctiontocalculatethemaximumoftwovalues
template<typenameT>T
max(T a, T b) {
return(a>b)?a:b;
}

intmain() {
clrscr();
II Using the max() function for different data types
int maxlnt = max(l0, 20);
double maxDouble =max(3.14, 2.718);
char maxChar = max('a', 'z');

cout<<"Maximumof10and20:"<<maxlnt<<endl;
cout <<"Maximum of 3.14 and 2.718: "<<maxDouble<< endl;
cout<<"Maximumof'a' and'z':"<<maxChar<< endl;
getch();
return0;
}

Output:

Maximumof10and20:20

Maximum of 3.14 and 2.718: 3.14 Maximum of 'a' and 'z': z


37. Write a program to implement concept of exception
handling.

#include
<iostream.h>#include
<conio.h>
double divide(double numerator, double denominator) {if
(denominator == 0) {
throwruntime_error("Divisionbyzeroisnotallowed.");
}
returnnumeratorIdenominator;
}
intmain(){
doublenuml,num2;
double result;
try{
cout<<"Enterthefirstnumber:"; cin
>> numl;
cout<<"Enterthesecondnumber:"; cin
>> num2;
result=divide(numl,num2);
cout<<"Result:"<<numl<<"I" <<num2<<"="<<result<<endl;
}catch (const runtime_error& e)
{ cerr<<"Error:"<<e.what()<<endl;
}
getch();
returnO;
}

Output:

Enter the first number: 10 Enterthesecond number:2 Result: 10 /2 = 5

You might also like