C++ Programs for Basic Operations
C++ Programs for Basic Operations
[Link] a program to read in two integers and perform the following operations on
them: addition, subtraction, multiplication, division, and modulo.
PROGRAM:-
#include<iostream>
using namespace std;
int main() {
char op;
int a,b;
char choice;
do{
cout << "Enter an operator(+,-,/,%,*): ";
cin >>op;
cout << "Enter two operands: ";
cin>>a>>b;
switch(op) {
case '+':
cout << a << " + " << b << " = " << (a+b) << endl;
break;
case '-':
cout << a << " - " << b << " = " << (a-b) << endl;
break;
case '*':
cout << a << " * " << b << " = " << (a*b) << endl;
break;
case '/':
if (b!= 0) {
cout << a << " / " << b << " = " << (a/b) << endl;
} else {
cout << "Error: Division by zero!" << endl;
}
break;
case '%':
if (b!= 0)
cout << a << " % " << b << " = " << (a % b) << endl;
else
cout << "Error: Division by zero!" << endl;
break;
default:
cout << "Error: Invalid operator!" << endl;
break;
}
cout << "Do you want to continue? (yes/no): ";
cin >> choice;
} while (choice == 'y' || choice == 'Y');
return 0;
}
OUTPUT:-
2. Program to determine the integer is odd or even
PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"enter number:";
cin>>n;
if(n%2==0)
cout<<"even number";
else
cout<<"odd number";
}
OUTPUT:-
for(int i=0;i<n;i++)
{
cin>>a[i];
sum=sum+a[i];
}
avg=sum/n;
cout<<"the average of"<<"\t"<<n <<" numbers is "<<avg;
}
OUTPUT:-
5. Write a program to read in two Floating numbers and perform the following
operations on them: addition, subtraction, multiplication, division, and modulo.
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
double num1, num2;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Enter an operator (+, -, *, /, %): ";
cin >> operation;
switch (operation) {
case '+':
cout << "Result: " << num1 + num2 << endl;
break;
case '-':
cout << "Result: " << num1 - num2 << endl;
break;
case '*':
cout << "Result: " << num1 * num2 << endl;
break;
case '/':
if (num2 != 0)
cout << "Result: " << num1 / num2 << endl;
else
cout << "Error: Division by zero is not allowed." << endl;
break;
case '%':
if (static_cast<int>(num2) != 0) {
cout << "Result: " << static_cast<int>(num1) % static_cast<int>(num2) << endl;
}else {
cout << "Error: Modulus by zero is not allowed." << endl;
}
break;
default:
cout << "Error: Invalid operator." << endl;
break;
}
}
OUTPUT:-
OUTPUT:-
[Link] to read a floating-number and round it to the nearest integer using the
floor an ceil functions.
PROGRAM:-
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float num;
cout << "Enter a floating-point number: ";
cin >> num;
int floor_val = floor(num);
int ceil_val = ceil(num);
if (num - floor_val < 0.5) {
cout << "Rounded value: " << floor_val << endl;
} else {
cout << "Rounded value: " << ceil_val << endl;
}
return 0;
}
OUTPUT:-
[Link] Number
PROGRAM:-
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int num,originalNum,remainder,res=0,n=0;
cout<<"enter a number:";
cin>>num;
originalNum=num;
while(originalNum!=0){
originalNum/=10;
n++;
}
originalNum=num;
while(originalNum!=0){
remainder=originalNum%10;
res+=pow(remainder,n);
originalNum/=10;
}
if(res==num)
cout<<num<<" "<<"armstrong number";
else
cout<<num<<"not armstrong number";
return 0;
}
OUTPUT:-
[Link] Number
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int number, sum = 0, temp;
cout << "Enter a number: ";
cin >> number;
temp = number;
while (temp > 0) {
sum += temp % 10;
temp /= 10;
}
if (number % sum == 0)
cout << number << " is a Harshad number." << endl;
else
cout << number << " is not a Harshad number." << endl;
return 0;
}
OUTPUT:-
[Link] Number
PROGRAM:-
#include <iostream>
using namespace std;
int sumOfSquares(int n) {
int sum = 0,digit;
while (n > 0) {
digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
bool isHappyNumber(int n) {
int x = n, y = sumOfSquares(n);
while (y != 1 && x != y) {
x = sumOfSquares(x);
y = sumOfSquares(sumOfSquares(y));
}
return y == 1;
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isHappyNumber(num))
cout << num << " is a happy number!" << endl;
else
cout << num << " is not a happy number." << endl;
return 0;
}
OUTPUT:-
[Link] Number:
PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int n,i,temp,sum=0,digit;
cout<<"enter a number "<<endl;
cin>>n;
temp=n;
while(n>0)
{
digit=n%10;
int fact=1;
for(i=1;i<=digit;i++)
{
fact=fact*i;
}
sum=sum+fact;
n/=10;
}
if(sum==temp)
cout<<"strong Number"<<endl;
else
cout<<"not strong number"<<endl;
return 0;
}
OUTPUT:-
[Link] Number:-
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num % 7 == 0 || num % 10 == 7)
cout << num << " is a Buzz number!" << endl;
else
cout << num << " is not a Buzz number." << endl;
return 0;
}
OUTPUT:-
[Link] Number
PROGRAM:-
#include<iostream>
using namespace std;
int main() {
int num, square, sum = 0;
cout << "Enter a number: ";
cin >> num;
square = num * num;
while (square > 0) {
sum += square % 10;
square /= 10;
}
if (sum == num)
cout << num << " is a neon number!" << endl;
else
cout << num << " is not a neon number." << endl;
return 0;
}
OUTPUT:-
[Link] Number:-
PROGRAM:-
#include<iostream>
using namespace std;
int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0)
sum += i;
}
return sum;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
int sum = sumOfDivisors(number);
if (sum > number)
cout << number << " is an abundant number." << endl;
else
cout << number << " is not an abundant number." << endl;
return 0;
}
OUTPUT:-
[Link] number
PROGRAM:-
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num, originalNum, remainder, n = 0, result = 0;
cout << "Enter a number: ";
cin >> num;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
if (result == num)
cout << num << " is a Narcissistic number." << endl;
else
cout << num << " is not a Narcissistic number." << endl;
return 0;
}
OUTPUT:-
[Link] pattern
1
22
333
4444
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int n;
cout<<”enter limit:”;
cin>>n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << i;
}
cout << endl;
}
return 0;
}
OUTPUT:-
[Link] Pattern
*
**
***
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int rows;
cout<<"enter no of rows";
cin>>rows;
for(int i = 1; i <= rows; ++i) {
for(int j = 1; j <= i; ++j) {
cout << "*";
}
cout << endl;
}
}
OUTPUT:-
OUTPUT:-
cout << "Enter " << n << " elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter the position of the element to delete (1-based index): ";
cin >> pos;
if (pos < 1 || pos > n) {
cout << "Invalid position!" << endl;
} else {
for (int i = pos - 1; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
n--;
cout << "Array after deletion: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
return 0;
}
OUTPUT:-
return 0;
}
OUTPUT:-
[Link] a dynamic 2D (Two dimensional) array using pointers and display the
values
PROGRAM:-
#include<iostream>
using namespace std;
int main() {
int rows, cols;
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> cols;
int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
array[i] = new int[cols];
}
cout << "Enter elements of the array:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << "Element [" << i << "][" << j << "]: ";
cin >> array[i][j];
}
}
cout << "The 2D array is:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << array[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < rows; i++) {
delete[] array[i];
}
delete[] array;
return 0;
}
Output:-
[Link] a c++ program to create a class for a bank account with a constructor and a
destructor
PROGRAM:
#include <iostream>
#include <string>
Using namespace std;
Class BankAccount {
Private:
String accountHolder;
Int accountNumber;
Double balance;
Public:
BankAccount(string holder, int number, double initialBalance) {
accountHolder = holder;
accountNumber = number;
balance = initialBalance;
cout << “Bank account for “ << accountHolder << “ created with balance: “ <<
balance << endl;
}
~BankAccount() {
Cout << “Bank account for “ << accountHolder << “ with account number “ <<
accountNumber << “ is closed.” << endl;
}
Void displayAccountInfo() {
Cout << “Account Holder: “ << accountHolder << endl;
Cout << “Account Number: “ << accountNumber << endl;
Cout << “Balance: $” << balance << endl;
}
Void deposit(double amount) {
Balance += amount;
Cout << “$” << amount << “ deposited. New balance: $” << balance << endl;
}
Void withdraw(double amount) {
If (amount > balance) {
Cout << “Insufficient funds!” << endl;
} else {
Balance -= amount;
Cout << “$” << amount << “ withdrawn. New balance: $” << balance << endl;
}
}
};
Int main() {
BankAccount account(“John Doe”, 123456, 1000.0);
[Link]();
[Link](500);
[Link](200);
Return 0;
}
OUTPUT:
[Link] a c++ program to create a class for a car with a constructor and a destructor
PROGRAM:
#include <iostream>
Using namespace std;
Class Car {
Private:
String make;
String model;
Int year;
Public:
Car(string carMake, string carModel, int carYear) {
Make = carMake;
Model = carModel;
Year = carYear;
Cout << “Car “ << make << “ “ << model << “ (“ << year << “) created.” << endl;
}
~Car() {
Cout << “Car “ << make << “ “ << model << “ (“ << year << “) is destroyed.” <<
endl;
}
Void displayCarInfo() {
Cout << “Make: “ << make << endl;
Cout << “Model: “ << model << endl;
Cout << “Year: “ << year << endl;
}
};
Int main() {
Car car1(“Toyota”, “Corolla”, 2020);
[Link]();
Return 0;
}
OUTPUT:
[Link] a c++ program to create a class for a rectangle with a constructor and a destructor
PROGRAM:
#include <iostream>
Using namespace std;
Class Rectangle {
Private:
Double length;
Double width;
Public:
Rectangle(double l, double w) {
Length = l;
Width = w;
Cout << “Rectangle created with length “ << length << “ and width “ << width <<
endl;
}
Double area() {
Return length * width;
}
~Rectangle() {
Cout << “Rectangle with length “ << length << “ and width “ << width << “
destroyed” << endl;
}
};
Int main() {
Rectangle rect(5.256, 3.5894);
Cout << “Area of the rectangle: “ << [Link]() << endl;
Return 0;
}
OUTPUT:
[Link] a c++ program to create a class for a book with a constructor and a destructor
PROGRAM:
#include <iostream>
#include <string>
Using namespace std;
Class Book {
Private:
String title;
String author;
Int pages;
Public:
// Constructor
Book(string t, string a, int p) {
Title = t;
Author = a;
Pages = p;
Cout << “Book \”” << title << “\” by “ << author << “ with “ << pages << “ pages
created.” << endl;
}
// Destructor
~Book() {
Cout << “Book \”” << title << “\” by “ << author << “ is being destroyed.” << endl;
}
Int main() {
// Creating a book object
Book book1(“1984”, “George Orwell”, 328);
// The destructor will be called automatically when the object goes out of scope
Return 0;
}
OUTPUT:
[Link] a c++ program to create a class for student with a constructor and a destructor
PROGRAM:
#include <iostream>
#include <string>
Using namespace std;
Class Student {
Private:
String name;
Int age;
Public:
// Constructor
Student(string studentName, int studentAge) {
Name = studentName;
Age = studentAge;
Cout << “Student created: “ << name << “, Age: “ << age << endl;
}
// Destructor
~Student() {
Cout << “Destructor called for: “ << name << endl;
}
Int main() {
// Create a Student object
Student student1(“Alice”, 20);
[Link]();
// The destructor will be called automatically when the object goes out of scope
Return 0;
}
OUTPUT :
Exception Handling
[Link] a c++ program to demonstrate to use of the finally block for handling
exceptions
PROGRAM:
#include <iostream>
#include <stdexcept>
class FinallyBlock {
public:
FinallyBlock() {
std::cout << "Resource acquired\n";
}
~FinallyBlock() {
std::cout << "Resource released (Finally block)\n";
}
};
FinallyBlock finally;
if (throwException) {
throw std::runtime_error("An exception occurred!");
}
std::cout << "Function executed without exceptions\n";
}
int main() {
std::cout << "Test with no exception:\n";
try {
testFunction(false);
} catch (const std::exception& e) {
std::cout << "Caught exception: " << [Link]() << '\n';
}
return 0;
}
OUTPUT:
[Link] a c++ program to demonstrate to use of nested try-catch blocks for handling
exceptions
PROGRAM:
#include <iostream>
#include <stdexcept>
int main()
{
try
{
std::cout << "Outer try block\n";
try
{
std::cout << "Inner try block\n";
throw std::runtime_error("Exception from inner try block");
}
catch (const std::runtime_error& e)
{
std::cout << "Caught exception in inner catch block: " << [Link]() << "\n";
throw;
}
}
catch (const std::runtime_error& e)
{
std::cout << "Caught exception in outer catch block: " << [Link]() << "\n";
}
catch (...)
{
std::cout << "Caught an unknown exception in outer catch block\n";
}
std::cout << "Program continues after exception handling\n";
return 0;
}
OUTPUT:
int main() {
int age;
try {
checkAge(age);
} catch (const MyCustomException& e) {
return 0;
}
OUTPUT:
[Link] a base class called Shape with a virtual function area(). Derive two classes
Rectangle and Circle from the base class. Implement the area() function for each
class.
PROGRAM:
#include <iostream>
#include <cmath>
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() {}
};
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return M_PI * radius * radius;
}
};
int main() {
Shape* shapes[2];
shapes[0] = new Rectangle(5.0, 3.0);
shapes[1] = new Circle(4.0);
Operator overloading
int main() {
Counter counter(5);
return 0;
}
OUTPUT :
2. Write a c++ program to overload the + operator to add two variables.
#include <iostream>
class Number {
private:
int value;
public:
Number(int v = 0) : value(v) {}
int main() {
Number num1(10);
Number num2(20);
return 0;
}
OUTPUT :
3. Write a c++ program to overload the << operator to print contents of a
user defined class.
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
public:
// Constructor
Person(const std::string& n, int a) : name(n), age(a) {}
int main() {
Person person("Alice", 30);
return 0;
}
OUTPUT :
4. Write a c++ program to overload the == operator to compare two
objects of a user defined class.
#include <iostream>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
bool operator==(const Person &other) {
return (name == [Link] && age == [Link]);
}
};
int main() {
Person person1("Alice", 25);
Person person2("Alice", 25);
Person person3("Bob", 30);
if (person1 == person2) {
cout << "person1 and person2 are equal." << endl;
} else {
cout << "person1 and person2 are not equal." << endl;
}
if (person1 == person3) {
cout << "person1 and person3 are equal." << endl;
} else {
cout << "person1 and person3 are not equal." << endl;
}
return 0;
}
OUTPUT :
OUTPUT :
OUTPUT :
class FunctionOverloader {
public:
void operator()(int a, int b) {
std::cout << "Sum: " << a + b << std::endl;
}
};
int main() {
FunctionOverloader func;
func(5, 10);
return 0;
}
OUTPUT :
8. write a c++ program to overload the – operator to subtract two
variables.
#include <iostream>
class Subtract {
public:
int value;
Subtract(int v) : value(v) {}
int main() {
Subtract a(10);
Subtract b(5);
Subtract result = a - b;
class Adder {
public:
int add(int a, int b) {
return a + b;
}
int main() {
Adder adder;
return 0;
}
OUTPUT :
10. Write a c++ program to overload the += operator to add two objects of a
user defined class.
#include <iostream>
using namespace std;
class MyClass {
private:
int value;
public:
MyClass(int v = 0) : value(v) {}
MyClass& operator+=(const MyClass& other) {
this->value += [Link];
return *this;
}
void display() const {
cout << "Value: " << value << endl;
}
};
int main() {
MyClass obj1(10), obj2(20);
cout << "Before += operation:" << endl;
[Link]();
[Link]();
obj1 += obj2;
cout << "After += operation:" << endl;
[Link]();
return 0;
}
OUTPUT :
11. write a c++ program to overload a function to find the maximum value
from two integer numbers and two floating point number, and two
characters separately.
#include <iostream>
using namespace std;
int findMax(int a, int b) {
return (a > b) ? a : b;
}
float findMax(float a, float b) {
return (a > b) ? a : b;
}
char findMax(char a, char b) {
return (a > b) ? a : b;
}
int main() {
int int1 = 10, int2 = 20;
float float1 = 10.5f, float2 = 20.3f;
char char1 = 'A', char2 = 'Z';
cout << "Maximum of two integers: " << findMax(int1, int2) << endl;
cout << "Maximum of two floating-point numbers: " << findMax(float1,
float2) << endl;
cout << "Maximum of two characters: " << findMax(char1, char2) << endl;
return 0;
}
OUTPUT :
12. write a c++ program to overload a function to concatenate two strings
and two characters arrays separately.
#include <iostream>
#include <cstring>
using namespace std;
string concatenate(const string& str1, const string& str2) {
return str1 + str2;
}
char* concatenate(const char* str1, const char* str2) {
char* result = new char[strlen(str1) + strlen(str2) + 1];
strcpy(result, str1);
strcat(result, str2);
return result;
}
int main() {
string s1 = "Hello, ";
string s2 = "World!";
cout << "Concatenated std::string: " << concatenate(s1, s2) << endl;
const char* c1 = "Good ";
const char* c2 = "Morning!";
char* concatenatedCharArray = concatenate(c1, c2);
cout << "Concatenated char arrays: " << concatenatedCharArray << endl;
delete[] concatenatedCharArray;
return 0;
}
OUTPUT :
13. write a c++ program to overload a function to calculate the sum of two
matrices and two arrays separately.
#include <iostream>
using namespace std;
void sum(int arr1[], int arr2[], int result[], int size) {
for (int i = 0; i < size; i++) {
result[i] = arr1[i] + arr2[i];
}
}
void sum(int mat1[][3], int mat2[][3], int result[][3], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
int main() {
int arr1[] = {1, 2, 3};
int arr2[] = {4, 5, 6};
int arrResult[3];
int main() {
int intArr[] = {1, 2, 3, 4, 5};
cout << "Integer array: ";
printArray(intArr, 5);
double doubleArr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
cout << "Double array: ";
printArray(doubleArr, 5);
char charArr[] = {'H', 'e', 'l', 'l', 'o'};
cout << "Character array: ";
printArray(charArr, 5);
return 0;
}
OUTPUT :
int main() {
int intNum;
double floatNum;
cout << "Enter an integer number: ";
cin >> intNum;
cout << "Factorial of " << intNum << " is: " << factorial(intNum) << endl;
cout << "Enter a floating-point number: ";
cin >> floatNum;
cout << "Factorial of " << floatNum << " is: " << factorial(floatNum) <<
endl;
return 0;
}
OUTPUT :
16. write a c++ program to overload a function to sort an integer array and
a double array.
#include <iostream>
#include <algorithm>
using namespace std;
void sortArray(int arr[], int size) {
sort(arr, arr + size);
cout << "Sorted integer array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void sortArray(double arr[], int size) {
sort(arr, arr + size);
cout << "Sorted double array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int intArr[] = {5, 2, 9, 1, 5, 6};
int intSize = sizeof(intArr) / sizeof(intArr[0]);
double doubleArr[] = {3.2, 1.5, 4.7, 3.9, 0.9};
int doubleSize = sizeof(doubleArr) / sizeof(doubleArr[0]);
sortArray(intArr, intSize);
sortArray(doubleArr, doubleSize);
return 0;
}
OUTPUT :
int main() {
int intBase, intExponent;
double floatBase;
std::cout << "Enter an integer base and exponent: ";
std::cin >> intBase >> intExponent;
std::cout << intBase << " raised to the power of " << intExponent << " is: " <<
power(intBase, intExponent) << std::endl;
std::cout << "Enter a floating-point base and an integer exponent: ";
std::cin >> floatBase >> intExponent;
std::cout << floatBase << " raised to the power of " << intExponent << " is: " <<
power(floatBase, intExponent) << std::endl;
return 0;
}
OUTPUT :
int main() {
int intNumber;
double floatNumber;
std::cout << "Enter an integer: ";
std::cin >> intNumber;
std::cout << "The absolute value of " << intNumber << " is: " <<
absolute(intNumber) << std::endl;
// Input for floating-point absolute value calculation
std::cout << "Enter a floating-point number: ";
std::cin >> floatNumber;
std::cout << "The absolute value of " << floatNumber << " is: " <<
absolute(floatNumber) << std::endl;
return 0;
}
OUTPUT :
Functions in C++
#include <iostream>
using namespace std;
double celsiusToFahrenheit (double Celsius) { return
(Celsius * 9.0 / 5.0) + 32;
}
double fahrenheitToCelsius (double fahrenheit) { return
(fahrenheit - 32) * 5.0 / 9.0;
}
int main () {
double temp Celsius, temp Fahrenheit; cout
<< "Enter temperature in Celsius: "; cin >>
temp Celsius;
temp Fahrenheit = celsiusToFahrenheit (temp Celsius);
cout << temp Celsius << "°C is equal to " << temp Fahrenheit << "°F" << endl; cout
<< "Enter temperature in Fahrenheit: ";
cin >> temp Fahrenheit;
temp Celsius = fahrenheitToCelsius (temp Fahrenheit);
cout << temp Fahrenheit << "°F is equal to " << temp Celsius << "°C" << endl;
return 0;
}
2. Find the area of a circle using function
#include <iostream>
using namespace std;
double areaOfCircle (double radius) {
const double PI = 3.14159;
return PI * radius * radius;
}
int main() {
double radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
double area = areaOfCircle(radius);
cout << "The area of the circle with radius " << radius << " is " << area << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome (string str) {
int start = 0;
int end = [Link]() - 1;
while (start < end) {
if (str[start] != str[end]) {
return false;
}
start++;
end--;
}
return true;
}
int main() { string
str;
cout << "Enter a string: ";
cin >> str;
if (isPalindrome(str)) {
cout << str << " is a palindrome." << endl;
} else {
cout << str << " is not a palindrome." << endl;
}
return 0;
}
[Link] factorial using function
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello, World!";
string reversed([Link] (), [Link]());
cout << "Reversed string: " << reversed << endl; return
0;
}
#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is: "<<fact<<endl; return 0;
}
OUTPUT:
[Link] a base class called vehicle with data members for make, model, and year. Derive two
classes Car and Truck from the base class. The Car class should have additional data members
for seating capacity and fuel type, while the Truck class should have additional data members
for payload capacity and towing capacity. Write member functions to get and set the data
members for each class
CODE:
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
protected:
string make;
string model;
int year;
public:
Vehicle(string m, string mod, int y) : make(m), model(mod), year(y) {}
string getMake() const { return make; }
string getModel() const { return model; }
int getYear() const { return year; }
void setMake(const string &m) { make = m; }
void setModel(const string &mod) { model = mod; }
void setYear(int y) { year = y; }
};
class Car : public Vehicle {
private:
int seatingCapacity;
string fuelType;
public:
Car(string m, string mod, int y, int capacity, string fuel)
: Vehicle(m, mod, y), seatingCapacity(capacity), fuelType(fuel) {}
int getSeatingCapacity() const { return seatingCapacity; }
string getFuelType() const { return fuelType; }
void setSeatingCapacity(int capacity) { seatingCapacity = capacity; }
void setFuelType(const string &fuel) { fuelType = fuel; }
};
class Truck : public Vehicle {
private:
double payloadCapacity;
double towingCapacity;
public:
Truck(string m, string mod, int y, double payload, double towing)
: Vehicle(m, mod, y), payloadCapacity(payload), towingCapacity(towing) {}
double getPayloadCapacity() const { return payloadCapacity; }
double getTowingCapacity() const { return towingCapacity; }
void setPayloadCapacity(double payload) { payloadCapacity = payload; }
void setTowingCapacity(double towing) { towingCapacity = towing; }
};
OUTPUT:
3. Create a base class called Animal with data members for name, species, and age. Derive
two classes Cat and Dog from the base class. The Cat class should have additional data
members for color and breed, while the Dog class should have additional data members for
weight and breed. Write member functions to get and set the data members for each class.
CODE:
#include <iostream>
#include <string>
using namespace std;
class Animal {
protected:
string name;
string species;
int age;
public:
void setName(const string& n) { name = n; }
void setSpecies(const string& s) { species = s; }
void setAge(int a) { age = a; }
string getName() const { return name; }
string getSpecies() const { return species; }
int getAge() const { return age; }
};
class Cat : public Animal {
private:
string color;
string breed;
public:
void setColor(const string& c) { color = c; }
void setBreed(const string& b) { breed = b; }
public:
void setEngineerData() {
setEmployeeData();
cout << "Enter specialty and hours: ";
cin >> specialty >> hours;
}
OUTPUT:
5. Create a base class called Person with data members for name, age, and gender. Derive two
classes Student and Teacher from the base class. The Student class should have additional data
members for roll number and class, while the Teacher class should have additional data
members for subject and salary. Write member functions to get and set the data members for
each class.
CODE:
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
string gender;
public:
Person() : name(""), age(0), gender("") {}
void setPersonData() {
cout << "Enter name: ";
getline(cin, name);
cout << "Enter age: ";
cin >> age;
cout << "Enter gender: ";
cin >> gender;
[Link]();
}
void getPersonData() const {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
}
};
class Student : public Person {
private:
int rollNumber;
string className;
public:
Student() : rollNumber(0), className("") {}
void setStudentData() {
setPersonData();
cout << "Enter roll number: ";
cin >> rollNumber;
[Link]();
cout << "Enter class name: ";
getline(cin, className);
}
void getStudentData() const {
getPersonData();
cout << "Roll Number: " << rollNumber << endl;
cout << "Class: " << className << endl;
}
};
class Teacher : public Person {
private:
string subject;
double salary;
public:
Teacher() : subject(""), salary(0.0) {}
void setTeacherData() {
setPersonData();
cout << "Enter subject: ";
getline(cin, subject);
cout << "Enter salary: ";
cin >> salary;
[Link]();
}
void getTeacherData() const {
getPersonData();
cout << "Subject: " << subject << endl;
cout << "Salary: $" << salary << endl;
}
};
int main() {
Student student;
cout << "Enter student details:" << endl;
[Link]();
cout << "\nStudent Data:" << endl;
[Link]();
cout << endl;
Teacher teacher;
cout << "Enter teacher details:" << endl;
[Link]();
cout << "\nTeacher Data:" << endl;
[Link]();
return 0;
}
OUTPUT:
6. Write a C++ program to create a pointer to an integer and display its value.
CODE:
#include <iostream>
using namespace std;1
int main() {
int number;
int* ptr = &number;
cout << "Enter an integer value: ";
cin >> number;
cout << "The value of the integer is: " << *ptr << endl;
cout << "The address of the integer is: " << ptr << endl;
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to a float and display its value.
CODE:
#include <iostream>
using namespace std;
int main() {
float num;
cout<<"enter the float num:";
cin>>num;
float* ptr = #
cout << "Value of num: " << *ptr << endl;
cout << "Address of num: " << ptr << endl;
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to a char and display its value.
CODE:
#include <iostream>
using namespace std;
int main() {
char letter;
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to a double and display its value.
CODE:
#include <iostream>
using namespace std;
int main() {
double num;
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to a string and display its value.
CODE:
#include <iostream>
#include <string>
int main() {
string str = "Hello, World!";
string* ptr = &str;
cout << "The value of the string is: " << *ptr << endl;
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to an array of elements and display its value.
CODE:
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
int size = sizeof(arr) / sizeof(arr[0]);
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to an array of character and display its value.
CODE:
#include <iostream>
using namespace std;
int main() {
char arr[] = "Hello";
char* ptr = arr;
cout << "Character Array: ";
while (*ptr != '\0') {
cout << *ptr;
ptr++;
}
cout << endl;
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to an array of floats and display its value.
CODE:
#include <iostream>
using namespace std;
int main() {
float arr[] = {3.14, 2.71, 1.41, 1.73};
float* ptr = arr;
cout << "Float Array: ";
for (int i = 0; i < 4; i++) {
cout << *(ptr + i) << " ";
}
cout << endl;
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to an object and display its attributes.
CODE:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Person p1("John Doe", 30);
Person* ptr = &p1;
ptr->display();
return 0;
}
OUTPUT:
[Link] a C++ program to create a pointer to a function and call the function using the
pointer.
CODE:
#include <iostream>
using namespace std;
void greet() {
cout << "Hello, welcome to function pointers in C++!" << endl;
}
int main() {
void (*funcPtr)();
funcPtr = &greet;
(*funcPtr)();
funcPtr();
return 0;
}
OUTPUT: