0% found this document useful (0 votes)
204 views93 pages

C++ Programs for Basic Operations

Uploaded by

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

C++ Programs for Basic Operations

Uploaded by

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

Operators and Control Structures

[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:-

3. Program to compute the average of three integers


PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int a[5],n,sum=0,avg;
cout<<"enter number of elements in array:";
cin>>n;
cout<<"enter elements in array:";

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:-

[Link] to check two numbers are equal or not


PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"enter a:";
cin>>a;
cout<<"enter b:";
cin>>b;
if(a==b)
cout<<"equal";
else
cout<<"not equal";
}
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:-

[Link] to check the character is a vowel or consonant


PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"enter character:";
cin>>ch;
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
cout<<"vowel";
else
cout<<"consonant";
}
OUTPUT:-

[Link] to check the number is positive, negative or zero


PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"enter n:";
cin>>n;
if(n>0)
cout<<"positive number";
else if(n<0)
cout<<"negative number";
else
cout<<"zero";
}

OUTPUT:-

8. Program to determine which number is greater among two integers


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
if (a > b)
cout << "The greatest number is: " << a << endl;
else
cout << "The greatest number is: " << b << endl;
return 0;
}
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] to swap two numbers using bitwise XOR operator


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Before swap: a = " << a << ", b = " << b << endl;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << "After swap: a = " << a << ", b = " << b << endl;
return 0;
}
OUTPUT:-

[Link] among three numbers using ternary conditional operator


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;
int largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
cout << "The largest number is: " << largest << endl;
return 0;
}
OUTPUT:-
[Link] to check two numbers are equal or not using ternary conditional operator
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
operator to check if numbers are equal
string result = (num1 == num2) ? "Numbers are equal" : "Numbers are not equal";
cout << result << endl;
return 0;
}
OUTPUT:-

[Link] to check the integer is divisible by 3 or not using ternary conditional


operator.
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
string result = (num % 3 == 0) ? "Divisible by 3" : "Not divisible by 3";
cout << result << endl;
return 0;
}
OUTPUT:-

[Link] to print numbers from 1 to 10 using for loop


PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int n,i=1;
cout<<"enter limit:";
cin>>n;
do{
cout<<i<<" "<<endl;
i++;
} while(i<=n);
return 0;
}
OUTPUT:-

[Link] of a number using for loop


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int num, factorial = 1;
cout << "Enter a number: ";
cin >> num;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
cout << "Factorial of " << num << " is: " << factorial << endl;
return 0;
}
OUTPUT:-

[Link] multiplication table using for loop


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Multiplication Table of " << num << ":" << endl;
for (int i = 1; i <= 10; i++) {
cout << num << " x " << i << " = " << num * i << endl;
}
return 0;
}
OUTPUT:-

[Link] series using for loop


PROGRAM:-
#include<iostream>
using namespace std;
int main() {
int n,a=0,b=1,c;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: " << a << ", " << b << ", ";
for (int i = 3; i <= n; i++) {
c = a+b;
cout << c << ", ";
a = b;
b = c;
}
return 0;
}
OUTPUT:-

18. Prime number using for loop


PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int n,i,count=0;
cout<<"enter number:";
cin>>n;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
cout<<"prime number";
else
cout<<" not prime number";
}
OUTPUT:-

19. Check the string is palindrome or not using while loop


PROGRAM:-
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[20];
char revstr[20] = "";
cout << "Enter the string: ";
cin >> str;
int l = strlen(str);
int i = 0;
while (i < l) {
revstr[i] = str[l - i - 1];
i++;
}
revstr[l] = '\0';
if (strcmp(str, revstr) == 0) {
cout << "Palindrome" << endl;
} else {
cout << "Not palindrome" << endl;
}
return 0;
}
OUTPUT:-
20. Sum of all digits using while loop (n=123 output:1+2+3=6)
Program:-
#include<iostream>
using namespace std;
int main() {
int n,i=1,sum = 0, number;
cout << "Enter the number of elements to sum: ";
cin >> n;
while(i<=n)
{
sum=sum+i;
i++;
}
cout << "The sum of the entered numbers is: " << sum << endl;
return 0;
}
Output:-

[Link] of two numbers using do-while loop


Program:-
#include<iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
if (num2 > num1) {
int temp=num1;
num1=num2;
num2=temp;
}
int gcd;
do {
gcd= num1 % num2;
num1=num2;
num2 = gcd;
} while (gcd != 0);
cout << "GCD: "<< num1 << endl;
return 0;
}
OUTPUT:-
22. Check whether the number is perfect or not
PROGRAM:-
#include<iostream>
using namespace std;
int main()
{
int n,i,sum=0;
cout<<"enter n:";
cin>>n;
for(i=1;i<n;i++)
{
if(n%i==0)
sum=sum+i;
}
if(n==sum)
cout<<"perfect number";
else
cout<<"not perfect number";
}
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:-

[Link] pascal triangle pattern nested for loop


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows for Pascal's Triangle: ";
cin >> rows;
for (int i = 0; i < rows; i++) {
int number = 1;
for (int space = 0; space < rows - i - 1; space++) {
cout << " ";
}
for (int j = 0; j <= i; j++) {
cout << number << " ";
number = number * (i - j) / (j + 1);
}
cout << endl;
}
return 0;
}
OUTPUT:-

[Link] diamond pattern with * using nested for loop


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

OUTPUT:-

[Link] to reverse the elements in an array


PROGRAM:-
#include <iostream>
using namespace std;
void reverseArray(int arr[], int size) {
for (int start = 0, end = size - 1; start < end; start++, end--) {
swap(arr[start], arr[end]);
}
}
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int arr[size];
cout << "Enter the elements of the array: ";
for (int i = 0; i < size; i++) cin >> arr[i];
cout << "Original Array: ";
for (int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
reverseArray(arr, size);
cout << "Reversed Array: ";
for (int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
return 0;
}
OUTPUT:-

[Link] to insert an element in an array at a specific position


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int n, element, position;
cout << "Enter the size of the array: ";
cin >> n;
int arr[100];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << "Enter the element to insert: ";
cin >> element;
cout << "Enter the position (0-based index): ";
cin >> position;
if (position < 0 || position > n) {
cout << "Invalid position!" << endl;
return 1;
}
for (int i = n; i > position; i--)
arr[i] = arr[i - 1];
arr[position] = element;
n++;
cout << "Array after insertion: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
OUTPUT:-

[Link] to Delete an element in an array at a specific position


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int n, pos;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];

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:-

[Link] the sum of all elements in an array


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = 0; i < n; i++) {
sum += arr[i];
}
cout << "The sum of all elements in the array is: " << sum << endl;
return 0;
}
OUTPUT:-

[Link] the average of all elements in an array


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
double arr[n], sum = 0.0;
cout << "Enter the elements of the array:" << endl;
for(int i = 0; i < n; i++) {
cin >> arr[i];
sum += arr[i];
}
double average = sum / n;
cout << "The average of the array elements is: " << average << endl;
return 0;
}
OUTPUT:-

[Link] the second largest element in an array


PROGRAM:-
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n,a[5],i;
cout<<"enter number of elements"<<endl;
cin>>n;
cout<<"enter elements into an array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
cout << "Sorted array in ascending order";
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
cout<<"second largest element"<<a[n-2];
return 0;
}
OUTPUT:-

[Link] the number of occurrences of a value in an array


PROGRAM:-
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 2, 4, 5, 2, 4, 5, 2, 3, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
int target = 2;
int counter = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
counter++;
}
}
cout << "Number " << target << " occurs " << counter
<< " times in the array.";
return 0;
}
OUTPUT:-
[Link] Two Array
PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 4, 6, 8};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int mergedSize = size1 + size2;
int mergedArray[mergedSize];
for (int i = 0; i < size1; i++) {
mergedArray[i] = arr1[i];
}
for (int i = 0; i < size2; i++) {
mergedArray[size1 + i] = arr2[i];
}
cout << "Merged Array: ";
for (int i = 0; i < mergedSize; i++) {
cout << mergedArray[i] << " ";
}
return 0;
}
OUTPUT:-

[Link] a dynamic array using pointers and display the values


PROGRAM:-
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int* arr = new int[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "The elements in the array are: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
delete[] arr;

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] Two Matrices


PROGRAM:-
#include<iostream>
using namespace std;
int main() {
int i, j, r, c, k;
cout << "Enter number of rows and columns (for square matrices)" << endl;
cin >> r >> c;
int a[3][3], b[3][3], res[3][3] = {0};
cout << "Enter elements in the first matrix" << endl;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
cin >> a[i][j];
}
}
cout << "Enter elements in the second matrix"<<endl;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
cin >> b[i][j];
}
}
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
res[i][j] = 0;
{
res[i][j] += a[i][j] +b[i][j];
}
}
}
cout << "The addition of the two matrices is:" << endl;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}
OUTPUT:-

[Link] Two Matrices


PROGRAM:-
#include<iostream>
using namespace std;
int main() {
int i, j, r, c, k;
cout << "Enter number of rows and columns (for square matrices)" << endl;
cin >> r >> c;
int a[3][3], b[3][3], res[3][3] = {0};
cout << "Enter elements in the first matrix" << endl;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
cin >> a[i][j];
}
}
cout << "Enter elements in the second matrix" << endl;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
cin >> b[i][j];
}
}
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
res[i][j] = 0;
for (k = 0; k < c; k++) {
res[i][j] += a[i][k] * b[k][j];
}
}
}
cout << "The multiplication of the two matrices is:" << endl;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}
OUTPUT:-

[Link] of diagonals of a matrix.


PROGRAM:-
#include<iostream>
using namespace std;
int main() {
int n, i, j;
cout << "Enter the size of the square matrix (n x n): ";
cin >> n;
int matrix[10][10];
cout << "Enter elements of the matrix:" << endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
int mainDiagonalSum = 0, secondaryDiagonalSum = 0;
for (i = 0; i < n; i++) {
mainDiagonalSum += matrix[i][i];
secondaryDiagonalSum += matrix[i][n - i - 1];
}
cout << "Sum of the main diagonal: " << mainDiagonalSum << endl;
cout << "Sum of the secondary diagonal: " << secondaryDiagonalSum << endl;
return 0;
}
OUTPUT:-

Constructor and destructor

[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;
}

// Method to display book details


Void displayDetails() {
Cout << “Title: “ << title << endl;
Cout << “Author: “ << author << endl;
Cout << “Pages: “ << pages << endl;
}
};

Int main() {
// Creating a book object
Book book1(“1984”, “George Orwell”, 328);

// Display book details


[Link]();

// 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;
}

// Method to display student information


Void displayInfo() {
Cout << “Name: “ << name << “, Age: “ << age << 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";
}
};

void testFunction(bool throwException) {

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';
}

std::cout << "\nTest with exception:\n";


try {
testFunction(true);
} 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:

3. Write a c++ program to demonstrate to use of user-defined exception for handling


custom exception
PROGRAM:
#include <iostream>
#include <exception>
#include <string>

class MyCustomException : public std::exception {


private:
std::string message;
public:

MyCustomException(const std::string& msg) : message(msg) {}

const char* what() const noexcept override {


return message.c_str();
}
};

void checkAge(int age) {


if (age < 18) {

throw MyCustomException("Age is less than 18. Access denied!");


} else {
std::cout << "Access granted.\n";
}
}

int main() {
int age;

std::cout << "Enter your age: ";


std::cin >> age;

try {

checkAge(age);
} catch (const MyCustomException& e) {

std::cout << "Caught exception: " << [Link]() << '\n';


}

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);

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


std::cout << "Area: " << shapes[i]->area() << std::endl;
delete shapes[i];
}
return 0;
}
OUTPUT:

Operator overloading

1. Write a c++ program to overload the ++ operator to increment a


variable.
#include <iostream>
class Counter {
private:
int value;
public:
Counter(int v = 0) : value(v) {}
// Prefix ++ operator overloading
Counter& operator++() {
++value;
return *this;
}

// Postfix ++ operator overloading


Counter operator++(int) {
Counter temp = *this;
++value;
return temp;
}

void display() const {


std::cout << "Value: " << value << std::endl;
}
};

int main() {
Counter counter(5);

std::cout << "Initial state: ";


[Link]();

++counter; // Prefix increment


std::cout << "After prefix increment: ";
[Link]();

counter++; // Postfix increment


std::cout << "After postfix increment: ";
[Link]();

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) {}

Number operator+(const Number& other) {


return Number(value + [Link]);
}

void display() const {


std::cout << "Value: " << value << std::endl;
}
};

int main() {
Number num1(10);
Number num2(20);

std::cout << "First Number: ";


[Link]();

std::cout << "Second Number: ";


[Link]();

Number sum = num1 + num2;


std::cout << "Sum: ";
[Link]();

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) {}

// Friend function to overload the << operator


friend std::ostream& operator<<(std::ostream& os, const Person& person) {
os << "Name: " << [Link] << ", Age: " << [Link];
return os;
}
};

int main() {
Person person("Alice", 30);

std::cout << "Person Details: " << person << std::endl;

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 :

5. Write a c++ program to overload the * operator to multiply two


matrices.
#include <iostream>
using namespace std;
class Matrix {
private:
int mat[2][2];
public:
Matrix(int a, int b, int c, int d) {
mat[0][0] = a; mat[0][1] = b;
mat[1][0] = c; mat[1][1] = d;
}
Matrix operator*(const Matrix &other) {
return Matrix(
mat[0][0] * [Link][0][0] + mat[0][1] * [Link][1][0],
mat[0][0] * [Link][0][1] + mat[0][1] * [Link][1][1],
mat[1][0] * [Link][0][0] + mat[1][1] * [Link][1][0],
mat[1][0] * [Link][0][1] + mat[1][1] * [Link][1][1]
);
}
void display() {
cout << mat[0][0] << " " << mat[0][1] << endl;
cout << mat[1][0] << " " << mat[1][1] << endl;
}
};
int main() {
Matrix mat1(1, 2, 3, 4);
Matrix mat2(5, 6, 7, 8);
Matrix result = mat1 * mat2;
cout << "Result of multiplication:" << endl;
[Link]();
return 0;
}

OUTPUT :

6. write a c++ program to overload the [] operator to access the elements in


an array using index values.
#include <iostream>
using namespace std;
class Array {
private:
int arr[5];
public:
Array() {
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
}
int& operator[](int index) {
if (index >= 0 && index < 5) {
return arr[index];
} else {
cout << "Index out of bounds!" << endl;
exit(1);
}
}
};
int main() {
Array myArray;
cout << "Element at index 0: " << myArray[0] << endl;
cout << "Element at index 2: " << myArray[2] << endl;
myArray[2] = 10;
cout << "Modified element at index 2: " << myArray[2] << endl;
return 0;
}

OUTPUT :

7. Write a c++ program to overload the () to call a function with


arguments.
#include <iostream>

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) {}

Subtract operator-(const Subtract& other) {


return Subtract(this->value - [Link]);
}
};

int main() {
Subtract a(10);
Subtract b(5);
Subtract result = a - b;

std::cout << "Result of subtraction: " << [Link] << std::endl;


return 0;
}
OUTPUT :
9. write a c++ program to overload a function to add two integer numbers
and two floating point number separately.
#include <iostream>
using namespace std;

class Adder {
public:
int add(int a, int b) {
return a + b;
}

float add(float a, float b) {


return a + b;
}
};

int main() {
Adder adder;

int intResult = [Link](5, 10);


float floatResult = [Link](5.5f, 10.5f);

cout << "Sum of integers: " << intResult << endl;


cout << "Sum of floating point numbers: " << floatResult << endl;

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];

sum(arr1, arr2, arrResult, 3);

cout << "Sum of 1D arrays: ";


for (int i = 0; i < 3; i++) {
cout << arrResult[i] << " ";
}
cout << endl;
int mat1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int mat2[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int matResult[3][3];

sum(mat1, mat2, matResult, 3, 3);

cout << "Sum of 2D matrices: " << endl;


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matResult[i][j] << " ";
}
cout << endl;
}
return 0;
}
OUTPUT :

14. write a c++ program to overload a function to print an integer array, a


double array and a character array separately.
#include <iostream>
using namespace std;
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void printArray(double arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void printArray(char arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

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 :

15. write a c++ program to overload a function to find a factorial of an


integer number and factorial of a floating-point number separately.
#include <iostream>
#include <cmath>

using namespace std;


int factorial(int n) {
if (n < 0)
return -1;
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
double factorial(double n) {
if (n < 0.0)
return -1.0;
return tgamma(n + 1.0);
}

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 :

[Link] a c++ program to overload a function to calculate the power of an integer


number and power of a floating-point number separately.
#include <iostream>
#include <cmath>
int power(int base, int exponent) {
return static_cast<int>(std::pow(base, exponent));
}
double power(double base, int exponent) {
return std::pow(base, exponent);
}

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 :

[Link] a c++ program to overload a function to find an absolute value of


an integer number and absolute value of a floating-point number
separately.
#include <iostream>
#include <cmath>
int absolute(int number) {
return (number < 0) ? -number : number;
}
double absolute(double number) {
return std::fabs(number); // Use fabs from <cmath>
}

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++

1. Convert Celsius and Fahrenheit using function

#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;
}

3. Check whether the string is palindrome or not

#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;
}

5. Find prime number using function

#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;
}

6. Find GCD of two number using function


#include <iostream>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
int result = gcd(num1, num2);
std::cout << "GCD of " << num1 << " and " << num2 << " is: " << result << std::endl;
return 0;
}
7. Function to count the no of elements in a string.
#include <iostream>
#include <string>
int countCharacters(const std::string& str) { int
count = 0;
for (char c : str) {
count++;
}
return count;
}
int main() {
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input);
int customCount = countCharacters(input); int
builtInCount = [Link]();
std::cout << "Number of characters (custom function): " << customCount << std::endl;
std::cout << "Number of characters (built-in method): " << builtInCount <<
std::endl;
return 0;
}
8. Find minimum and maximum element in an array using function.
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"input length of array = ";
cin>>n;
int array[n];
for(int i=0; i<n;i++)
{
int a;
cout<<"input element "<<i+1<<" = ";
cin>>a;
}
int max=array[0];
int min=array[0];
for(int i=0; i<n;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
}
9. Find the reverse of a string using function
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello, World!";
reverse([Link](), [Link]());
cout << "Reversed string: " << str << endl;
return 0;
}

Inheritance and pointers


TEAM 5
[Link] a base class called Shape with data members for height and width. Derive two classes
Rectangle and Triangle from the base class. Write member functions to calculate the area and
perimeter of each class.
CODE:
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
protected:
double height;
double width;
public:
Shape(double h = 0, double w = 0) : height(h), width(w) {}
virtual double area() const = 0;
virtual double perimeter() const = 0;
};
class Rectangle : public Shape {
public:
Rectangle(double h, double w) : Shape(h, w) {}
double area() const override {
return height * width;
}
double perimeter() const override {
return 2 * (height + width);
}
};
class Triangle : public Shape {
public:
Triangle(double h, double w) : Shape(h, w) {}
double area() const override {
return 0.5 * height * width;
}

double perimeter() const override {


double hypotenuse = std::sqrt(height * height + width * width);
return height + width + hypotenuse;
}
};
int main() {
Rectangle rect(5, 10);
cout << "Rectangle Area: " << [Link]() << endl;
cout << "Rectangle Perimeter: " << [Link]() << endl;
Triangle tri(5, 10);
cout << "Triangle Area: " << [Link]() << endl;
cout << "Triangle Perimeter: " << [Link]() << 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; }

string getColor() const { return color; }


string getBreed() const { return breed; }
};
class Dog : public Animal {
private:
double weight;
string breed;
public:
void setWeight(double w) { weight = w; }
void setBreed(const string& b) { breed = b; }

double getWeight() const { return weight; }


string getBreed() const { return breed; }
};
int main() {
Cat myCat;
Dog myDog;
string catName, catSpecies, catColor, catBreed;
int catAge;

cout << "Enter cat's name: ";


getline(cin, catName);
[Link](catName);

cout << "Enter cat's species: ";


getline(cin, catSpecies);
[Link](catSpecies);

cout << "Enter cat's age: ";


cin >> catAge;
[Link](catAge);
[Link]();

cout << "Enter cat's color: ";


getline(cin, catColor);
[Link](catColor);

cout << "Enter cat's breed: ";


getline(cin, catBreed);
[Link](catBreed);

string dogName, dogSpecies, dogBreed;


double dogWeight;
int dogAge;

cout << "Enter dog's name: ";


getline(cin, dogName);
[Link](dogName);

cout << "Enter dog's species: ";


getline(cin, dogSpecies);
[Link](dogSpecies);

cout << "Enter dog's age: ";


cin >> dogAge;
[Link](dogAge);
[Link]();

cout << "Enter dog's weight: ";


cin >> dogWeight;
[Link](dogWeight);
[Link]();
cout << "Enter dog's breed: ";
getline(cin, dogBreed);
[Link](dogBreed);
cout << "\nCat Information:\n";
cout << "Name: " << [Link]() << "\n";
cout << "Species: " << [Link]() << "\n";
cout << "Age: " << [Link]() << "\n";
cout << "Color: " << [Link]() << "\n";
cout << "Breed: " << [Link]() << "\n";
cout << "\nDog Information:\n";
cout << "Name: " << [Link]() << "\n";
cout << "Species: " << [Link]() << "\n";
cout << "Age: " << [Link]() << "\n";
cout << "Weight: " << [Link]() << " kg\n";
cout << "Breed: " << [Link]() << "\n";
return 0;
}
Output:
4. Create a base class called Employee with data members for name, d, and salary Derive two
classes Manager and Engineer from the base class. The Manager class should have additional
data members for department and bonus, while theEngineer class should have additional data
members for specialty and hours. Write member functions to get and set the data members for
each class
#include <iostream>
#include <string>

using namespace std;


class Employee {
protected:
string name;
int id;
float salary;
public:
void setEmployeeData() {
cout << "Enter name, ID, and salary: ";
cin >> name >> id >> salary;
}
void getEmployeeData() const {
cout << "Name: " << name << ", ID: " << id << ", Salary: " << salary << endl;
}
};
class Manager : public Employee {
private:
string department;
float bonus;
public:
void setManagerData() {
setEmployeeData();
cout << "Enter department and bonus: ";
cin >> department >> bonus;
}
void getManagerData() const {
getEmployeeData();
cout << "Department: " << department << ", Bonus: " << bonus << endl;
}
};

// Derived class: Engineer


class Engineer : public Employee {
private:
string specialty;
int hours;

public:
void setEngineerData() {
setEmployeeData();
cout << "Enter specialty and hours: ";
cin >> specialty >> hours;
}

void getEngineerData() const {


getEmployeeData();
cout << "Specialty: " << specialty << ", Hours: " << hours << endl;
}
};
int main() {
Manager m;
Engineer e;
cout << "Manager:\n";
[Link]();
[Link]();
cout << "\nEngineer:\n";
[Link]();
[Link]();
return 0;
}

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 = &num;
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;

cout << "Enter a character: ";


cin >> letter;

char* ptr = &letter;

cout << "Value of letter: " << *ptr << endl;


cout << "Address of letter: " << static_cast<void*>(ptr) << endl;

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;

cout << "Enter a double value: ";


cin >> num;

double* ptr = &num;

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 string and display its value.
CODE:
#include <iostream>
#include <string>

using namespace std;

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>

using namespace std;

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
int size = sizeof(arr) / sizeof(arr[0]);

cout << "Array elements using pointer:" << endl;


for (int i = 0; i < size; i++) {
cout << "Element " << i << ": " << *(ptr + i) << endl;
}

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:

You might also like