0% found this document useful (0 votes)
20 views35 pages

Solutions

oops

Uploaded by

thesandipsunar
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)
20 views35 pages

Solutions

oops

Uploaded by

thesandipsunar
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/ 35

/*

1. Define a function which receives a number as argument and returns 1 if the number is prime
otherwise returns 0. Use this function in main function to display all prime numbers between two
numbers.

#include<stdio.h>

// Function to check if a number is prime

int isprime(int n) {

if (n <= 1) return 0; // 0 and 1 are not prime numbers

for (int i = 2; i <= n / 2; i++) {

if (n % i == 0) {

return 0; // Not prime if divisible by i

return 1; // Prime number

int main() {

int start, end, i;

// Input the range

printf("Enter start number: ");

scanf("%d", &start);

printf("Enter end number: ");

scanf("%d", &end);

printf("Prime numbers between %d and %d are: ", start, end);

// Loop through the range and print prime numbers


for (i = start; i <= end; i++) {

if (isprime(i)) { // Check if the number is prime

printf("%d ", i); // Print the prime number

printf("\n");

return 0;

*/

/*

2. Write a program which asks order of two matrices and read two matrices of given order. Subtract
second matrix from first and display the resultant matrix.

#include<stdio.h>

int main()

int i, j, m, n;

printf("enter the value of m:\n");

scanf("%d", &m);

printf("enter the value of n:\n");

scanf("%d", &n);

printf("the required order of the matrix is: %d*%d\n", m, n);

int mat1[m][n], mat2[m][n], result[m][n];


//for matrix1

printf("enter the values for mat1:");

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

for(j=0; j<n; j++)

printf("enter values[%d][%d]\n", i+1, j+1);

scanf("%d", &mat1[i][j]);

printf("the values are: %d \n", mat1[i][j]);

//for matrix2

printf("enter the values for mat2:");

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

for(j=0; j<n; j++)

printf("enter values[%d][%d]\n", i+1, j+1);

scanf("%d", &mat2[i][j]);

printf("the values are: %d \n", mat2[i][j]);

//for result

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

for(j=0; j<n; j++)


{

result[i][j]=mat1[i][j]-mat2[i][j];

printf("the result is: %d \n", result[i][j]);

return 0;

//3. Write a program to read a string from user and reverse it without using string related library
function.

#include<stdio.h>

#include<stdlib.h>

int reverse(char str[], char reversestr[]){

int i, len=0;

while(str[len]!='\0')

len++;

for(i=0; i<len; i++)

reversestr[i]= str[len-i-1];

reversestr[len]='\0';

}
}

int main()

char str[100], reversestr[100];

printf("enter the string:\n");

scanf("%s", str);

//function call

reverse(str, reversestr);

printf("the reversed string is: %s ", reversestr);

return 0;

4. Write a program that determine the largest of three numbers using pointer.

#include<stdio.h>

int largest(int *n1, int *n2, int *n3, int *large)

if(*n1>*n2 && *n1>*n3)

*large= *n1;

else if(*n2>*n1&& *n2>*n3)

*large= *n2;
}

else

*large=*n3;

int main()

int n1, n2, n3, large;

printf("enter three numbers:");

scanf("%d %d %d", &n1, &n2, &n3);

largest(&n1, &n2, &n3, &large);

printf("The largest number is: %d", large);

return 0;

5. Write a program to read 10 numbers and reorders them in ascending order. Define separate
function for reading , sorting and displaying array elements.

#include<stdio.h>

void reading(int arr[], int size)

printf("enter %d numbers ", size);

for(int i=0; i<size; i++){

scanf("%d", &arr[i]);

}
void sorting(int arr[], int size)

for(int i=0; i<size-1; i++)

for(int j=0; j<size-i-1; j++)

if(arr[j]>arr[j+1])

int temp= arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;

void displaying(int arr[], int size)

printf(" the numbers in ascending order are:\n");

for(int i=0; i<size; i++)

printf("%d", arr[i]);

printf("\n");

int main()

int numbers[10];
int size=10;

reading(numbers, size);

sorting(numbers, size);

displaying(numbers, size);

return 0;

6. Define two functions getArraynum() to read an array from user and determine the greatest
number respectively. Write main program to declare as floating point type array of size 10 and pass this
array to first function getarraynum() to read its elements and then pass the same array to another function
greatestnum() to determine the greatest number among elements of the array.

#include<stdio.h>

void getarraynum(float arr[], int size)

printf("Enter %d float numbers", size);

for(int i=0; i<size; i++)

scanf("%f", &arr[i]);

float greatestnum(float arr[], int size)

float max= arr[0];


for(int i=1; i<size; i++)

if(arr[i]>max)

max= arr[i];

return max;

int main()

float numbers[10];

int size=10;

getarraynum(numbers, size);

float greatest= greatestnum(numbers, size);

printf("the greatest number is: %f", greatest);

return 0;

7. Create a structure named student that has name, roll, marks and remarks as members. Assume
appropriate types and size of member. Use this structure to read and display records of 4 students. Create
two functions: one is to read information of students and other is to display the information. Pass array of
structure to these functions.

#include <stdio.h>

#define SIZE 4 // Correct macro definition


// Structure definition for student

struct student {

char name[20]; // Name of the student

int roll; // Roll number of the student

float marks; // Marks obtained by the student

char remarks[100]; // Remarks (changed to an array for proper input)

};

// Function to read student information

void read(struct student stu[]) {

for (int i = 0; i < SIZE; i++) {

printf("Enter the information of student %d\n", i + 1);

printf("Enter name: ");

scanf("%s", stu[i].name); // Use %s to read strings

printf("Enter roll number: ");

scanf("%d", &stu[i].roll); // Read the roll number

printf("Enter marks: ");

scanf("%f", &stu[i].marks); // Read the marks

printf("Enter remarks: ");

scanf(" %[^\n]", stu[i].remarks); // Read remarks, allowing spaces

// Function to display student information

void display(struct student st[]) {

printf("Student Name\tRoll\tMarks\tRemarks\n");

for (int i = 0; i < SIZE; i++) {

printf("%s\t\t%d\t%.2f\t%s\n", st[i].name, st[i].roll, st[i].marks, st[i].remarks);

}
}

int main() {

struct student s[SIZE]; // Declare an array of student structures

printf("Student information\n");

read(s); // Call to read student data

printf("Detail information:\n");

display(s); // Call to display student data

return 0;

8. Define a class named distance with meter and cm as private data members and appropriate
function members. Use this class to read two objects of the distance class , add them by passing these two
objects to a function members and finally display result object in main() function.

#include<iostream>

using namespace std;

class distance

private:

int meter;

int cm;

public:

getvalue()

cout<<"enter distance in meter:";

cin>>meter;

cout<<"enter distance in cm";


cin>>cm;

cout<<"the distance in meter and cm are:" <<meter<<"and" <<cm;

}; incomplete one

9. Define a class shape with dim1 and dim2 as private members. Create two constructors of the
class, one with one argument and other with two arguments. Write a main() program to define object
rectangle with two dimensions and another object square with only one dimension using appropriate
constructor and calculate their area.

*/

#include<iostream>

using namespace std;

class shape

private:

int dim1, dim2;

public:

shape(int side):dim1(side), dim2(side)

shape(int length, int breadth): dim1(length), dim2(breadth)

int area()

{
return dim1*dim2;

};

int main()

shape rectangle(5,6);

cout<<"the area of rectangle is"<<rectangle.area()<<endl;

shape square(4);

cout<<"The area of square is:"<<square.area()<<endl;

return 0;

/*1. Design two classes, Rectangle and Circle. Each class has private members representing the
dimensions:

• The Rectangle class has private members length and width.

• The Circle class has a private member radius.

Write a friend function that calculates and displays:

1. The area of the rectangle.

2. The area of the circle.

#include<iostream>

using namespace std;

class circle ;

class rectangle

{
private:

float length;

float breadth;

public:

rectangle(float l, float b)

length=l;

breadth=b;

friend void calculatearea(rectangle rect, circle circ);

};

class circle

private:

float radius;

public:

circle(float r)

radius =r;

friend void calculatearea(rectangle rect, circle circ);

};

void calculatearea(rectangle rect, circle circ)

float rectarea=rect.length*rect.breadth;

float circarea= 3.1416*circ.radius*circ.radius;

cout<<"the area of rectangle is:"<<rectarea<<endl;

cout<<"the area of circle is:"<<circarea<<endl;


}

int main()

rectangle rect(10.0,10.0);

circle circ(10.0);

calculatearea(rect, circ);

return 0;

2.write a program which contains a class named box with appropriate data members and function
members. Initialize an object of the class with parameterized constructor and copy this object into another
object using copy constructor.

#include<iostream>

using namespace std;

class box

private:

float length, breadth, height;

public:

box(float len, float br, float he) //parameterized constructor

length=len;

breadth= br;

height= he;

box (box &b2) //copy constructor


{

length=b2.length;

breadth=b2.breadth;

height=b2.height;

void display()

cout<<"length:"<<length<<endl;

cout<<"breadth:"<<breadth<<endl;

cout<<"height:"<<height<<endl;

float volume()

return length*breadth*height;

};

int main()

float vol;

box b1(2,2,2);

box b2(b1);

cout<<"for the object b1:"<<endl;

b1.display();

vol= b1.volume();

cout<<"the volune of the box is:"<<vol<<endl;

cout<<"for the object b2:"<<endl;

b2.display();
vol= b2.volume();

cout<<"the volune of the box is:"<<vol<<endl;

return 0;

3. write a program to illustrate the use of destructor in program for destroying variables created
dynamically using new operator.

#include<iostream>

using namespace std;

class sample

private:

int *ptr;

public:

sample(int value){

ptr=new int;

*ptr=value;

cout<<"memory allocated for ptr and value assigned="<<*ptr<<endl;

~sample()

delete ptr;

cout<<"memory deallocated for ptr"<<endl;


}

void display()

cout<<"value of ptr:"<<*ptr<<endl;

};

int main()

sample obj(42);

obj.display();

return 0;

4.create a class polygon with data members: dimension1 and dimension2 and a member
function:readdimension() to read data members. Derive two classes rectangle and polygon class with
appropriate member function to calculate area of each rectangle and triangle.

#include<iostream>

using namespace std;

class polygon

protected:

float dimension1, dimension2;

public:
float readdimension()

cout<<"enter dimension1:"<<endl;

cin>>dimension1;

cout<<"enter dimension2:"<<endl;

cin>>dimension2;

cout<<"the dimension are:"<<dimension1<<"and"<<dimension2;

};

class rectangle: public polygon

public:

float area()

return dimension1*dimension2;

};

class triangle: public polygon

public:

float area()

return 0.5*dimension1*dimension2;

};

int main()

{
rectangle r;

triangle t;

cout<<"Reading data for rectangle"<<endl;

r.readdimension();

cout<<"the area of rectangle is"<<r.area()<<endl;

cout<<"Reading data for triangle"<<endl;

t.readdimension();

cout<<"the area of triangle is"<<t.area()<<endl;

return 0;

5. write a program to illustrate the use of virtual base class.

6. Define a class BankAccount with:

• Private members: accountNumber, accountHolderName, and balance.

• A constructor to initialize the account.

• A destructor to display a message when the object is destroyed.

• A member function deposit() to add money to the account.

• A member function withdraw() to remove money from the account (with a condition that balance
should not go negative).

Write a main program to demonstrate the usage of the constructor, destructor, and member functions.
#include<iostream>

using namespace std;

class BankAccount

private:

int accountnumber;

string accountHolderName;

float balance;

public:

BankAccount(int accnum, string ahname, float initialbalance)

accountnumber= accnum;

accountHolderName= ahname;

balance=initialbalance;

cout<<"Account created for"<<accountHolderName<<"with balance"<<balance<<endl;

~BankAccount()

cout<<"the account of"<<accountHolderName<<"is closed"<<endl;

void deposit(float amount)

balance= balance+amount;

cout<<"the total amount after deposit is"<<balance<<endl;

void withdraw(float amount)

if(amount>balance)
{

cout<<"insufficient balance!"<<endl;

else

balance=balance-amount;

cout<<"The total balance after withdraw is:"<<balance<<endl;

void display()

cout<<"The total amount in the account is"<<balance<<endl;

};

int main()

BankAccount B(1234, "Bachha", 2000);

B.deposit(500);

B.withdraw(500);

B.display();

return 0;

7. Define a class MathOperations with the following overloaded functions:

• add(int, int) to add two integers.

• add(float, float) to add two floating-point numbers.


• add(int, int, int) to add three integers.

Write a main program to demonstrate function overloading by calling each of these functions.

#include<iostream>

using namespace std;

class mathoperations

public:

int add(int a, int b)

return a+b;

float add(float a, float b)

return a+b;

int add(int a, int b, int c)

return a+b+c;

};

int main()

mathoperations mathop;

int result1=mathop.add(25, 20);

cout<<"The addition of two integers is:"<<result1<<endl;

float result2=mathop.add(25.0f,20.0f);
cout<<"The addition of two float numbers is:"<<result2<<endl;

int result3=mathop.add(50, 50, 50);

cout<<"The addition of three integers is:"<<result3<<endl;

return 0;

8. Create a base class Shape with a virtual function area(). Derive two classes Rectangle and Circle from
Shape. Override the area() function in both derived classes to calculate:

• Area of the rectangle: length * width

• Area of the circle: π * radius^2

Write a program to demonstrate the concept of function overriding and calculate the area of a rectangle
and a circle using the base class pointer.

*/

#include <iostream>

using namespace std;

class shape {

public:

virtual float area() = 0; // Pure virtual function

};

class rectangle : public shape {

private:

int length;
int breadth;

public:

rectangle(int l, int b) {

length = l;

breadth = b;

float area() override { // Corrected placement of override

return length * breadth;

};

class circle : public shape {

private:

float radius;

public:

circle(float r) {

radius = r;

float area() override { // Corrected placement of override

return 3.1416 * radius * radius;

};

int main() {

// Base class pointer to Rectangle object

shape* shape1 = new rectangle(5, 10); // Changed Rectangle to rectangle

shape* shape2 = new circle(5);


// Calculate and display the areas

cout << "Area of the rectangle: " << shape1->area() << endl;

cout << "Area of the circle: " << shape2->area() << endl;

// Free dynamically allocated memory

delete shape1;

delete shape2;

return 0;

/*

9. Create a base class Person with private members: name and age. Derive a class Student that inherits
from Person and adds private members:

rollNumber and marks. Write a friend function that accepts a Student object as a parameter and
displays all the details (both Person

and Student class members) of the student.

/*

#include<iostream>

using namespace std;

class person {

private:

string name;

int age;

public:
// Constructor for person class

person(string n, int a) {

name = n;

age = a;

// Friend function declaration

friend void displaydetails(const class student& s);

};

class student : public person {

private:

int rollno;

double marks;

public:

// Constructor for student class which also calls person constructor

student(string n, int a, int r, double m) : person(n, a) {

rollno = r;

marks = m;

// Friend function declaration

friend void displaydetails(const student& s);

};

// Friend function definition to display details

void displaydetails(const student& s) {

// Access private members of both person and student

cout << "Name: " << s.name << endl;


cout << "Age: " << s.age << endl;

cout << "Roll Number: " << s.rollno << endl;

cout << "Marks: " << s.marks << endl;

int main() {

// Create a student object and pass name, age, rollno, and marks

student s1("Hari", 25, 2, 25.0);

// Call the friend function to display the student's details

displaydetails(s1);

return 0;

10. Write a class called Student that includes private member variables for name, class, roll number, and
marks. Include methods to calculate the grade

based on marks and display the student’s information.

#include<iostream>

using namespace std;

class student

private:

string name;
int classs;

int rollno;

double marks;

public:

string grade()

string grade;

if (marks>80)

cout<<"Grade A+"<<endl;

else if(marks>60)

cout<<"Grade B"<<endl;

else{

cout<<"Grade c";

void display()

cout<<"enter name"<<endl;

cin>>name;

cout<<"enter class"<<endl;

cin>>classs;

cout<<"enter rollno"<<endl;

cin>>rollno;

cout<<"enter marks"<<endl;

cin>>marks;
cout<<"Detailed information of student is:"<<endl;

cout<<"Name:"<<name<<endl;

cout<<"class:"<<classs<<endl;

cout<<"rollno:"<<rollno<<endl;

cout<<"marks"<<marks<<endl;

cout<<"Grade obtained by student is:"<<grade()<<endl;

};

int main()

student s;

s.display();

return 0;

Create a class Matrix for handling 2D matrices. Overload the + and - operators to perform matrix addition
and subtraction.

Implement a constructor that initializes the matrix with random values.

#include<iostream>

using namespace std;

class matrix

private:

int rows;
int cols;

int mat[3][3];

public:

matrix()

rows=3;

cols=3;

for(int i=0; i<rows; i++)

for(int j=0; j<cols; j++)

mat[i][j]=0;

matrix operator + (const matrix& m)

matrix temp;

};

*/

#include <iostream>

#include <cstdlib> // For random number generation

using namespace std;

class Matrix {

private:
int rows, cols;

int mat[3][3]; // A fixed-size 3x3 matrix for simplicity

public:

// Constructor to initialize the matrix with random values

Matrix() {

rows = 3;

cols = 3;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

mat[i][j] = rand() % 10; // Initialize with random values (0-9)

// Overloading the + operator to add two matrices

Matrix operator + (const Matrix& m) {

Matrix temp;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

temp.mat[i][j] = mat[i][j] + m.mat[i][j];

return temp;

// Overloading the - operator to subtract two matrices

Matrix operator - (const Matrix& m) {

Matrix temp;
for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

temp.mat[i][j] = mat[i][j] - m.mat[i][j];

return temp;

// Method to display the matrix

void display() {

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

cout << mat[i][j] << " ";

cout << endl;

};

int main() {

Matrix m1, m2, sum, diff;

// Display the original matrices

cout << "Matrix 1:" << endl;

m1.display();

cout << "\nMatrix 2:" << endl;

m2.display();
// Perform matrix addition and subtraction

sum = m1 + m2;

diff = m1 - m2;

// Display the results

cout << "\nSum of Matrix 1 and Matrix 2:" << endl;

sum.display();

cout << "\nDifference of Matrix 1 and Matrix 2:" << endl;

diff.display();

return 0;

You might also like