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

C++ Programs for Basic Algorithms and Data Structures

The document contains multiple C++ programming exercises that cover various topics such as finding the largest number in an array, checking for prime numbers, generating patterns, and implementing classes with inheritance. It also includes examples of binary search (both recursive and non-recursive), calculating GCD, and performing matrix operations with exception handling. Each question is followed by a complete C++ code implementation and its expected output.

Uploaded by

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

C++ Programs for Basic Algorithms and Data Structures

The document contains multiple C++ programming exercises that cover various topics such as finding the largest number in an array, checking for prime numbers, generating patterns, and implementing classes with inheritance. It also includes examples of binary search (both recursive and non-recursive), calculating GCD, and performing matrix operations with exception handling. Each question is followed by a complete C++ code implementation and its expected output.

Uploaded by

shauryadodeja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Ques 1: WAP to find the largest of n natural

numbers.

Ans:
#include<iostream>
using namespace std;
int main()
{
int max,n,x[n];
cout<<"Program to find the largest of the n numbers."<<endl;
cout<<"Enter the size of the Array : ";
cin>>n;
cout<<"Now enter the series of the numbers :-"<<endl;
for(int i=0;i<n;i++)
{
cout<<"Enter Number : ";
cin>>x[i];
}
max=x[0];
for(int j=1;j<n;j++)
{
if(x[j]>max)
{
max=x[j];
}
}
cout<<"Maximum number is : "<<max;
return 0;
}

Output :-
Ques 2: WAP to find whether a given number is
prime or not.

Ans:
#include <iostream>
using namespace std;
int main()
{
int a,factor=0;
cout<<"Program to find the whether a given number is Prime or not."<<endl;
cout<<"Enter a number : ";
cin>>a;
for(int i=1;i<=a;i++)
{
if(a%i==0)
{
factor++;
}
}
if(factor==2)
{
cout<<"Entered number is Prime Number.";
}
else
{
cout<<"Entered number is not Prime Number.";
}
return 0;
}

Output :-
Ques 3: WAP that takes a positive integer n and the
produce n lines of output as shown:
*
**
***
**** (sample output for
n=4)

Ans:
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a number :";
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
cout<<"*";
}
cout<<endl;
}
return 0;
}

Output :-
Ques 4: Write a menu driven program for
following :-
a. To check whether a given number is odd or even.
b. Display a Fibonacci series.
c. Compute factorial of a number.

Ans:
#include <iostream>
using namespace std;
int main()
{
int choice;
cout<<"Enter choice 1 to find whether the given number is odd or even."<<endl;
cout<<"Enter choice 2 to display Fibonacci series."<<endl;
cout<<"Enter choice 3 to compute factorial of a number."<<endl<<endl;
cout<<"Enter choice :";
cin >> choice;
switch(choice)
{
case 1:
{
int num;
cout<<"Program to find whether the given number is odd or even."<<endl;
cout<<"Enter a number :";
cin>>num;
if(num%2==0)
cout<<"Entered number is Even.";
else
cout<<"Entered number is Odd.";
break;
}
case 2:
{
cout<<"Program to display Fibonacci series."<<endl;
int term,x,y,z;
cout<<"Enter first number x (usually 0):";
cin>>x;
cout<<"Enter second number y (usually 1):";
cin>>y;
cout<<"Enter number of terms:";
cin>>term;
cout<<x<<" "<<y<<" ";
for(int i=1;i<=term-2;i++)
{
z= x+y;
cout<<z<<" ";
x=y;
y=z;
}
break;
}
case 3:
{
cout << "Program to compute Factorial of a number."<<endl;
int num1,fac=1;
cout<<"Enter a number :";
cin>>num1;
for(int i=1;i<=num1;i++)
{
fac *= i;
}
cout<<"Factorial of entered number is :"<< fac;
break;
}
default:
cout << "Wrong Choice";
break;
}
return 0;
}

Output :-
Ques 5: Write a program to perform the following
operations on an input string
a. Print length of the string
b. Find frequency of a character in the string
c. Print whether characters are in uppercase or
lowercase

Ans a:
#include <iostream>
using namespace std;
int main()
{
string str;
cout<<"Program to print length of the given string."<<endl;
cout<<"Enter any string:";
cin>>str;
cout<<"String Length = "<< [Link]();
return 0;
}

Output :-

Ans b:
#include <iostream>
using namespace std;
int main()
{
string str;
char ch;
cout<<"Enter any string: ";
getline(cin, str);
cout<<"Enter any character to find its frequency: ";
cin>>ch;
int frequency=0;
for (int i=0;i<[Link]();i++)
{
if (str[i]==ch)
{
frequency++;
}
}
cout<<"Number of '"<<ch<<"' = "<<frequency;
return 0;
}

Output :-

Ans c:
#include <iostream>
using namespace std;
int main()
{
char t;
cout<<"Enter any character : ";
cin>>t;
if ((t>='A')&&(t<='Z'))
{
cout<<"UPPER";
}
else if((t>='a')&&(t<='z'))
{
cout<<"LOWER";
}
else
{
cout<<"ERROR";
}
return 0;
}
Output :-
Ques 6: Design a class named Vehicle, having
registration number and year as its private
members. Define a suitable constructor and a
method to print the details of a vehicle. Write a C+
+ program to test the above class.

Ans:
#include <iostream>
using namespace std;
class vehicle
{
private:
int rno;
int year;
public:
void getvalue();
void showvalue();
};
void vehicle::getvalue()
{
cout<<"Enter the register number in vehicle : ";
cin>>rno;
cout<<"Enter the year : ";
cin>>year;
}
void vehicle::showvalue()
{
cout<<"Registration No.:"<<rno<<endl<<"Year:"<<year;
}
int main()
{
vehicle v;
[Link]();
[Link]();
return 0;
}

Output :-

Same above program with a constructor :-


Ans :
#include <iostream>
using namespace std;
class vehicle {
private:
int rno;
int year;
public:
void getvalue();
void showvalue();
vehicle(int r,int y)
{
rno=r;
year=y;
}
};
void vehicle::showvalue()
{
cout<<"Registration No.:"<<rno<<endl<<"Year:"<<year;
}
int main()
{
vehicle v(15,2022);
[Link]();
return 0;
}

Output :-

Q
ues 7: Inherit a class Car from the Vehicle class
defined above. Add model to the Car class. Define a
suitable constructor and a method to print the
details of a car. Write a C++ program to test
inheritance of this class.
Ans :
#include <iostream>
using namespace std;
class vehicle {
private:
int rno;
int year;
public:
void getvalue();
void showvalue();
};
class car:public vehicle
{
public:
int model;
car(int m)
{
model=m;
}
void showvalues();
};
void vehicle::getvalue()
{
cout<<"Enter the register number in vehicle : ";
cin>>rno;
cout<<"Enter the year : ";
cin>>year;
}
void vehicle::showvalue()
{
cout<<"Registration No.:"<<rno<<endl<<"Year:"<<year<<endl;
}
void car::showvalues()
{
cout<<"Model No.:"<<model;
}
int main() {
car c(7);
[Link]();
[Link]();
[Link]();
return 0;
}
Output :-

Q.8: Write a program to search a given element in


a set of N numbers using Binary Search
(a) With recursion
Ans :
#include <iostream>
using namespace std;
int binarySearch(int array[],int x,int low,int high)
{
if (high>=low)
{
int mid=low+(high-low)/2;
if (array[mid]==x)
return mid;
if (x>array[mid])
return binarySearch(array,x,mid+1,high);
return binarySearch(array,x,low,mid-1);
}
return -1;
}
int main()
{
int n;
cout<<"Enter size of array: ";
cin>>n;
int array[n];
cout<<"Enter "<<n<<" sorted elements:"<<endl;
for (int i=0;i<n;i++)
{
cin>>array[i];
}
int x;
cout<<"Enter the element to search: ";
cin>>x;
int result=binarySearch(array,x,0,n-1);
if (result==-1)
cout<<"Element not found";
else
cout<<"Element found at index "<<result<<" (position "<<result+1<<")";
return 0;
}
Output :-
(b) Without recursive
Ans :
#include <iostream>
using namespace std;
int binarySearch(int array[],int x,int n)
{
int low=0;
int high=n-1;
while (low<=high)
{
int mid=low+(high-low)/2;
if (array[mid]==x)
return mid;
else if (array[mid]<x)
low=mid+1;
else
high=mid-1;
}
return -1;
}
int main()
{
int n;
cout<<"Enter size of array: ";
cin>>n;
int array[100];
cout<<"Enter "<<n<<" elements in sorted order:"<<endl;
for (int i=0;i<n;i++)
{
cin>>array[i];
}
int x;
cout<<"Enter element to search: ";
cin>>x;
int result=binarySearch(array,x,n);
if (result==-1)
cout<<"Element not found";
else
cout<<"Element found at index "<<result<<"(position "<<result+1<<")";
return 0;
}
Output :-

Ques 9: Write a program to calculate GCD of two


numbers
a. With recursion

Ans :
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (b==0)
return a;
return gcd(b,a%b);
}
int main()
{
int a,b;
cout<<"Enter two number to find their GCD"<<endl;
cout<<"Enter num 1: ";
cin>>a;
cout<<"Enter num 2: ";
cin>>b;
cout<<"GCD is "<<gcd(a,b);
return 0;
}

Output :-

b. Without recursion

Ans :
#include <iostream>
using namespace std;
void input(int& a, int& b);
int gcdnum(int a, int b);
void input(int& a, int& b)
{
cout<<"Enter num 1: ";
cin>>a;
cout<<"Enter num 2: ";
cin>>b;
}
int gcdnum(int a, int b)
{
int min,i,gcd=1;
min=(a<b)?a:b;
for (i=1;i<=min;i++)
{
if (a%i==0&&b%i==0)
{
gcd=i;
}
}
return gcd;
}
int main()
{
int a,b;
cout<<"Enter two numbers to find ther GCD"<<endl;
input(a,b);
int ans=gcdnum(a,b);
cout<<"GCD is "<<ans;
return 0;
}

Output :-

Ques 10: Define a class Person having name as a


data member. Inherit two classes Student and
Employee from Person. Student has additional
attributes as course, marks and year and Employee
has department and salary. Write display() method
in all the three classes to display the corresponding
attributes. Provide the necessary methods to show
runtime polymorphism.

Ans :
#include <iostream>
using namespace std;
class Person{
char name[20];
public:
Person(){}
void input(){
cout<<"Enter Name: ";
cin>>name;
}
void display(){
cout<<"Name: "<<name<<endl;
}
};
class Student:public Person{
char course[20];
float marks;
int year;
public:
Student(float m1,int y)
{
marks=m1;
year=y;
}
void input()
{
cout<<"--- Student Details Input ---"<<endl;
Person::input();
cout<<"Enter course, marks and year: "<<endl;
cin>>course>>marks>>year;
}
void display()
{
cout<<endl<<"--- Student Details ---"<<endl;
Person::display();
cout<<"Course: "<<course<<endl;
cout<<"Marks: "<<marks<<endl;
cout<<"Year: "<<year<<endl;
}
};
class Employee:public Person
{
char department[20];
float salary;
public:
Employee(float s)
{
salary=s;
}
void input()
{
cout<<endl<<"--- Employee Details Input ---"<<endl;
Person::input();
cout<<"Enter department and salary: "<<endl;
cin>>department>>salary;
}
void display()
{
cout<<endl<<"--- Employee Details ---"<<endl;
Person::display();
cout<<"Department: "<<department<<endl;
cout<<"Salary: "<<salary<<endl;
}
};
int main()
{
Person bp;
Student o1(4.5,4);
Employee o2(6.2);
[Link]();
[Link]();
[Link]();
[Link]();
return 0;
}
Output :-
Ques 11: Copy the contents of one text file to
another file, after removing all whitespaces.

Ans :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
ifstream fin("[Link]");
ofstream fout("[Link]");
if (!fin || !fout)
{
cout<<"Error opening file.";
return 0;
}
while ([Link](ch))
{
if (!isspace(ch))
[Link](ch);
}
[Link]();
[Link]();
cout<<"Copied after removing all whitespaces.";
return 0;
}
Output :-

Ques 12: Create a Matrix class. Write a menu-


driven program to perform following Matrix
operations (exceptions should be thrown by the
functions if matrices passed to them are
incompatible and handled by the main() function):
a. Sum
b. Product
c. Transpose

Ans :
#include <iostream>
#include <stdexcept>
using namespace std;
class Matrix
{
int a[10][10], r, c;
public:
Matrix(int x=0, int y=0){r=x; c=y;}
void input()
{
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cin>>a[i][j];
}
void display()
{
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
Matrix add(Matrix m)
{
if(r!=m.r || c!=m.c)
throw runtime_error("Addition not possible");
Matrix t(r,c);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
t.a[i][j]=a[i][j]+m.a[i][j];
return t;
}
Matrix multiply(Matrix m)
{
if(c!=m.r)
throw runtime_error("Multiplication not possible");
Matrix t(r,m.c);
for (int i=0;i<r;i++)
{
for (int j=0;j<m.c;j++)
{
t.a[i][j]=0;
for (int k=0;k<c;k++)
t.a[i][j]+=a[i][k]*m.a[k][j];
}
}
return t;
}
Matrix transpose()
{
Matrix t(c,r);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
t.a[j][i]=a[i][j];
return t;
}
};
int main()
{
int ch;
do
{
cout<<"[Link] [Link] [Link] [Link]"<<endl<<"Choice: ";
cin>>ch;
try
{
if(ch==1)
{
int r,c;
cout<<"Enter rows & columnss: ";
cin>>r>>c;
Matrix m1(r,c), m2(r,c);
cout<<"Enter Matrix 1:"<<endl;
[Link]();
cout<<"Enter Matrix 2:"<<endl;
[Link]();
cout<<"Sum Result : "<<endl;
Matrix res = [Link](m2);
[Link]();
}
else if(ch==2)
{
int r1,c1,r2,c2;
cout<<"Enter rows & columns of M1: ";
cin>>r1>>c1;
cout<<"Enter rows & columns of M2: ";
cin>>r2>>c2;
Matrix m1(r1,c1), m2(r2,c2);
cout<<"Enter M1:"<<endl;
[Link]();
cout<<"Enter M2:"<<endl;
[Link]();
cout<<"Multiply Result : "<<endl;
Matrix res = [Link](m2);
[Link]();
}
else if(ch==3)
{
int r,c;
cout<<"Enter rows & columns: ";
cin>>r>>c;
Matrix m(r,c);
cout << "Enter matrix:"<<endl;
[Link]();
cout << "Transpose Result : "<<endl;
Matrix res = [Link]();
[Link]();
}
else if (ch !=4)
{
cout<<"Invaild Choice"<<endl;
}
}
catch(runtime_error &e)
{
cout<<"Error: "<<[Link]()<<endl;
}
}
while(ch!=4);
return 0;
}
Output :-

You might also like