0% found this document useful (0 votes)
32 views

C++ Codes

C++ Codes for practicals

Uploaded by

Shlok khunte
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)
32 views

C++ Codes

C++ Codes for practicals

Uploaded by

Shlok khunte
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/ 27

C++ Codes

1) WAP to overload '= =' operator.


Code:-
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}

// Overload the '==' operator


bool operator==(const Complex& obj)
{
return (real == obj.real) && (imag == obj.imag);
}

void print()
{
cout << real << " + i" << imag << '\n';
}
};

int main()
{
Complex c1(10, 5), c2(10, 5);

if (c1 == c2)
{
cout << "The complex numbers are equal.\n";
}
else
{
cout << "The complex numbers are not equal.\n";
}

return 0;
}

2) WAP to print prime number using Constructor.


Code :-
#include <iostream>
using namespace std;
class PrimeChecker
{
private:
int number;

public:
// Constructor to initialize the number
PrimeChecker(int n)
{

number = n;
}

// Function to check if a number is prime


bool isPrime()
{
if (number <= 1)
return false;

for (int i = 2; i * i <= number; ++i)


{
if (number % i == 0)
return false;
}
return true;
}
};

int main()

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

PrimeChecker primeObj(num);

if (primeObj.isPrime())
cout << "The number is prime.\n";
else
cout << "The number is not prime.\n";

return 0;
}

3) WAP to print the string in reverse order.


Code :-
#include <iostream>
#include <string>
using namespace std;

int main() {
string input;
cout << "Enter a string: ";
getline(cin, input);
cout << "Reversed string: ";
for (int i = input.length() - 1; i >= 0; i--) {
cout << input[i];
}

return 0;
}

4) Write a program to illustrate try-catch concept enter user id and


password from user if entered wrongly throw an exception.
Code:-
#include <iostream>
#include <string>
int main()
{
std::string userID, password;

// Hardcoded correct user ID and password for demonstration purposes


const std::string correctUserID = "user123";
const std::string correctPassword = "pass123";

std::cout << "Enter user ID: ";


std::cin >> userID;
std::cout << "Enter password: ";
std::cin >> password;

if (userID == correctUserID && password == correctPassword)


{
std::cout << "Login successful!" << std::endl;
}
else
{
std::cout << "Invalid user ID or password!" << std::endl;
}
return 0;
}

5) WAP to display the entered string is palindrome or not.


Code :-
#include <iostream>
#include <string>
using namespace std;

bool Palindrome(const string& str)


{
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left] != str[right])
{
cout << "The entered string is not a palindrome.\n";
return false;
}
++left;
--right;
}
cout << "The entered string is a palindrome.\n";
return true;
}

int main()
{
string str;
cout << "Enter a string: ";
cin >> str;

Palindrome(str);
return 0;
}

6) WAP to display Simple Interest using inline function.


Code:-
#include<iostream>
using namespace std;
inline float SimpleInterest(float p, float r, float t)
{
return (p * r * t) / 100;
}

int main() {
float principal, rate, time;
cout << "Enter principal amount: ";
cin >> principal;
cout << "Enter rate of interest: ";
cin >> rate;
cout << "Enter time (in years): ";
cin >> time;

float interest = SimpleInterest(principal, rate, time);


cout << "The Simple Interest is: " << interest;

return 0;
}

7) WAP to overload ‘*’ operator.


Code:-
#include<iostream>
using namespace std;
class Multiply
{
public:
int num;
Multiply(int n = 0) {num = n;}

// Overloading the * operator


Multiply operator * (Multiply const &obj)
{
Multiply result;
result.num = num * obj.num;
return result;
}

void print() { cout << "Result is: " << num << endl; }
};

int main()
{
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;

Multiply m1(num1), m2(num2);


Multiply m3 = m1 * m2;
m3.print();
}

8)WAP to overload ' << ' and ' >> ' operator.
Code:-
#include<iostream>
using namespace std;
class Simple
{
public:
int num;
};

ostream & operator << (ostream &out, const Simple &s)


{
out << s.num;
return out;
}

istream & operator >> (istream &in, Simple &s)


{
in >> s.num;
return in;
}

int main()
{
Simple s;
cout << "Enter a number: ";
cin >> s;
cout << "The number is: " << s;
return 0;
}

9)WAP to print Armstrong of a number.


Code:-
#include<iostream>
#include<cmath>
using namespace std;
bool Armstrong(int num)
{
int originalNum, remainder, result = 0;
originalNum = num;
while (originalNum != 0)
{
remainder = originalNum%10;
result += pow(remainder, 3);
originalNum /= 10;
}

return (result == num);


}

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

if(Armstrong(num))
cout << num << " is an Armstrong number.";
else
cout << num << " is not an Armstrong number.";

return 0;
}

10)Write a program to find out maximum of three numbers using


INLINE function.
Code:-
#include <iostream>
using namespace std;
inline int max_of_three(int a, int b, int c)
{

return max(max(a, b), c);


}

int main()
{
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

int max = max_of_three(a, b, c);

cout << "The maximum of the three numbers is: " << max << endl;

return 0;
}

11)Write a program to show a main function can be friend function of


a class.
Code:-
#include <iostream>
using namespace std;
class MyClass
{
private:
int privateVar;
public:
MyClass() : privateVar(10) {}
friend int main();
};

int main()
{
MyClass obj;
cout << "Accessing private member of MyClass from main: " <<
obj.privateVar << endl;
return 0;
}

11) Write a program to illustrate try-catch with the division by zero


exception.
Code:-
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
double result;

cout << "Enter two numbers: ";


cin >> num1 >> num2;

try {
if(num2 == 0)
{
throw "Division by zero condition!";
}
result = (double)num1 / num2;
cout << "The result is: " << result << endl;
}
catch(const char* msg)
{
cerr << "Error: " << msg << endl;
}

return 0;
}
12)print the following pattern using CONSTRUCTOR
1
23
456
78910
Code:-
#include <iostream>
using namespace std;
class Pattern
{
int counter;
public:
Pattern() : counter(1) {} // Constructor initializes counter to 1

void printPattern(int n)
{
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= i; ++j)
{
cout << counter++;
}
cout << endl;
}
}
};

int main()
{
Pattern p;
int n;

cout << "Enter the number of lines for the pattern: ";
cin >> n;
p.printPattern(n); // Prints the pattern up to n lines

return 0;
}

13)Write a program to find factorial of a number using copy


constructor.
Code:-
#include<iostream>
using namespace std;
class Factorial
{
public:
int num;
long long fact;

// Constructor to calculate factorial


Factorial(int n)
{
num = n;
fact = 1;
for(int i = 1; i <= n; i++)
{
fact *= i;
}
}

// Copy constructor
Factorial(Factorial &f)
{
num = f.num;
fact = f.fact;
}
void display()
{
cout << "Factorial of " << num << " is " << fact << endl;
}
};

int main()
{
int number;
cout << "Enter a number : ";
cin >> number;

Factorial f1(number); // This will calculate factorial


Factorial f2 = f1; // Copy constructor will be called here

f2.display(); // This will display the factorial

return 0;
}

14)Write a program to find fibonacii of a number.


Code:-
#include<iostream>
using namespace std;
int main()
{
int n, t1 = 0, t2 = 1, nextTerm = 0;

cout << "Enter a number : ";


cin >> n;

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


{
if(i == 1)
{
cout << t1 << ", ";
continue;
}
if(i == 2)
{
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;

cout << nextTerm << ", ";


}

return 0;
}

15)Write a program to accept age, if age is greater than or equal to 18


print msg' driving 1) license can be issued otherwise throw an
exception.
Code:-
#include<iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age: ";
cin >> age;

if(age >= 18)


{
cout << "Driving license can be issued.";
}
else
{
cout << "Age must be at least 18 for a driving license.";
}

return 0;
}

16)Write a program to print number is odd or even if even square root


of that number.
Code:-
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;

if(num % 2 == 0)
{
cout << num << " is even." << endl;
cout << "Square root of " << num << " is " << sqrt(num);
}
else
{
cout << num << " is odd.";
}

return 0;
}
17)Write a program to accept two numbers from user and display sum
of two numbers using constructor.
Code:-
#include<iostream>
using namespace std;
class Sum
{
int num1, num2, sum;

public:
// Constructor to initialize and calculate sum
Sum(int n1, int n2)
{
num1 = n1;
num2 = n2;
sum = num1 + num2;
}

void display()
{
cout << "Sum of " << num1 << " and " << num2 << " is " << sum <<
endl;
}
};

int main()
{
int number1, number2;

cout << "Enter first number: ";


cin >> number1;

cout << "Enter second number: ";


cin >> number2;
// Create object of Sum class
Sum s(number1, number2);

// Display the sum


s.display();

return 0;
}

18)Write a program to find square root of an number with different


data type using function overloading concept.
Code:-
#include<iostream>
#include<cmath> // for sqrt function
using namespace std;

// Function to find square root of int


void findSquareRoot(int num) {
cout << "Square root of " << num << " is " << sqrt(num) << endl;
}

// Function to find square root of double


void findSquareRoot(double num) {
cout << "Square root of " << num << " is " << sqrt(num) << endl;
}

int main() {
int num1 = 16;
double num2 = 15.5;

// Call function with int


findSquareRoot(num1);
// Call function with double
findSquareRoot(num2);

return 0;
}

Q19)Write a program to overload "++" and "-" operator.


Code:-
#include<iostream>
using namespace std;
class Number
{
public:
int num;

// Constructor
Number(int n = 0) : num(n) {}

// Overload "+" operator


Number operator+(Number const &obj)
{
Number res;
res.num = this->num + obj.num;
return res;
}

// Overload "-" operator


Number operator-(Number const &obj)
{
Number res;
res.num = this->num - obj.num;
return res;
}
};
int main()
{
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;

Number a(x), b(y);


Number c = a + b;
Number d = a - b;

cout << "Result of addition: " << c.num << endl;


cout << "Result of subtraction: " << d.num << endl;

return 0;
}

Q20)Write a program to print the following pattern


A
AB
ABC
ABCD
Code:-
#include <iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter the number of rows: ";
cin >> rows;

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


{
for(int j = 0; j <= i; ++j)
{
cout << char('A' + j);
}
cout << endl;
}
return 0;
}

Q21)Write program to print given string is palindrome or not.


Code:-
#include <iostream>
#include <string>
using namespace std;

bool Palindrome(const string& str)


{
int n = str.length();
for(int i = 0; i < n / 2; ++i)
{
if(str[i] != str[n - i - 1])
{
return false;
}
}
return true;
}

int main()
{
string input;
cout << "Enter a string: ";
cin >> input;

if(Palindrome(input))
{
cout << "\"" << input << "\" is a palindrome." << endl;
}
else
{
cout << "\"" << input << "\" is not a palindrome." << endl;
}
return 0;
}

Q22) WAP to illustrate multilevel inheritance concept.


Code:-
#include <iostream>
using namespace std;

// Base class
class Animal
{
public:
void eat()
{
cout << "Eating..." << endl;
}
};

// Derived class
class animal : public Animal
{
public:
void breathe()
{
cout << "Breathing..." << endl;
}
};
// Derived class
class Dog : public animal
{
public:
void bark()
{
cout << "Barking..." << endl;
}
};

int main()
{
Dog d;
d.eat(); // Inherited from Animal
d.breathe(); // Inherited from animal
d.bark(); // Own function
return 0;
}

Q23)Write a C++ program using class to print factorial of number.


Code:-
#include <iostream>
using namespace std;

class FactorialCalculator
{
public:
// Function to calculate factorial
unsigned long long calculate(int n)
{
if (n <= 1) return 1;
return n * calculate(n - 1);
}
};

int main()
{
FactorialCalculator fc;
int number;

cout << "Enter a number : ";


cin >> number;

cout << "Factorial of " << number << " is " << fc.calculate(number) <<
endl;

return 0;
}

Q24)Write a C++ program to compare strings (length wise) using '>',


'<', '=" operator.
Code:-
#include <iostream>
#include <string>
using namespace std;

int main() {
string str1, str2;

// Input two strings


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

// Compare the lengths of the strings


if (str1.length() == str2.length())
{
cout << "Both strings are of equal length." << endl;
}
else if (str1.length() > str2.length())
{
cout << "\"" << str1 << "\" is longer than \"" << str2 << "\"." << endl;
}
else
{
cout << "\"" << str2 << "\" is longer than \"" << str1 << "\"." << endl;
}

return 0;
}

Q25)WAP to display area of circle using inline function.


Code:-
#include <iostream>
using namespace std;

// Define the constant for pi


const float PI = 3.14;

// Inline function to calculate the area of a circle


inline float areaOfCircle(float radius) {
return PI * radius * radius;
}

int main() {
float radius;

// Ask the user for the radius


cout << "Enter the radius of the circle: ";
cin >> radius;
// Calculate and display the area
cout << "The area of the circle is: " << areaOfCircle(radius) << endl;

return 0;
}

Q26) WAP to print Fibonacci of a number using Constructor.


Code:-
#include<iostream>
using namespace std;

class Fibonacci
{
public:
Fibonacci(int n)
{
int a = 0, b = 1, c;
cout << "Fibonacci Series: ";
if (n >= 1) cout << a << " ";
if (n >= 2) cout << b << " ";
for(int i = 3; i <= n; ++i)
{
c = a + b;
cout << c << " ";
a = b;
b = c;
}
cout << endl;
}
};

int main() {
int number;
cout << "Enter the number of terms for Fibonacci Series: ";
cin >> number;
Fibonacci fib(number);
return 0;
}

You might also like