#include <conio.h>
and
getch()
.
Question: Write a C++ program that calculates the sum and average of n integers entered by the user.
#include<iostream>
#include<conio.h> // Not in C++11 and later
using namespace std;
int main(){
int temp,n,sum=0;
float avg;
cout<<"Enter the total number of elements"<<endl;
cin>>n;
cout<<"Enter n values"<<endl;
for (int i=0; i<n; i++){
cout<<"Enter element "<<i+1<<endl;
cin>>temp;
sum+=temp;
}
cout<<"Sum = "<<sum<<"\nAverage = "<<sum/n<<endl;
getch(); // Not in C++11 and later
return 0;
}
Enter the total number of elements 5 Enter n values Enter element 1 1 Enter element 2 2 Enter element 3 3 Enter element 4 4 Enter element 5 5 Sum = 15 Average = 3
Question: Write a C++ program that calculates the sum and average of n integers entered by the user using array.
#include<iostream>
#include<conio.h> //for getch()
using namespace std;
int main(){
int a[50],n,sum=0;
float avg;
cout<<"Enter the total number of elements"<<endl;
cin>>n;
cout<<"Enter n values"<<endl;
for (int i=0; i<n; i++){
cin>>a[i];
sum+=a[i];
}
cout<<"Sum = "<<sum<<"\nAverage = "<<sum/n<<endl;
getch();
return 0;
}
Enter the total number of elements 5 Enter n values 1 2 3 4 5 Sum = 15 Average = 3
Question: Write a C++ program that calculates the average of two numbers entered by the user.
#include<iostream.h>
#include<conio.h> //for getch()
int main(){
int a,b;
float avg;
cout<<"Enter two numbers"<<endl;
cin>>a>>b;
avg=(a+b)/2.0;
cout<<"Average of "<<a<<" and "<<b<<" is "<<avg<<endl;
getch();
return 0;
}
Enter two numbers 5 6 Average of 5 and 6 is 5.5
Question: Write a C++ program that accepts the name, roll number, and marks of a student, then displays the student's details using a class.
#include <iostream>
#include <conio.h> //for getch() comment this line if you using visual studio 2010 or older
#include <string>
using namespace std;
class Student {
string name;
int roll;
float marks;
public:
void display() {
cout << "Name: " << name << endl;
cout << "Roll: " << roll << endl;
cout << "Marks: " << marks << endl;
}
void set(string n, int r, float m) {
name = n;
roll = r;
marks = m;
}
};
int main(){
Student s1;
string name;
int roll;
float marks;
cout << "Enter name, roll and marks of student" << endl;
cin >> name >> roll >> marks;
s1.set(name, roll, marks);
s1.display();
getch();
return 0;
}
Enter name, roll and marks of student Ashwith 29 90 Name: Ashwith Roll: 29 Marks: 90
Question: Write a C++ program that stores and displays the details of n students. The program should ask the user to input the name, roll number, and marks of each student, and then display the details of all the students.
#include <iostream>
// #include <conio.h> //for getch() comment this line if you using visual studio 2010 or older
#include <string>
using namespace std;
class Student {
string name;
int roll;
float marks;
public:
void display() {
cout << "Name: " << name << endl;
cout << "Roll: " << roll << endl;
cout << "Marks: " << marks << endl;
}
void set(string n, int r, float m) {
name = n;
roll = r;
marks = m;
}
};
int main(){
Student s[3];
string name;
int roll,n;
float marks;
cout << "Enter number of students" << endl;
cin >> n;
for(int i=0;i<n;i++){
cout << "Enter name, roll and marks of student" << endl;
cin >> name >> roll >> marks;
s[i].set(name, roll, marks);
}
cout << "Details of students" << endl;
for(int i=0;i<n;i++){
s[i].display();
}
// getch();
return 0;
}
Enter number of students 3 Enter name, roll and marks of student Ashwith 29 90 Enter name, roll and marks of student Arya 24 90 Enter name, roll and marks of student Arnav 23 90 Details of students Name: Ashwith Roll: 29 Marks: 90 Name: Arya Roll: 24 Marks: 90 Name: Arnav Roll: 23 Marks: 90
Question: Write a C++ program that swaps the values of two integers using pass-by-reference.
#include<iostream>
#include<conio.h>
using namespace std;
void swap(int &x, int &y){
x = x + y;
y = x - y;
x = x - y;
}
int main(){
int x = 10,y = 20;
cout<<"Before Swapping\nx = "<<x<<endl<<"y = "<<y<<endl;
swap(x,y);
cout<<"After Swapping\nx = "<<x<<endl<<"y = "<<y<<endl;
getch();
return 0;
}
Before Swapping x = 10 y = 20 After Swapping x = 20 y = 10
Question: Write a C++ program that swaps the values of two integers using pass-by-value.
#include<iostream>
#include<conio.h>
using namespace std;
int swap(int x, int y){
int temp = x;
x = y;
y = x;
cout<<"After Swapping\nx = "<<x<<endl<<"y = "<<y<<endl;
return 0;
}
int main(){
int x = 10,y = 20;
cout<<"Before Swapping\nx = "<<x<<endl<<"y = "<<y<<endl;
swap(x,y);
getch();
return 0;
}
Before Swapping x = 10 y = 20 After Swapping x = 20 y = 10
Question: Write a C++ program that swaps the values of two integers using pointers.
#include <iostream>
#include <conio.h> //for getch()
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10;
int y = 20;
std::cout << "Before swapping: x = " << x << ", y = " << y << std::endl;
swap(&x, &y);
std::cout << "After swapping: x = " << x << ", y = " << y << std::endl;
getch()
return 0;
}
Before swapping: x = 10, y = 20 After swapping: x = 20, y = 10
Question: Write a C++ program that demonstrates how to use a public member variable in a class. The program should display the value of a public variable x through a member function.
#include<iostream>
#include<conio.h> // Not in C++11 and later
using namespace std;
class Disp{
public:
int x;
void display(){
cout<<"x = "<<x<<endl;
}
};
int main(){
Disp obj1;
obj1.x = 5;
obj1.display();
getch(); // Not in C++11 and later
return 0;
}
x = 5
Question: Write a C++ program that demonstrates the use of public and private members in a class. The program should include a class with a public variable and a private variable, along with functions to set and display both of them.
#include<iostream>
#include<conio.h> // Not in C++11 and later
using namespace std;
class Disp{
int y;
public:
int x;
void display(){
cout<<"x = "<<x<<endl;
}
void setY(int val){
y = val;
}
void showY(){
cout<<"y = "<<y<<endl;
}
};
int main(){
Disp obj1;
obj1.x = 5;
obj1.display();
obj1.setY(10);
obj1.showY();
getch(); // Not in C++11 and later
return 0;
}
x = 5 y = 10
Question: Write a C++ program that demonstrates the use of friend classes. The program should have two classes, sample1 and sample2. The sample1 class should be able to access the private members of the sample2 class through a friend relationship.
#include <iostream>
#include <conio.h> // Not in C++11 and later
using namespace std;
class sample1;
class sample2
{
int y, z;
public:
void setValues(int a, int b)
{
y = a;
z = b;
}
friend class sample1;
};
class sample1
{
public:
void display1(sample2 s)
{
cout << "y = " << s.y << endl;
}
void display2(sample2 s)
{
cout << "z = " << s.z << endl;
}
};
int main()
{
sample1 s1;
sample2 s2;
s2.setValues(10, 20);
s1.display1(s2);
s1.display2(s2);
getch(); // Not in C++11 and later
return 0;
}
y = 10 z = 20
Question: Write a C++ program that demonstrates the use of friend functions to calculate the area of a rectangle. The program should involve a Rectangle class with private data members for length and breadth, and a friend function Area() that calculates the area of the rectangle.
#include<iostream>
#include<conio.h> // Not in C++11 and later
using namespace std;
class Rectangle{
int length;
int breadth;
public:
void setDimensions(int l, int b){
length = l;
breadth = b;
}
friend void Area(Rectangle);
};
void Area(Rectangle r){
cout<<"Area = "<<r.length*r.breadth<<endl;
}
int main(){
Rectangle r;
r.setDimensions(10, 20);
Area(r);
getch(); // Not in C++11 and later
return 0;
}
Area = 200
Question: Write a C++ program that demonstrates the use of friend functions. The program should calculate the mean of two private variables from two different classes using a friend function. The program should involve two classes, sample1 and sample2, and a friend function mean that accesses the private data of both classes
#include<iostream>
#include<conio.h> // Not in C++11 and later
using namespace std;
class sample2;
class sample1{
int a;
public:
void setA(int x){
a = x;
}
friend float mean(sample1, sample2);
};
class sample2{
int b;
public:
void setB(int y){
b = y;
}
friend float mean(sample1, sample2);
};
float mean(sample1 s1, sample2 s2){
return float(s1.a + s2.b)/2;
}
int main(){
sample1 s1;
sample2 s2;
s1.setA(25);
s2.setB(30);
cout<<"Mean = "<<mean(s1, s2)<<endl;
getch(); // Not in C++11 and later
return 0;
}
Mean = 27.5
Question: Write a C++ program that demonstrates the use of copy constructors. The program should include a class with a default constructor, a parameterized constructor, and a copy constructor. When an object is copied, the copy constructor should be called, and a message should be displayed.
#include <iostream>
#include <conio.h> // Not in C++11 and later
using namespace std;
class example{
int data;
public:
example () {} // Default Constructor
example(int i){ // Parameterized Constructor
data = i;
}
example(example &sample){ // Copy Constructor
data = sample.data;
cout<<"Copy Constructor Called "<<data<<endl;
}
}
int main(){
example e1(10);
example e2(e1);
getch(); // Not in C++11 and later
return 0;
}
Copy Constructor Called 10
Question: Write a C++ program to create a Student class using a default constructor. The program should prompt the user to enter the student's name, roll number, and branch, and then display the student details using a member function.
#include<iostream>
#include<conio.h>
#include <string>
using namespace std;
class Student{
string name,branch;
int rollno;
public:
Student(); // Default Constructor declaration
void display();
};
Student::Student(){ // Default Constructor definition
cout<<"Enter the Name: "<<endl;
cin>>name;
cout<<"Enter the Roll No.: "<<endl;
cin>>rollno;
cout<<"Enter the Branch: "<<endl;
cin>>branch;
}
void Student::display(){
cout<<"\nStudent Details"<<endl;
cout<<"Name : "<<name<<"\nRoll No. :"<<rollno<<"Branch : "<<branch<<endl;
}
int main(){
Student s;
s.display();
getch();
return 0;
}
Enter the Name: Ashwith Enter the Roll No.: 29 Enter the Branch: ECE Student Details Name : Ashwith Roll No. :29Branch : ECE
Question: Write a C++ program that demonstrates the use of constructors and destructors. The program should track and display the number of objects created and destroyed. The alpha class should maintain a static counter that is incremented when an object is created and decremented when an object is destroyed. The program should also show the impact of block-scoped objects on the counter.
#include <iostream>
#include <conio.h> // Not in C++11 and later
using namespace std;
int count = 0;
class alpha{
public:
alpha(){
count++;
cout<<"No. of object created "<<count<<endl;
}
~alpha(){
count--;
cout<<"No. of object remaining "<<count<<endl;
}
};
int main(){
cout<<"Enter main function"<<endl;
alpha a1, a2, a3,a4;
{
cout<<"Entering Block 1"<<endl;
alpha a5;
}
{
cout<<"Entering Block 2"<<endl;
alpha a6;
}
cout<<"Re-Entering main function"<<endl;
getch(); // Not in C++11 and later
return 0;
}
Enter main function No. of object created 1 No. of object created 2 No. of object created 3 No. of object created 4 Entering Block 1 No. of object created 5 No. of object remaining 4 Entering Block 2 No. of object created 5 No. of object remaining 4 Re-Entering main function No. of object remaining 3 No. of object remaining 2 No. of object remaining 1 No. of object remaining 0
Question: Write a C++ program that uses two classes, xyz and abc, where each class has a private integer member variable. Both classes should have a member function to set the value of the integer. Additionally, implement a friend function max() that compares the values of these two classes and prints the greater value.
#include<iostream>
#include<conio.h> // Not in C++11 and later
using namespace std;
class abc;
class xyz{
int x;
public:
void setvalue(int i){
x = i;
}
friend void max(xyz, abc);
};
class abc{
int a;
public:
void setvalue(int i){
a = i;
}
friend void max(xyz, abc);
};
void max(xyz m, abc n){
if(m.x > n.a){
cout<<"Max value is "<<m.x<<endl;
}
else{
cout<<"Max value is "<<n.a<<endl;
}
}
int main(){
xyz m;
abc n;
m.setvalue(10);
n.setvalue(20);
max(m, n);
getch(); // Not in C++11 and later
return 0;
}
Max value is 20
Question: Write a C++ program to implement a Student class that uses a parameterized constructor to initialize the student's name, roll number, and branch. The program should take input for the student's details and display them using a member function.
#include<iostream>
#include<conio.h>
#include <string>
using namespace std;
class Student{
string name,branch;
int rollno;
public:
Student(string,int,string); // Parameterized Constructor declaration
void display();
};
Student::Student(string n,int r,string b){ // Parameterized Constructor definition
name = n;
rollno = r;
branch = b;
}
void Student::display(){
cout<<"\nStudent Details"<<endl;
cout<<"Name : "<<name<<"\nRoll No. :"<<rollno<<"Branch : "<<branch<<endl;
}
int main(){
string name, branch;
int rollno;
cout<<"Enter the Name: "<<endl;
cin>>name;
cout<<"Enter the Roll No.: "<<endl;
cin>>rollno;
cout<<"Enter the Branch: "<<endl;
cin>>branch;
Student s(name,rollno,branch);
s.display();
getch();
return 0;
}
Enter the Name: Ashwith Enter the Roll No.: 29 Enter the Branch: ECE Student Details Name : Ashwith Roll No. :29 Branch : ECE
Question: Write a C++ program that uses two classes, A and B, where each class contains a private integer member. Implement a friend function swap() to exchange the values of the two integer members from different classes. The program should display the values before and after swapping.
#include <iostream>
#include <conio.h> // Not in C++11 and later
using namespace std;
class B;
class A{
public:
int a;
void setvalue(int i){
a = i;
}
friend void swap(A &, B &);
};
class B{
public:
int b;
void setvalue(int i){
b = i;
}
friend void swap(A &, B &);
};
void swap(A &m, B &n){
int temp = m.a;
m.a = n.b;
n.b = temp;
}
int main(){
A m;
B n;
m.setvalue(10);
n.setvalue(20);
cout<<"Before Swapping\na = "<<m.a<<endl<<"b = "<<n.b<<endl;
swap(m, n);
cout<<"After Swapping\na = "<<m.a<<endl<<"b = "<<n.b<<endl;
getch(); // Not in C++11 and later
return 0;
}
Before Swapping a = 10 b = 20 After Swapping a = 20 b = 10
Question: Write a C++ program to add two complex numbers using operator overloading and display the result.
#include <iostream>
#include <conio.h>
using namespace std;
class Complex{
float real;
float img;
public:
Complex(float r,float i);
Complex operator +(const Complex&);
void show();
};
Complex::Complex(float r,float i){
real = r;
img = i;
}
void Complex::show(){
if (img>0){
cout<<real<<"+"<<img<<"i"<<endl;
}else{
cout<<real<<img<<"i"<<endl;
}
}
Complex Complex::operator +(const Complex &other){
float r = real + other.real;
float i = img + other.img;
Complex sum(r,i);
return sum;
}
int main(){
Complex complex1(1,1);
Complex complex2(1,5);
Complex complex3(4,1);
Complex complex4(-10,-5);
Complex sum1 = complex1+complex2;
sum1.show();
Complex sum2 = complex3+complex4;
sum2.show();
getch();
return 0;
}
2+6i -6-4i
Question: Write a C++ program using an inline function to find the maximum of two integers.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
inline int Max(int x, int y)
{
return (x > y) ? x : y;
}
int main()
{
cout << "Max (20,10): " << Max(20, 10) << endl;
cout << "Max (0,200): " << Max(0, 200) << endl;
cout << "Max (100,1010): " << Max(100, 1010) << endl;
getch();
return 0;
}
Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010
Question: Write a C++ program to overload the unary minus operator to negate the values of the data members of a class Space that represents a point in 3D space.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
class Space
{
int x, y, z;
public:
void getdata(int a, int b, int c);
void display(void);
void operator -();
};
void Space::getdata(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void Space::display(void)
{
cout << "x:" << x << " y:" << y << " z:" << z << "\n";
}
void Space::operator -()
{
x = -x;
y = -y;
z = -z;
}
int main()
{
Space S;
S.getdata(10, -20, 30);
cout << "S: ";
S.display();
-S;
cout << "S: ";
S.display();
getch();
return 0;
}
S: x:10 y:-20 z:30 S: x:-10 y:20 z:-30
Question: Write a program to demonstrate Multilevel Inheritance.
#include <iostream>
#include <conio.h> // for getch()
#include <string>
using namespace std;
class Studet
{
protected:
string name;
int roll;
public:
void get_data(int r, string n)
{
name = n;
roll = r;
}
void put_data()
{
cout << "Name: " << name << endl;
cout << "Roll No: " << roll << endl;
}
};
class Test : public Studet
{
protected:
float sub1, sub2;
public:
void get_test(float m1,float m2)
{
sub1 = m1;
sub2 = m2;
}
void put_test()
{
cout << "Marks in Subject 1: " << sub1 << endl;
cout << "Marks in Subject 2: " << sub2 << endl;
}
};
class Result : public Test
{
float total;
public:
void display()
{
total = sub1 + sub2;
put_data();
put_test();
cout << "Total Marks: " << total << endl;
}
};
int main(){
string name;
int rollno;
float subj1,subj2;
Result r;
cout<<"Enter the roll number of the student: "<<endl;
cin>>rollno;
cout<<"Enter the name of the student: "<<endl;
cin>>name;
cout<<"Enter the marks of two subjects: "<<endl;
cin>>subj1>>subj2;
r.get_data(rollno,name);
r.get_test(subj1,subj2);
cout<<"\n\n**********RESULT**********\n\n";
r.display();
cout<<"\n\n**************************\n\n";
getch();
return 0;
}
Enter the roll number of the student: 29 Enter the name of the student: Ashwith Enter the marks of two subjects: 99 100 **********RESULT********** Name: Ashwith Roll NO: 29 Marks in Subject 1: 99 Marks in Subject 2: 100 Total Marks: 199 **************************
Question: Write a program to demonstrate the use of private inheritance.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
class B
{
int a;
public:
int b;
void get_ab();
int get_a();
void show_a();
};
void B::get_ab()
{
cout << "Enter values for a and b: ";
cin >> a >> b;
}
int B::get_a()
{
return a;
}
void B::show_a()
{
cout << "a = " << a << endl;
}
class D : private B
{
int c;
public:
void mul();
void display();
};
void D::mul()
{
get_ab();
c = b * get_a();
}
void D::display()
{
show_a();
cout << "b = " << b << endl;
cout << "c = " << c << endl;
}
int main()
{
D d;
d.mul();
d.display();
getch();
return 0;
}
Enter values for a and b: 5 10 a = 5 b = 10 c = 50
Question: Write a program to demonstrate the use of private inheritance.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
class B
{
int a;
public:
int b;
void get_ab();
int get_a();
};
void B::get_ab()
{
cout << "Enter values for a and b: ";
cin >> a >> b;
}
int B::get_a()
{
return a;
}
class D : public B
{
int c;
public:
void mul();
void display();
};
void D::mul()
{
c = b * get_a();
}
void D::display()
{
cout << "a = " << get_a()<<endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
}
int main()
{
D d;
d.get_ab();
d.mul();
d.display();
getch();
return 0;
}
Enter values for a and b: 4 8 a = 4 b = 8 c = 32
Question: Write a program to calculate the area of a triangle and a rectangle using virtual functions.
#include<iostream>
#include<conio.h> //for getch()
using namespace std;
class geofig{
public:
float a,b,area;
void get_data(){
cin>>a>>b;
}
virtual void display(){
// Empty
}
};
class tri:public geofig{
public:
void display(){
area=0.5*a*b;
cout<<"Height and base of the triangle are: "<<a<<" and "<<b<<endl;
cout<<"Area of the triangle is: "<<area<<endl;
}
};
class rect:public geofig{
public:
void display(){
area=a*b;
cout<<"Length and breadth of the rectangle are: "<<a<<" and "<<b<<endl;
cout<<"Area of the rectangle is: "<<area<<endl;
}
};
int main(){
geofig *ptr;
tri t1;
rect r1;
char c;
cout<<"Enter the type of figure (t/r): "<<endl;
cin>>c;
if(c=='t'){
cout<<"Enter the height and base of the triangle: "<<endl;
ptr=&t1;
ptr->get_data();
ptr->display();
}
else if(c=='r'){
cout<<"Enter the length and breadth of the rectangle: "<<endl;
ptr=&r1;
ptr->get_data();
ptr->display();
}
else{
cout<<"Invalid input"<<endl;
}
getch();
return 0;
}
Enter the type of figure (t/r): t Enter the height and base of the triangle: 5 10 Height and base of the triangle are: 5 and 10 Area of the triangle is: 25
Question: Write a program to demonstrate the use of pointers to objects.
#include<iostream>
#include<conio.h> //for getch()
using namespace std;
class Date{
private:
int day,month,year;
public:
Date(){
day=month=year=0;
}
void setDate(int d,int m,int y){
day=d;
month=m;
year=y;
}
void printDate(){
cout<<"Date: "<<day<<"/"<<month<<"/"<<year<<endl;
}
};
int main(){
Date D1,*dptr;
cout<<"Initializing using the object"<<endl;
D1.setDate(2,12,2024);
cout<<"Printing using the object"<<endl;
D1.printDate();
dptr=&D1;
cout<<"Printing using the object pointer"<<endl;
dptr->printDate();
cout<<"Initializing using the object pointer"<<endl;
dptr->setDate(3,12,2024);
cout<<"Printing using the object"<<endl;
D1.printDate();
cout<<"Printing using the object pointer"<<endl;
dptr->printDate();
getch();
return 0;
}
/*
OUTPUT
Initializing using the object
Printing using the object
Date: 2/12/2024
Printing using the object pointer
Date: 2/12/2024
Initializing using the object pointer
Printing using the object
Date: 3/12/2024
Printing using the object pointer
Date: 3/12/2024
*
a program to demonstrate the use of pointers to objects. #include#include //for getch() using namespace std; class Date{ private: int day,month,year; public: Date(){ day=month=year=0; } void setDate(int d,int m,int y){ day=d; month=m; year=y; } void printDate(){ cout<<"Date: "< printDate(); cout<<"Initializing using the object pointer"< setDate(3,12,2024); cout<<"Printing using the object"< printDate(); getch(); return 0; } /* OUTPUT Initializing using the object Printing using the object Date: 2/12/2024 Printing using the object pointer Date: 2/12/2024 Initializing using the object pointer Printing using the object Date: 3/12/2024 Printing using the object pointer Date: 3/12/2024
Question: Write a simple program to demonstrate the use virtual functions.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
class Base{
public:
void display(){
cout<<"Display Base class"<<endl;
}
virtual void show(){
cout<<"Show Base class"<<endl;
}
};
class Derived:public Base{
public:
void display(){
cout<<"Display Derived class"<<endl;
}
void show(){
cout<<"Show Derived class"<<endl;
}
};
int main(){
Base b;
Derived d;
Base *bptr;
cout<<"bptr points to Base class"<<endl;
bptr=&b;
bptr->display();
bptr->show();
cout<<"bptr points to Derived class"<<endl;
bptr=&d;
bptr->display();
bptr->show();
getch();
return 0;
}
bptr points to Base class Display Base class Show Base class bptr points to Derived class Display Base class Show Derived class
Question: Write a program to convert infix expression to postfix expression using stack.
#include <iostream>
#include <stack>
#include <conio.h>
#include <string>
using namespace std;
// Function to return precedence of operators
int precedence(char ch)
{
if (ch == '+' || ch == '-')
return 1;
else if (ch == '*' || ch == '/')
return 2;
else if (ch == '^')
return 3;
else
return -1;
}
// Function to convert infix to postfix
void infixToPostfix(string s)
{
stack<char> st;
string result = "";
for (int i = 0; i < s.length(); i++)
{
char c = s[i];
// If the scanned character is an operand, add it to output
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
result += c;
// If the scanned character is an '(', push it to the stack
else if (c == '(')
st.push(c);
// If the scanned character is an ')', pop and output from the stack until an '(' is encountered
else if (c == ')')
{
while (!st.empty() && st.top() != '(')
{
result += st.top();
st.pop();
}
if (!st.empty())
st.pop();
}
// If the scanned character is an operator, pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator.
else
{
while (!st.empty() && precedence(c) <= precedence(st.top()))
{
result += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty())
{
result += st.top();
st.pop();
}
cout << "Postfix expression: " << result << endl;
}
// Main function
int main(){
string exp;
cout << "Enter the infix expression: ";
cin >> exp;
infixToPostfix(exp);
getch();
return 0;
}
Enter the infix expression: A+B+C/D*E(F+G)/H Postfix expression: AB+CD/EFG+*H/+
Question: Write a program to convert postfix expression to infix expression using stack.
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
class Stack
{
public:
char postfix[30];
int s[30];
int result;
int top;
Stack()
{
top = -1;
}
// Fuction to evaluate postfix expression
void evaluateExprssions()
{
for (int i = 0; i < strlen(postfix); i++)
{
char ch = postfix[i];
if (isdigit(ch))
{
s[++top] = ch - '0';
}
else
{
int op2 = s[top--];
int op1 = s[top--];
performOperation(op1, op2, ch);
s[++top] = result;
}
}
}
void performOperation(int op1,int op2,char symbol){
switch (symbol)
{
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
case '^':
case '$':
result = pow(op1, op2);
break;
}
}
};
int main()
{
Stack ob;
cout << "Enter the postfix expression: ";
cin >> ob.postfix;
ob.evaluateExprssions();
cout << "Result: " << ob.result << endl;
return 0;
}
Question: Write a simple program to demonstrate the use of Stack
#include <iostream>
#include <conio.h> // for _getch()
# define stack_size 5
using namespace std;
class stack
{
int top;
int s[stack_size]
public:
int item;
stack()
{
top = -1;
}
void push(int item)
{
if (top >= stack_size - 1)
cout << "Stack Overflow" << endl;
else
s[++top] = item;
cout << item << " pushed into stack" << endl;
}
void pop()
{
if (top < 0)
cout << "Stack is empty" << endl;
else
cout << s[top--] << " popped from stack" << endl;
}
void display()
{
if (top < 0)
cout << "Stack is empty" << endl;
else
cout << "Stack elements are: ";
for (int i = 0; i <= top; i++)
{
cout << s[i] << " ";
}
cout << endl;
}
};
int main()
{
stack ob;
int choice;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
for(;;)
{
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be pushed: ";
cin >> ob.item;
ob.push(ob.item);
break;
case 2:
ob.pop();
break;
case 3:
ob.display();
break;
case 4:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
1. Push 2. Pop 3. Display 4. Exit Enter your choice: 1 Enter the element to be pushed: 5 5 pushed into stack Enter your choice: 1 Enter the element to be pushed: 10 10 pushed into stack Enter your choice: 1 Enter the element to be pushed: 15 15 pushed into stack Enter your choice: 2 15 popped from stack Enter your choice: 3 Stack elements are: 5 10 Enter your choice: 2 10 popped from stack Enter your choice: 2 5 popped from stack Enter your choice: 2 Stack is empty
Question: Write a program to implement a circular queue .
#include <iostream>
#include <conio.h> // for getch()
#define size 3
using namespace std;
class CircularQueue
{
int front, rear;
int arr[size];
int count;
public:
CircularQueue()
{ count = 0;
front = -1;
rear = -1;
}
void enqueue(int data)
{
if (count == size)
{
cout << "Queue is full" << endl;
}
else
{
if (front == -1)
{
front = 0;
}
rear = (rear+1)%size;
arr[rear] = data;
count = count+1;
cout << data << " is enqueued" << endl;
}
}
void dequeue()
{
if (count == 0)
{
cout << "Queue is empty" << endl;
}
else
{
cout << arr[front] << " is dequeued" << endl;
front = (front+1)%size;
count--;
}
}
void display()
{
if (front == -1)
{
cout << "Queue is empty" << endl;
}
else
{
cout << "Queue elements are: ";
int j = 0;
int i = front;
while (j<count)
{
cout << arr[i] << " ";
i = (i+1)%size;
j++;
}
cout << endl;
}
}
};
int main()
{
CircularQueue ob;
int choice;
int item;
cout<<"Circular Queue\n";
cout << "1. Enqueue" << endl;
cout << "2. Dequeue" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
for(;;)
{
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be Enqueue : ";
cin >> item;
ob.enqueue(item);
break;
case 2:
ob.dequeue();
break;
case 3:
ob.display();
break;
case 4:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
Circular Queue 1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 1 Enter the element to be Enqueue : 1 1 is enqueued Enter your choice: 1 Enter the element to be Enqueue : 2 2 is enqueued Enter your choice: 1 Enter the element to be Enqueue : 3 3 is enqueued Enter your choice: 1 Enter the element to be Enqueue : 4 Queue is full Enter your choice: 3 Queue elements are: 1 2 3 Enter your choice: 2 1 is dequeued Enter your choice: 2 2 is dequeued Enter your choice: 2 3 is dequeued Enter your choice: 2 Queue is empty Enter your choice:
Question: Write a program to implement a linear queue.
#include <iostream>
#include <conio.h> // for getch()
#define size 5
using namespace std;
class Queue
{
int front, rear;
int arr[size];
public:
Queue()
{
front = -1;
rear = -1;
}
void enqueue(int data)
{
if (rear == size - 1)
{
cout << "Queue is full" << endl;
}
else
{
if (front == -1)
{
front = 0;
}
rear++;
arr[rear] = data;
cout << data << " is enqueued" << endl;
}
}
void dequeue()
{
if (front == -1)
{
cout << "Queue is empty" << endl;
}
else
{
cout << arr[front] << " is dequeued" << endl;
front++;
if (front > rear)
{
front = rear = -1;
}
}
}
void display()
{
if (front == -1)
{
cout << "Queue is empty" << endl;
}
else
{
cout << "Queue elements are: ";
for (int i = front; i <= rear; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
}
};
int main()
{
Queue ob;
int choice;
int item;
cout << "1. Enqueue" << endl;
cout << "2. Dequeue" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
for(;;)
{
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be Enqueue: ";
cin >> item;
ob.enqueue(item);
break;
case 2:
ob.dequeue();
break;
case 3:
ob.display();
break;
case 4:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 1 Enter the element to be Enqueue: 3 3 is enqueued Enter your choice: 1 Enter the element to be Enqueue: 5 5 is enqueued Enter your choice: 1 Enter the element to be Enqueue: 0 0 is enqueued Enter your choice: 2 3 is dequeued Enter your choice: 2 5 is dequeued Enter your choice: 2 0 is dequeued Enter your choice: 2 Queue is empty Enter your choice:
Question: Write a program to implement a doubly linked list.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
struct Node
{
int data;
Node *next;
Node *prev;
};
class list
{
public:
Node *head;
int item;
list()
{
head = NULL;
}
void insert_front()
{
Node *newNode = new Node;
newNode->data = item;
newNode->next = head;
newNode->prev = NULL;
if (head != NULL)
{
head->prev = newNode;
}
head = newNode;
}
void insert_rear()
{
Node *newNode = new Node;
newNode->data = item;
newNode->next = NULL;
if (head == NULL)
{
newNode->prev = NULL;
head = newNode;
}
else
{
Node *curr = head;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = newNode;
newNode->prev = curr;
}
}
void delete_front()
{
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *newNode = head;
head = head->next;
if (head != NULL)
{
head->prev = NULL;
}
delete newNode;
}
}
void delete_rear()
{
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *curr = head;
Node *prev = NULL;
while (curr->next != NULL)
{
prev = curr;
curr = curr->next;
}
if (prev == NULL)
{
head = NULL;
}
else
{
prev->next = NULL;
}
delete curr;
}
}
void search_and_delete()
{
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *curr = head;
Node *prev = NULL;
while (curr != NULL)
{
if (curr->data == item)
{
if (prev == NULL)
{
head = curr->next;
}
else
{
prev->next = curr->next;
}
if (curr->next != NULL)
{
curr->next->prev = prev;
}
delete curr;
return;
}
prev = curr;
curr = curr->next;
}
cout << "Element not found" << endl;
}
}
void display(){
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *curr = head;
while (curr != NULL)
{
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
}
};
int main(){
list ob;
int choice;
int item;
for (;;)
{
cout << "1. Insert at front" << endl;
cout << "2. Insert at rear" << endl;
cout << "3. Delete from front" << endl;
cout << "4. Delete from rear" << endl;
cout << "5. Search and delete" << endl;
cout << "6. Display" << endl;
cout << "7. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be inserted at front : ";
cin >> ob.item;
ob.insert_front();
break;
case 2:
cout << "Enter the element to be inserted at rear : ";
cin >> ob.item;
ob.insert_rear();
break;
case 3:
ob.delete_front();
break;
case 4:
ob.delete_rear();
break;
case 5:
cout << "Enter the element to be searched and deleted : ";
cin >> ob.item;
ob.search_and_delete();
break;
case 6:
ob.display();
break;
case 7:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 1 Enter the element to be inserted at front : 1 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 2 Enter the element to be inserted at rear : 2 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 2 Enter the element to be inserted at rear : 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 1 Enter the element to be inserted at front : 4 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 4 1 2 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 1 2 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 5 Enter the element to be searched and deleted : 2 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 1 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 3 List is empty 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit
Question: Write a program to implement a singly linked list.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
struct Node
{
int data;
Node *next;
};
class list
{
public:
Node *head;
int item;
list()
{
head = NULL;
}
void insert_front()
{
Node *newNode = new Node;
newNode->data = item;
newNode->next = head;
head = newNode;
}
void insert_rear()
{
Node *newNode = new Node;
newNode->data = item;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
}
else
{
Node *curr = head;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = newNode;
}
}
void delete_front()
{
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *newNode = head;
head = head->next;
delete newNode;
}
}
void delete_rear()
{
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *curr = head;
Node *prev = NULL;
while (curr->next != NULL)
{
prev = curr;
curr = curr->next;
}
if (prev == NULL)
{
head = NULL;
}
else
{
prev->next = NULL;
}
delete curr;
}
}
void search_and_delete()
{
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *curr = head;
Node *prev = NULL;
while (curr != NULL)
{
if (curr->data == item)
{
if (prev == NULL)
{
head = curr->next;
}
else
{
prev->next = curr->next;
}
delete curr;
return;
}
prev = curr;
curr = curr->next;
}
cout << "Element not found" << endl;
}
}
void display()
{
if (head == NULL)
{
cout << "List is empty" << endl;
}
else
{
Node *curr = head;
while (curr != NULL)
{
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
}
};
int main()
{
list ob;
int choice;
int item;
for (;;)
{
cout << "1. Insert at front" << endl;
cout << "2. Insert at rear" << endl;
cout << "3. Delete from front" << endl;
cout << "4. Delete from rear" << endl;
cout << "5. Search and delete" << endl;
cout << "6. Display" << endl;
cout << "7. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be inserted at front : ";
cin >> ob.item;
ob.insert_front();
break;
case 2:
cout << "Enter the element to be inserted at rear : ";
cin >> ob.item;
ob.insert_rear();
break;
case 3:
ob.delete_front();
break;
case 4:
ob.delete_rear();
break;
case 5:
cout << "Enter the element to be searched and deleted : ";
cin >> ob.item;
ob.search_and_delete();
break;
case 6:
ob.display();
break;
case 7:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 List is empty 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 1 Enter the element to be inserted at front : 5 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 2 Enter the element to be inserted at rear : 10 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 1 Enter the element to be inserted at front : 15 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 15 5 10 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 3 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 5 10 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 4 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 5 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 4 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit Enter your choice: 6 List is empty 1. Insert at front 2. Insert at rear 3. Delete from front 4. Delete from rear 5. Search and delete 6. Display 7. Exit
Question: Write a C++ program, using common friend function, the function is called by reference to exchange the private data members of two classes, display the data before exchange and after exchange
#include <iostream>
#include <conio.h> // comment if you are are using modern compilers
using namespace std;
// Forward declaration of class B
class B;
class A
{
private:
int dataA;
public:
A(int val)
{
dataA = val;
}
void display()
{
cout << "Data of class A: " << dataA << endl;
}
// Declare friend function
friend void exchange(A &, B &);
};
class B
{
private:
int dataB;
public:
B(int val)
{
dataB = val;
}
void display()
{
cout << "Data of class B: " << dataB << endl;
}
// Declare friend function
friend void exchange(A &, B &);
};
// Common friend function to exchange data members of two classes
void exchange(A &objA, B &objB)
{
int temp = objA.dataA;
objA.dataA = objB.dataB;
objB.dataB = temp;
}
int main()
{
A objA(10);
B objB(20);
cout << "Before exchange:" << endl;
objA.display();
objB.display();
// Call friend function to exchange data
exchange(objA, objB);
cout << "\nAfter exchange:" << endl;
objA.display();
objB.display();
getch(); // comment if using modern compilers
return 0;
}
Before exchange: Data of class A: 10 Data of class B: 20 After exchange: Data of class A: 20 Data of class B: 10
Question: Write a C++ program, to perform addition of two complex numbers, use default and parameterized constructor and display the both complex numbers and sum of two complex numbers. (e.g. 2+3j)
#include<iostream>
#include <conio.h> // comment if you are are using modern compilers
using namespace std;
class Complex {
private:
int real;
int imag;
public:
// Default constructor
Complex() {
real = 0;
imag = 0;
}
// Parameterized constructor
Complex(int r, int i) {
real = r;
imag = i;
}
// Function to display complex number
void display() {
cout << real << " + " << imag << "j" << endl;
}
// Function to add two complex numbers
Complex add(Complex c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
};
int main() {
// Create complex numbers using parameterized constructor
Complex c1(2, 3);
Complex c2(4, 5);
// Display the complex numbers
cout << "Complex Number 1: ";
c1.display();
cout << "Complex Number 2: ";
c2.display();
// Add the complex numbers
Complex c3 = c1.add(c2);
// Display the sum of complex numbers
cout << "Sum of Complex Numbers: ";
c3.display();
getch();
return 0;
}
Complex Number 1: 2 + 3j Complex Number 2: 4 + 5j Sum of Complex Numbers: 6 + 8j
Question: Write a C++ program, to demonstrate unary minus operator is overloaded.
#include <iostream>
#include <conio.h> // for getch()
using namespace std;
class Space
{
int x, y, z;
public:
void getdata(int a, int b, int c);
void display(void);
void operator -();
};
void Space::getdata(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void Space::display(void)
{
cout << "x:" << x << " y:" << y << " z:" << z << "\n";
}
void Space::operator -()
{
x = -x;
y = -y;
z = -z;
}
int main()
{
Space S;
S.getdata(10, -20, 30);
cout << "S: ";
S.display();
-S;
cout << "S: ";
S.display();
getch();
return 0;
}
S: x:10 y:-20 z:30 S: x:-10 y:20 z:-30
Question: Create a base class Student which reads and displays roll_no of the student. Derive a class test from student class which reads and prints two subject marks, now derive one more class result which inherits the marks from test class of the student, find total marks and display the sum. Use appropriate type of inheritance to implement above program.
#include<iostream>
#include <conio.h> // comment if you are are using modern compilers
using namespace std;
// Base class Student
class Student {
protected:
int roll_no;
public:
void readRollNo() {
cout << "Enter Roll No: ";
cin >> roll_no;
}
void displayRollNo() {
cout << "Roll No: " << roll_no << endl;
}
};
// Derived class Test from Student
class Test : public Student {
protected:
int marks1, marks2;
public:
void readMarks() {
cout << "Enter Marks for Subject 1: ";
cin >> marks1;
cout << "Enter Marks for Subject 2: ";
cin >> marks2;
}
void displayMarks() {
cout << "Marks for Subject 1: " << marks1 << endl;
cout << "Marks for Subject 2: " << marks2 << endl;
}
};
// Derived class Result from Test
class Result : public Test {
private:
int total;
public:
void calculateTotal() {
total = marks1 + marks2;
}
void displayResult() {
displayRollNo(); // Display roll number from Student class
displayMarks(); // Display marks from Test class
cout << "Total Marks: " << total << endl;
}
};
int main() {
Result r;
// Read roll number and marks
r.readRollNo();
r.readMarks();
// Calculate total marks
r.calculateTotal();
// Display result
cout << "\nStudent Result:" << endl;
r.displayResult();
getch();
return 0;
}
Enter Roll No: 29 Enter Marks for Subject 1: 10 Enter Marks for Subject 2: 20 Student Result: Roll No: 29 Marks for Subject 1: 10 Marks for Subject 2: 20 Total Marks: 30
Question: Create a class Student which reads and displays roll_no of the student. Create another class Test which reads and prints two subject marks, now create one more class SportsMark which reads and prints sports marks of the student, derive a single class Result from all above mentioned classes to find total marks of the student and display it. Use appropriate type of inheritance to implement above program.
#include<iostream>
#include <conio.h> // comment if you are are using modern compilers
using namespace std;
// Base class Student
class Student {
protected:
int roll_no;
public:
void readRollNo() {
cout << "Enter Roll No: ";
cin >> roll_no;
}
void displayRollNo() {
cout << "Roll No: " << roll_no << endl;
}
};
// Base class Test
class Test {
protected:
int marks1, marks2;
public:
void readMarks() {
cout << "Enter Marks for Subject 1: ";
cin >> marks1;
cout << "Enter Marks for Subject 2: ";
cin >> marks2;
}
void displayMarks() {
cout << "Marks for Subject 1: " << marks1 << endl;
cout << "Marks for Subject 2: " << marks2 << endl;
}
};
// Base class SportsMark
class SportsMark {
protected:
int sportsMarks;
public:
void readSportsMarks() {
cout << "Enter Sports Marks: ";
cin >> sportsMarks;
}
void displaySportsMarks() {
cout << "Sports Marks: " << sportsMarks << endl;
}
};
// Derived class Result from Student, Test, and SportsMark
class Result : public Student, public Test, public SportsMark {
private:
int total;
public:
void calculateTotal() {
total = marks1 + marks2 + sportsMarks;
}
void displayResult() {
displayRollNo(); // Display roll number from Student class
displayMarks(); // Display marks from Test class
displaySportsMarks(); // Display sports marks from SportsMark class
cout << "Total Marks: " << total << endl;
}
};
int main() {
Result r;
// Read roll number, subject marks, and sports marks
r.readRollNo();
r.readMarks();
r.readSportsMarks();
// Calculate total marks
r.calculateTotal();
// Display result
cout << "\nStudent Result:" << endl;
r.displayResult();
getch();
return 0;
}
Enter Roll No: 29 Enter Marks for Subject 1: 10 Enter Marks for Subject 2: 20 Enter Sports Marks: 30 Student Result: Roll No: 29 Marks for Subject 1: 10 Marks for Subject 2: 20 Sports Marks: 30 Total Marks: 60
Question: Write a C++ program to create a base class geofig with member function getdata() to accept the sides of the geofig and display() function. Make the display () virtual. Define two derived class called rect and tri with member function display() to compute the respective area and display the sides and area. Make an interactive program to accept the appropriate dimension for the chosen figure.
#include<iostream>
#include<conio.h> //for getch()
using namespace std;
class geofig{
public:
float a,b,area;
void get_data(){
cin>>a>>b;
}
virtual void display(){
// Empty
}
};
class tri:public geofig{
public:
void display(){
area=0.5*a*b;
cout<<"Height and base of the triangle are: "<<a<<" and "<<b<<endl;
cout<<"Area of the triangle is: "<<area<<endl;
}
};
class rect:public geofig{
public:
void display(){
area=a*b;
cout<<"Length and breadth of the rectangle are: "<<a<<" and "<<b<<endl;
cout<<"Area of the rectangle is: "<<area<<endl;
}
};
int main(){
geofig *ptr;
tri t1;
rect r1;
char c;
cout<<"Enter the type of figure (t/r): "<<endl;
cin>>c;
if(c=='t'){
cout<<"Enter the height and base of the triangle: "<<endl;
ptr=&t1;
ptr->get_data();
ptr->display();
}
else if(c=='r'){
cout<<"Enter the length and breadth of the rectangle: "<<endl;
ptr=&r1;
ptr->get_data();
ptr->display();
}
else{
cout<<"Invalid input"<<endl;
}
getch();
return 0;
}
Enter the type of figure (t/r): t Enter the height and base of the triangle: 5 10 Height and base of the triangle are: 5 and 10 Area of the triangle is: 25
Question: Write a C++ program, to implement basic stack operations using array.
#include <iostream>
#include <conio.h> // for _getch()
# define stack_size 5
using namespace std;
class stack
{
int top;
int s[stack_size]
public:
int item;
stack()
{
top = -1;
}
void push(int item)
{
if (top >= stack_size - 1)
cout << "Stack Overflow" << endl;
else
s[++top] = item;
cout << item << " pushed into stack" << endl;
}
void pop()
{
if (top < 0)
cout << "Stack is empty" << endl;
else
cout << s[top--] << " popped from stack" << endl;
}
void display()
{
if (top < 0)
cout << "Stack is empty" << endl;
else
cout << "Stack elements are: ";
for (int i = 0; i <= top; i++)
{
cout << s[i] << " ";
}
cout << endl;
}
};
int main()
{
stack ob;
int choice;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
for(;;)
{
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be pushed: ";
cin >> ob.item;
ob.push(ob.item);
break;
case 2:
ob.pop();
break;
case 3:
ob.display();
break;
case 4:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
1. Push 2. Pop 3. Display 4. Exit Enter your choice: 1 Enter the element to be pushed: 5 5 pushed into stack Enter your choice: 1 Enter the element to be pushed: 10 10 pushed into stack Enter your choice: 1 Enter the element to be pushed: 15 15 pushed into stack Enter your choice: 2 15 popped from stack Enter your choice: 3 Stack elements are: 5 10 Enter your choice: 2 10 popped from stack Enter your choice: 2 5 popped from stack Enter your choice: 2 Stack is empty
Question: Write a C++ program, to convert the given infix expression to postfix expression.
#include <iostream>
#include <stack>
#include <conio.h>
#include <string>
using namespace std;
// Function to return precedence of operators
int precedence(char ch)
{
if (ch == '+' || ch == '-')
return 1;
else if (ch == '*' || ch == '/')
return 2;
else if (ch == '^')
return 3;
else
return -1;
}
// Function to convert infix to postfix
void infixToPostfix(string s)
{
stack<char> st;
string result = "";
for (int i = 0; i < s.length(); i++)
{
char c = s[i];
// If the scanned character is an operand, add it to output
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
result += c;
// If the scanned character is an '(', push it to the stack
else if (c == '(')
st.push(c);
// If the scanned character is an ')', pop and output from the stack until an '(' is encountered
else if (c == ')')
{
while (!st.empty() && st.top() != '(')
{
result += st.top();
st.pop();
}
if (!st.empty())
st.pop();
}
// If the scanned character is an operator, pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator.
else
{
while (!st.empty() && precedence(c) <= precedence(st.top()))
{
result += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty())
{
result += st.top();
st.pop();
}
cout << "Postfix expression: " << result << endl;
}
// Main function
int main(){
string exp;
cout << "Enter the infix expression: ";
cin >> exp;
infixToPostfix(exp);
getch();
return 0;
}
Enter the infix expression: A+B+C/D*E(F+G)/H Postfix expression: AB+CD/EFG+*H/+
Question: Write a C++ program, to evaluate a valid postfix expression and display the result.
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
class Stack
{
public:
char postfix[30];
int s[30];
int result;
int top;
Stack()
{
top = -1;
}
// Fuction to evaluate postfix expression
void evaluateExpressions()
{
for (int i = 0; i < strlen(postfix); i++)
{
char ch = postfix[i];
if (isdigit(ch))
{
s[++top] = ch - '0';
}
else
{
int op2 = s[top--];
int op1 = s[top--];
performOperation(op1, op2, ch);
s[++top] = result;
}
}
}
void performOperation(int op1,int op2,char symbol){
switch (symbol)
{
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
case '^':
case '$':
result = pow(op1, op2);
break;
}
}
};
int main()
{
Stack ob;
cout << "Enter the postfix expression: ";
cin >> ob.postfix;
ob.evaluateExpressions();
cout << "Result: " << ob.result << endl;
return 0;
}
Question: Write a C++ program, to implement linear queue operations using array.
#include <iostream>
#include <conio.h> // for getch()
#define size 5
using namespace std;
class Queue
{
int front, rear;
int arr[size];
public:
Queue()
{
front = -1;
rear = -1;
}
void enqueue(int data)
{
if (rear == size - 1)
{
cout << "Queue is full" << endl;
}
else
{
if (front == -1)
{
front = 0;
}
rear++;
arr[rear] = data;
cout << data << " is enqueued" << endl;
}
}
void dequeue()
{
if (front == -1)
{
cout << "Queue is empty" << endl;
}
else
{
cout << arr[front] << " is dequeued" << endl;
front++;
if (front > rear)
{
front = rear = -1;
}
}
}
void display()
{
if (front == -1)
{
cout << "Queue is empty" << endl;
}
else
{
cout << "Queue elements are: ";
for (int i = front; i <= rear; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
}
};
int main()
{
Queue ob;
int choice;
int item;
cout << "1. Enqueue" << endl;
cout << "2. Dequeue" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
for(;;)
{
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be Enqueue: ";
cin >> item;
ob.enqueue(item);
break;
case 2:
ob.dequeue();
break;
case 3:
ob.display();
break;
case 4:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 1 Enter the element to be Enqueue: 3 3 is enqueued Enter your choice: 1 Enter the element to be Enqueue: 5 5 is enqueued Enter your choice: 1 Enter the element to be Enqueue: 0 0 is enqueued Enter your choice: 2 3 is dequeued Enter your choice: 2 5 is dequeued Enter your choice: 2 0 is dequeued Enter your choice: 2 Queue is empty Enter your choice:
Question: Write a C++ program, to implement circular queue operations using array.
#include <iostream>
#include <conio.h> // for getch()
#define size 3
using namespace std;
class CircularQueue
{
int front, rear;
int arr[size];
int count;
public:
CircularQueue()
{ count = 0;
front = -1;
rear = -1;
}
void enqueue(int data)
{
if (count == size)
{
cout << "Queue is full" << endl;
}
else
{
if (front == -1)
{
front = 0;
}
rear = (rear+1)%size;
arr[rear] = data;
count = count+1;
cout << data << " is enqueued" << endl;
}
}
void dequeue()
{
if (count == 0)
{
cout << "Queue is empty" << endl;
}
else
{
cout << arr[front] << " is dequeued" << endl;
front = (front+1)%size;
count--;
}
}
void display()
{
if (front == -1)
{
cout << "Queue is empty" << endl;
}
else
{
cout << "Queue elements are: ";
int j = 0;
int i = front;
while (j<count)
{
cout << arr[i] << " ";
i = (i+1)%size;
j++;
}
cout << endl;
}
}
};
int main()
{
CircularQueue ob;
int choice;
int item;
cout<<"Circular Queue\n";
cout << "1. Enqueue" << endl;
cout << "2. Dequeue" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
for(;;)
{
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element to be Enqueue : ";
cin >> item;
ob.enqueue(item);
break;
case 2:
ob.dequeue();
break;
case 3:
ob.display();
break;
case 4:
exit(0);
default:
cout << "Invalid choice" << endl;
}
}
getch();
return 0;
}
Circular Queue 1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 1 Enter the element to be Enqueue : 1 1 is enqueued Enter your choice: 1 Enter the element to be Enqueue : 2 2 is enqueued Enter your choice: 1 Enter the element to be Enqueue : 3 3 is enqueued Enter your choice: 1 Enter the element to be Enqueue : 4 Queue is full Enter your choice: 3 Queue elements are: 1 2 3 Enter your choice: 2 1 is dequeued Enter your choice: 2 2 is dequeued Enter your choice: 2 3 is dequeued Enter your choice: 2 Queue is empty Enter your choice:
Question:
include
#define QUEUE_SIZE 5
using namespace std;
class PriorityQueue {
public:
int frontIndex, rearIndex, queueArray[QUEUE_SIZE];
PriorityQueue() {
frontIndex = 0;
rearIndex = -1;
}
void enqueue(int element) {
if (rearIndex == QUEUE_SIZE - 1) {
cout << "Queue overflow." << endl;
return;
}
int shiftIndex = rearIndex;
while (shiftIndex >= frontIndex && element < queueArray[shiftIndex]) {
queueArray[shiftIndex + 1] = queueArray[shiftIndex];
shiftIndex--;
}
queueArray[shiftIndex + 1] = element;
rearIndex++;
}
void dequeue() {
if (frontIndex > rearIndex) {
cout << "Queue underflow." << endl;
} else {
cout << "Dequeued: " << queueArray[frontIndex] << endl;
frontIndex++;
}
}
void display() {
if (frontIndex > rearIndex) {
cout << "Queue is empty." << endl;
} else {
cout << "Priority Queue contents: ";
for (int i = frontIndex; i <= rearIndex; i++) {
cout << queueArray[i] << " ";
}
cout << endl;
}
}
};
int main() {
PriorityQueue pq;
int choice, value;
while (true) {
cout << "1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\nEnter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter the value to enqueue: ";
cin >> value;
pq.enqueue(value);
break;
case 2:
pq.dequeue();
break;
case 3:
pq.display();
break;
case 4:
return 0;
default:
cout << "Invalid choice." << endl;
}
}
return 0;
}
1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 1 Enter the value to enqueue: 2 1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 1 Enter the value to enqueue: 6 1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 1 Enter the value to enqueue: 1 1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice: 3 Priority Queue contents: 1 2 6 1. Enqueue 2. Dequeue 3. Display 4. Exit Enter your choice:
Question: Write a C++ programs, that reads a list of integers form that reads a list of integers from the user, and search for a particular key in the created list if search is successful then delete it and update the rest list and display the list contents using singly linked list.
#include <iostream>
#include <conio.h> // for getch
using namespace std;
struct Node
{
int data;
Node *link;
};
class LinkedList
{
public:
Node *head; // head of list
LinkedList()
{
head = NULL;
}
void construct_linked_list_from_array(int *, int);
void search_and_delete(int key);
void display();
};
void LinkedList::construct_linked_list_from_array(int *arr, int n)
{
Node *temp;
for (int i = 0; i < n; i++)
{
Node *new_node = new Node;
new_node->data = arr[i];
new_node->link = NULL;
if (head == NULL)
{
head = new_node;
temp = head;
}
else
{
temp->link = new_node;
temp = temp->link;
}
}
}
void LinkedList::search_and_delete(int key)
{
if (head == NULL)
{
cout << "List is empty" << endl;
return;
}
if (head->data == key)
{
Node *temp = head;
head = head->link;
delete temp;
return;
}
Node *temp = head;
while (temp->link != NULL)
{
if (temp->link->data == key)
{
Node *temp1 = temp->link;
temp->link = temp->link->link;
delete temp1;
return;
}
temp = temp->link;
}
cout << "Key not found" << endl;
}
void LinkedList::display()
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->link;
}
}
int main(){
int n,a[100],key;
cout<<"Enter the number of elements: ";
cin>>n;
cout<<"Enter the elements: ";
for(int i=0;i<n;i++){
cin>>a[i];
}
LinkedList list;
list.construct_linked_list_from_array(a,n);
cout<<"Enter the key to search and delete: ";
cin>>key;
list.search_and_delete(key);
cout<<"List after deleting the key: ";
list.display();
getch();
return 0;
}
Enter the number of elements: 5 Enter the elements: 1 2 3 4 5 Enter the key to search and delete: 3 List after deleting the key: 1 2 4 5
Question: Write a C++ program, that reads a list of integers from the user, and deletes a data from the frontend of created list and display the list contents using Singly Linked List.
#include <iostream>
#include <conio.h> // for getch
using namespace std;
struct Node {
int data;
Node *link;
};
class LinkedList {
public:
Node *head;
LinkedList() { head = NULL; }
void construct_linked_list_from_array(int *arr, int n) {
Node *temp;
for (int i = 0; i < n; i++) {
Node *new_node = new Node;
new_node->data = arr[i];
new_node->link = NULL;
if (!head) {
head = new_node;
temp = head;
} else {
temp->link = new_node;
temp = temp->link;
}
}
}
void delete_from_front() {
if (!head) {
cout << "List is empty" << endl;
return;
}
Node *temp = head;
head = head->link;
delete temp;
}
void display() {
Node *temp = head;
while (temp) {
cout << temp->data << " ";
temp = temp->link;
}
cout << endl;
}
};
int main() {
int n, arr[100];
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
LinkedList list;
list.construct_linked_list_from_array(arr, n);
cout<< "List: ";
list.display();
list.delete_from_front();
cout << "List after deleting from front: ";
list.display();
getch();
return 0;
}
Enter the number of elements: 6 Enter the elements: 1 2 3 4 5 6 List: 1 2 3 4 5 6 List after deleting from front: 2 3 4 5 6
Question: Write a C++ programs, that reads a list of integers form that reads a list of integers from the user, and search for a particular key in the created list if search is successful then delete it and update the rest list and display the list contents using Circular linked list.
#include <iostream>
#include <conio.h> // for getch
using namespace std;
struct Node {
int data;
Node* link;
};
class CircularLinkedList {
public:
Node* last;
CircularLinkedList() { last = NULL; }
void insert_rear(int data) {
Node* new_node = new Node;
new_node->data = data;
if(!last) {
last = new_node;
last->link = last;
} else {
new_node->link = last->link;
last->link = new_node;
last = new_node;
}
}
void construct_linked_list_from_array(int* arr, int n) {
for(int i = 0; i < n; i++){
insert_rear(arr[i]);
}
}
void search_and_delete(int key) {
if(!last) {
cout << "List is empty" << endl;
return;
}
Node *curr = last->link, *prev = last;
do {
if(curr->data == key) {
// If there's only one node in the list
if(curr == last && curr->link == last) {
delete curr;
last = NULL;
}
// If the key is in the first node of the list
else if(curr == last->link) {
last->link = curr->link;
delete curr;
}
// If the key is in the last node of the list
else if(curr == last) {
prev->link = curr->link;
last = prev;
delete curr;
}
// Otherwise, it's in a middle node
else {
prev->link = curr->link;
delete curr;
}
return;
}
prev = curr;
curr = curr->link;
} while(curr != last->link);
cout << "Key not found" << endl;
}
void display() {
if(!last) {
cout << "List is empty" << endl;
return;
}
Node* temp = last->link;
do {
cout << temp->data << " ";
temp = temp->link;
} while(temp != last->link);
cout << endl;
}
};
int main() {
int n, arr[100], key;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
CircularLinkedList list;
list.construct_linked_list_from_array(arr, n);
cout << "Enter the key to search and delete: ";
cin >> key;
list.search_and_delete(key);
cout << "List after deleting the key: ";
list.display();
getch();
return 0;
a C++ programs, that reads a list of integers form that reads a list of integers from the user, and search for a particular key in the created list if search is successful then delete it and update the rest list and display the list contents using Circular linked list. #include#include // for getch using namespace std; struct Node { int data; Node* link; }; class CircularLinkedList { public: Node* last; CircularLinkedList() { last = NULL; } void insert_rear(int data) { Node* new_node = new Node; new_node->data = data; if(!last) { last = new_node; last->link = last; } else { new_node->link = last->link; last->link = new_node; last = new_node; } } void construct_linked_list_from_array(int* arr, int n) { for(int i = 0; i < n; i++){ insert_rear(arr[i]); } } void search_and_delete(int key) { if(!last) { cout << "List is empty" << endl; return; } Node *curr = last->link, *prev = last; do { if(curr->data == key) { // If there's only one node in the list if(curr == last && curr->link == last) { delete curr; last = NULL; } // If the key is in the first node of the list else if(curr == last->link) { last->link = curr->link; delete curr; } // If the key is in the last node of the list else if(curr == last) { prev->link = curr->link; last = prev; delete curr; } // Otherwise, it's in a middle node else { prev->link = curr->link; delete curr; } return; } prev = curr; curr = curr->link; } while(curr != last->link); cout << "Key not found" << endl; } void display() { if(!last) { cout << "List is empty" << endl; return; } Node* temp = last->link; do { cout << temp->data << " "; temp = temp->link; } while(temp != last->link); cout << endl; } }; int main() { int n, arr[100], key; cout << "Enter the number of elements: "; cin >> n; cout << "Enter the elements: "; for(int i = 0; i < n; i++) { cin >> arr[i]; } CircularLinkedList list; list.construct_linked_list_from_array(arr, n); cout << "Enter the key to search and delete: "; cin >> key; list.search_and_delete(key); cout << "List after deleting the key: "; list.display(); getch(); return 0;
Question: write a C++ program that reads a list of integers from the user, and deletes a data from the front end of created list and display the list contents using linear doubly linked List
#include <iostream>
#include <conio.h> // for getch
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
};
class DoublyLinkedList {
public:
Node* head;
DoublyLinkedList() { head = NULL; }
void insert_rear(int data) {
Node* new_node = new Node;
new_node->data = data;
new_node->prev = NULL;
new_node->next = NULL;
if(!head) {
head = new_node;
} else {
Node* temp = head;
while(temp->next) {
temp = temp->next;
}
temp->next = new_node;
new_node->prev = temp;
}
}
void delete_from_front() {
if(!head) {
cout << "List is empty" << endl;
return;
}
Node* temp = head;
head = head->next;
if(head) {
head->prev = NULL;
}
delete temp;
}
void display() {
if(!head) {
cout << "List is empty" << endl;
return;
}
Node* temp = head;
while(temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
int n, arr[100];
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
DoublyLinkedList list;
for(int i = 0; i < n; i++) {
list.insert_rear(arr[i]);
}
cout << "List: ";
list.display();
list.delete_from_front();
cout << "List after deleting from front: ";
list.display();
getch();
return 0;
}
Enter the number of elements: 6 Enter the elements: 2 4 6 8 10 12 List: 2 4 6 8 10 12 List after deleting from front: 4 6 8 10 12