0% found this document useful (0 votes)
14 views16 pages

C++ PYQ Programs

Uploaded by

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

C++ PYQ Programs

Uploaded by

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

Q.

Explain different types of inheritance with the help of sample program


#include <iostream>
using namespace std;

// Base Class for Single Inheritance


class Animal {
public:
void eat() {
cout << "Eating food!" << endl;
} };

// Derived Class (Single Inheritance)


class Dog : public Animal {
public:
void bark() {
cout << "Barking!" << endl;
} };

// Base Class for Multiple Inheritance


class Vehicle {
public:
void drive() {
cout << "Driving vehicle!" << endl;
} };

// Another Base Class for Multiple Inheritance


class Machine {
public:
void operate() {
cout << "Operating machine!" << endl;
} };

// Derived Class (Multiple Inheritance)


class Car : public Vehicle, public Machine {
public:
void honk() {
cout << "Honk honk!" << endl;
} };

// Base Class for Multilevel Inheritance


class Shape {
public:
void draw() {
cout << "Drawing shape!" << endl;
} };

// Derived Class for Multilevel Inheritance


class Rectangle : public Shape {
public:
void area() {
cout << "Calculating area of rectangle!" << endl;
} };

// Derived Class for Multilevel Inheritance


class ColoredRectangle : public Rectangle {
public:
void color() {
cout << "Coloring rectangle!" << endl;
} };

int main() {
// Single Inheritance
cout << "Single Inheritance Example:" << endl;
Dog dog;
dog.eat(); // From Animal class
dog.bark(); // From Dog class
cout << endl;
// Multiple Inheritance
cout << "Multiple Inheritance Example:" << endl;
Car car;
car.drive(); // From Vehicle class
car.operate(); // From Machine class
car.honk(); // From Car class
cout << endl;

// Multilevel Inheritance
cout << "Multilevel Inheritance Example:" << endl;
ColoredRectangle coloredRect;
coloredRect.draw(); // From Shape class
coloredRect.area(); // From Rectangle class
coloredRect.color(); // From ColoredRectangle class
return 0;
}

Q. Write a program to overload + operator.


#include <iostream>
using namespace std;

class MyClass {
private:
int value;

public:
// Constructor to initialize the value
MyClass(int v) : value(v) {}

// Overloading the + operator


MyClass operator+(const MyClass& other) {
return MyClass(value + other.value);
}

// Function to display the value


void display() const {
cout << value << endl;
} };

int main() {
MyClass obj1(10);
MyClass obj2(20);

// Using the overloaded + operator


MyClass result = obj1 + obj2;

// Display the result


result.display(); // Output will be 30

return 0;
}
Q. Write a program for dynamic memory allocation.
#include <iostream>
using namespace std;

int main() {
// Dynamically allocate memory for an integer
int* ptr = new int;

// Assign a value to the allocated memory


*ptr = 42;
int a = 10;

// Display the value


cout << "The value stored in dynamically allocated memory: " << *ptr << endl;

// Free the dynamically allocated memory


delete ptr;

return 0;
}

Q. Write a program to show the working of constructor.


#include <iostream>
using namespace std;

// Base class
class Base {
public:
Base() {
cout << "Base class constructor called!" << endl;
}
};

// Derived class
class Derived : public Base {
public:
Derived() {
cout << "Derived class constructor called!" << endl;
} };

int main() {
// Creating an object of the derived class
Derived obj;
return 0;
}
Q. Wap to overload unary addition operator
#include <iostream>
using namespace std;

class MyClass {
private:
int value;

public:
// Constructor to initialize the value
MyClass(int v) : value(v) {}

// Overloading the + operator


MyClass operator+(const MyClass& other) {
return MyClass(value + other.value);
}

// Function to display the value


void display() const {
cout << value << endl;
} };

int main() {
MyClass obj1(10);
MyClass obj2(20);

// Using the overloaded + operator


MyClass result = obj1 + obj2;

// Display the result


result.display(); // Output will be 30

return 0;
}

Q. WAP to show the use of friend function


#include <iostream>
using namespace std;

class MyClass {
private:
int value;

public:
// Constructor to initialize value
MyClass(int v) : value(v) {}
// Declaring friend function
friend void displayValue(const MyClass& obj);
};

// Friend function definition


void displayValue(const MyClass& obj)
{
cout << "The value is: " << obj.value << endl;
}

int main() {
MyClass obj(42); // Create an object of MyClass with value 42
displayValue(obj);
return 0;
}

Q. Write a sample program to show difference between c and c++

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

void main(){
printf("Hello Duniya !!!! ");
}

C++ ->>
#include <iostream>

using namespace std;

void main(){
cout<<"Hello Duniya!!!! ";
}

Q. Write a program to calculate factorial of a number using construrctor


#include <iostream>
using namespace std;

class Factorial {
private:
int number;
int fact;

public:
// Constructor to initialize the number and calculate the factorial
Factorial(int num) {
number = num;
fact = 1;
calculateFactorial();
}

// Function to calculate factorial


void calculateFactorial() {
for (int i = 1; i <= number; i++) {
fact *= i;
}
cout << "Factorial of " << number << " is " << fact << endl;
}

};

int main() {
int num;

// Input from user


cout << "Enter a number: ";
cin >> num;
// Create an object of the Factorial class
Factorial factObj(num);
return 0;
}

Q. Write a code to show the use of polymorphism


#include <iostream>
using namespace std;

// Base class (parent class)


class Animal {
public:
// Virtual function to allow polymorphism
virtual void speak() {
cout << "Some generic animal sound" << endl;
}
};

// Derived class (child class)


class Dog : public Animal {
public:
// Override the speak method
void speak() override {
cout << "Woof!" << endl;
}
};

// Another derived class (child class)


class Cat : public Animal {
public:
// Override the speak method
void speak() override {
cout << "Meow!" << endl;
}
};

// Another derived class (child class)


class Cow : public Animal {
public:
// Override the speak method
void speak() override {
cout << "Moo!" << endl;
}
};
// Function that uses polymorphism
void animalSpeak(Animal* animal) {
animal->speak();
}

int main() {
// Create objects of the derived classes
Dog dog;
Cat cat;
Cow cow;

// Passing objects of different types to the function (Polymorphism in action)


animalSpeak(&dog); // Output: Woof!
animalSpeak(&cat); // Output: Meow!
animalSpeak(&cow); // Output: Moo!

return 0;
}

Q. Write a program in c++ to calculate average marks of 50 students in the class


#include <iostream>
using namespace std;

int main() {
// Declare variables
const int NUM_STUDENTS = 50;
float marks[NUM_STUDENTS];
float sum = 0.0;
float average;

// Taking marks as input for each student


cout << "Enter marks for " << NUM_STUDENTS << " students:\n";
for(int i = 0; i < NUM_STUDENTS; i++) {
cout << "Enter marks for student " << (i+1) << ": ";
cin >> marks[i];

// Check if marks are within a valid range (0 to 100)


if(marks[i] < 0 || marks[i] > 100) {
cout << "Invalid input. Marks should be between 0 and 100.\n";
i--;
}
}

// Calculate the sum of marks


for(int i = 0; i < NUM_STUDENTS; i++) {
sum += marks[i];
}

// Calculate the average marks


average = sum / NUM_STUDENTS;

// Output the result


cout << "The average marks of the " << NUM_STUDENTS << " students is: " << average <<
endl;

return 0;
}
Q. Write a sample code to show the use of constructor
#include <iostream>
using namespace std;

// Base class
class Base {
public:
Base() {
cout << "Base class constructor called!" << endl;
}
};

// Derived class
class Derived : public Base {
public:
Derived() {
cout << "Derived class constructor called!" << endl;
} };

int main() {
// Creating an object of the derived class
Derived obj;
return 0;
}

Q. Write a code to show how overriding is achieved


#include <iostream>
using namespace std;

// Base class (parent class)


class Animal {
public:
// Virtual function to allow polymorphism
virtual void speak() {
cout << "Some generic animal sound" << endl;
}
};

// Derived class (child class)


class Dog : public Animal {
public:
// Override the speak method
void speak() override {
cout << "Woof!" << endl;
}
};

// Another derived class (child class)


class Cat : public Animal {
public:
// Override the speak method
void speak() override {
cout << "Meow!" << endl;
}
};
// Another derived class (child class)
class Cow : public Animal {
public:
// Override the speak method
void speak() override {
cout << "Moo!" << endl;
}
};

// Function that uses polymorphism


void animalSpeak(Animal* animal) {
animal->speak();
}

int main() {
// Create objects of the derived classes
Dog dog;
Cat cat;
Cow cow;

// Passing objects of different types to the function (Polymorphism in action)


animalSpeak(&dog); // Output: Woof!
animalSpeak(&cat); // Output: Meow!
animalSpeak(&cow); // Output: Moo!

return 0;
}

Q. Wap to show how exception handling achieved in c++


#include <iostream>
using namespace std;

// Function that divides two numbers and throws an exception if division by zero occurs
double divide(double numerator, double denominator) {
if (denominator == 0) {
// Throwing exception when division by zero is attempted
throw "Error: Division by zero!"; }
return numerator / denominator; }

int main() {
double num1, num2;

// Taking input from the user


cout << "Enter numerator: ";
cin >> num1;
cout << "Enter denominator: ";
cin >> num2;
try {
// Attempt to perform division
double result = divide(num1, num2);
cout << "Result: " << result << endl; }
catch (const char* msg) {
// Catching the exception and displaying the error message
cout << msg << endl; }

return 0; }
Q. WAP to update the content using random access.
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;

struct Record {
int id;
char name[50];
};

int main() {
string filename = "data.txt";
vector<Record> records;

// Read records from file


ifstream file(filename);
if (!file) {
cout << "File could not be opened!" << endl;
return 1;
}

Record record;
while (file >> record.id) {
file.ignore();
file.getline(record.name, 50);
records.push_back(record);
}
file.close();

// Ask for record number to update


cout << "Enter record number to update: ";
int recordNumber;
cin >> recordNumber;

if (recordNumber < 0 || recordNumber >= records.size()) {


cout << "Invalid record number!" << endl;
return 1;
}

// Display current record and take new input


cout << "Current Record: ID=" << records[recordNumber].id
<< ", Name=" << records[recordNumber].name << endl;

cout << "Enter new ID: ";


cin >> records[recordNumber].id;
cout << "Enter new name: ";
cin.ignore(); // To clear leftover newline
cin.getline(records[recordNumber].name, 50);

// Write updated records back to file


ofstream outFile(filename);
for (const auto& rec : records) {
outFile << rec.id << " " << rec.name << endl; }
cout << "Record updated successfully!" << endl;

return 0; }
Q.WAP to check palindrome
#include <iostream>
using namespace std;

bool isPalindrome(int number) {


int originalNumber = number;
int reversedNumber = 0;
int remainder;

// Reverse the given number


while (number != 0) {
remainder = number % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + remainder; // Build the reversed number
number /= 10; // Remove the last digit
}

return originalNumber == reversedNumber; }

int main() {
int num;
// Input the number
cout << "Enter a number: ";
cin >> num;

// Check if the number is a palindrome


if (isPalindrome(num)) {
cout << num << " is a palindrome number." << endl; }
else
{ cout << num << " is not a palindrome number." << endl; }
return 0;
}

Q.WAP to compare two string


#include <iostream>
#include <string>
using namespace std;

int main() {
string str1, str2;

// Input two strings


cout << "Enter the first string: ";
getline(cin, str1);
cout << "Enter the second string: ";
getline(cin, str2);

// Compare the two strings


if (str1 == str2) {
cout << "The strings are equal." << endl;
} else {
cout << "The strings are not equal." << endl;
}

return 0; }
Q. Wap to print following pattern
#include <iostream>
using namespace std;

int main() {

for (int i = 5; i >= 1; i--) {

for (int j = 1; j <= i; j++) {


cout << "* "; // Print a star followed by a space
}
cout << endl; // Move to the next line after each row
}
return 0;
}

Q.Wap to find sum of series


#include <iostream>

using namespace std;

int main(){
int num;
cout<<"Enter the Number";
cin>>num;

int sum = 0;
for (int i = 0; i <= num; i++)
{
sum+=i;
}

cout<<"The Sum of N number is "<< sum;


return 0;
}

Q. WAP to calculate area of rectangle, triangle and spehere


#include <iostream>
#include <cmath>
using namespace std;

// Function to calculate the area of a rectangle


double calculateArea(double length, double width) {
return length * width;
}

// Function to calculate the area of a triangle


double calculateArea(double base, double height, int) {
return 0.5 * base * height;
}
// Function to calculate the surface area of a sphere
double calculateArea(double radius) {
return 4 * M_PI * radius * radius;
}

int main() {
double length, width, base, height, radius;

// Rectangle
cout << "Enter the length and width of the rectangle: ";
cin >> length >> width;
cout << "Area of Rectangle: " << calculateArea(length, width) << endl;

// Triangle
cout << "Enter the base and height of the triangle: ";
cin >> base >> height;
cout << "Area of Triangle: " << calculateArea(base, height, 0) << endl;

// Sphere
cout << "Enter the radius of the sphere: ";
cin >> radius;
cout << "Surface Area of Sphere: " << calculateArea(radius) << endl;

return 0;
}

Q. Fibonacci Series
#include <iostream>
using namespace std;

int main() {
int num1 = 0, num2 = 1, nextTerm;
cout << "Fibonacci Series: ";

// Loop to print the first 10 numbers


for (int i = 0; i < 10; i++) {
if (i == 0) {
cout << num1 << " ";
continue;
}
if (i == 1) {
cout << num2 << " ";
continue;
}
nextTerm = num1 + num2; // Sum of the previous two terms
cout << nextTerm << " ";

// Update num1 and num2 for the next term


num1 = num2;
num2 = nextTerm;
}

cout << endl;


return 0;
}
Q. WAP to test the train class
#include <iostream>
#include <string>
using namespace std;

class Train {
private:
int trainNumber;
string trainName;
string source;
string destination;
int capacity;

public:
// Function to initialize train data
void initializeMember(int tNumber, string tName, string src, string dest, int
cap) {
trainNumber = tNumber;
trainName = tName;
source = src;
destination = dest;
capacity = cap;
}

// Function to input train data from the user


void inputTrainData() {
cout << "Enter Train Number: ";
cin >> trainNumber;
cin.ignore(); // To ignore the newline character left in the input buffer
cout << "Enter Train Name: ";
getline(cin, trainName);
cout << "Enter Source: ";
getline(cin, source);
cout << "Enter Destination: ";
getline(cin, destination);
cout << "Enter Capacity: ";
cin >> capacity;
}

// Function to display train data


void displayData() const {
cout << "\nTrain Details:" << endl;
cout << "Train Number: " << trainNumber << endl;
cout << "Train Name: " << trainName << endl;
cout << "Source: " << source << endl;
cout << "Destination: " << destination << endl;
cout << "Capacity: " << capacity << endl;
}
};

int main() {
Train train;
// Option to initialize or input train data
int choice;
cout << "Choose an option: \n1. Initialize Train Data\n2. Input Train Data\nEnter
your choice: ";
cin >> choice;

if (choice == 1) {
// Initialize train data using default values
train.initializeMember(12345, "Express Train", "City A", "City B", 500);
} else
if (choice == 2) {
// Input train data from the user
train.inputTrainData();
} else {
cout << "Invalid choice!" << endl;
return 1;
}

// Display the train data


train.displayData();

return 0;
}

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
// Name of the file to store data
string fileName = "telephone_list.txt";

// Create and open the file


ofstream outFile(fileName);

// Check if the file is open


if (!outFile) {
cerr << "Error: Unable to create the file." << endl;
return 1; // Exit the program with an error code
}

// Write data to the file


outFile << "John 34567\n";
outFile << "Hari 56792\n";

// Close the file


outFile.close();

cout << "Data has been written to " << fileName << " successfully!" << endl;
return 0;
}

You might also like