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

C++ Problems

The document contains a collection of C++ programming examples, each demonstrating a specific concept or problem-solving technique. Programs include printing 'Hello World!', adding variables, finding maximum numbers in arrays, checking for prime numbers, and implementing algorithms like bubble sort and Fibonacci series. Each program is accompanied by code snippets and expected outputs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C++ Problems

The document contains a collection of C++ programming examples, each demonstrating a specific concept or problem-solving technique. Programs include printing 'Hello World!', adding variables, finding maximum numbers in arrays, checking for prime numbers, and implementing algorithms like bubble sort and Fibonacci series. Each program is accompanied by code snippets and expected outputs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

C++ PROGRAMS BY MUHAMMAD UMAIR

Program #1
The beginning of any programming language deals with your first “Hello World!” Can
you print this “Hello World!” in C++?
Answer: Main function is always executed first
CODE: OUTPUT:
#include <iostream>
using namespace std; Hello World

int main() {
cout << "Hello World!";
return 0;
}

Program #2
Can you add two variables in C++?
Answer: Declare two variables and use ‘+’ operator
CODE: OUTPUT:
#include <iostream>
using namespace std; 8

int main() {
int a = 2;
int b = 6;
cout << a + b;
return 0;
}

Program #3
Find the maximum number in an array of integers.
Answer: Define a maximum variable which will store the maximum in each iteration.
CODE: OUTPUT:
#include <iostream>
using namespace std; 5

int main() {
int arr[5] = {1, 2, 5, 4, 3};
int max = 0;
for (int i = 0; i < 5; i++) {
if (max < arr[i])
max = arr[i];
}
cout << max << endl;
return 0;
}
Program #4
Can you find out the sum of the digits of a number?
Answer: run a loop until the number is zero and keep adding each digit.
CODE: OUTPUT:
#include
using namespace std; 10
int main() {
int number = 145;
int sum = 0;
while(number!=0){
int digit = number%10;
number = number/10;
sum += digit;
}
cout<<sum<<endl;
return 0;
}

Program #5
Try to swap two numbers with a third variable.
Answer: store one number is a temporary variable.
CODE: OUTPUT:
#include <iostream>
using namespace std; 145 200
200 145
int main() {
int number1 = 145;
int number2 = 200;
cout << number1 << " " << number2 << endl;
int temp = number1;
number1 = number2;
number2 = temp;
cout << number1 << " " << number2 << endl;
return 0;
}

Program #6
Can you now swap two numbers without a third variable?
Answer: use the difference and sum operation.
CODE: OUTPUT:
#include <iostream>
using namespace std; 145 200
int main() { 200 145
int number1 = 145, number2 = 200;
cout << number1 << " " << number2 << endl;
number1 = number1 + number2;
number2 = number1 - number2;
number1 = number1 - number2;
cout << number1 << " " << number2 << endl;
return 0;
}
Program #7
Can you check whether a number is prime or not?
Answer: simple check whether all number below it can divide it or not.
CODE: OUTPUT:
#include <iostream>
using namespace std; prime
int main() {
int a = 23;
int b = 2;
bool prime = true;
while (b != a) {
if (a % b == 0) {
prime = false;
break;
}
b++;
}
if (prime)
cout << "prime";
else
cout << "not prime";
return 0;
}

Program #8
Write a program to find the reverse of a number.
Answer: try to get each digit and multiply with its corresponding power of 10.
CODE: OUTPUT:
#include <iostream>
using namespace std; 3221

int main() {
int a = 1223;
int res = 0;

while (a != 0) {
int dig = a % 10;
res = res * 10 + dig;
a = a / 10;
}

cout << res;

return 0;
}
Program #9
Now when you know to reverse a number, can you try to check whether a number is a
palindrome or not?
Answer: Palindrome is a number which when reversed we get the same value.
CODE: OUTPUT:
#include <iostream>
using namespace std; Palindrome

int reverse(int a) {
int res = 0;
while (a != 0) {
int dig = a % 10;
res = res * 10 + dig;
a = a / 10;
}
return res;
}

int main() {
int a = 1221;
int b = reverse(a);

if (a == b)
cout << "Palindrome";
else
cout << "Not palindrome";

return 0;
}

Program #10
Find the factorial of a number.
Answer: Factorial of n = 12345…(n-1) n, multiply all number below given numbers.
CODE: OUTPUT:
#include <iostream>
using namespace std; 120

int factorial(int n) {
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}

int main() {
int a = 5;
cout << factorial(a) << endl;
return 0;
}
Program #11
Write a C++ program to check whether a number is Armstrong number or not.
Answer: An Armstrong number is a number that is equal to the sum of cubes of its digits. Extract
each digit and add their cubes.
CODE: OUTPUT:
#include <iostream>
using namespace std; Armstrong Number

int sumofcubes(int n) {
int res = 0;
while (n != 0) {
int dig = n % 10;
res = res + (dig * dig * dig);
n = n / 10;
}
return res;
}

int main() {
int a = 371;

if (a == sumofcubes(a))
cout << "Armstrong Number";
else
cout << "Not Armstrong Number";

return 0;
}

Program #12
Can you convert a decimal number to binary?
Answer: Divide by 2 and store the remainders in reverse order.
CODE: OUTPUT:
#include <iostream>
using namespace std; 10111

int main() {
int a[10], n, i;
n = 23;

for (i = 0; n > 0; i++) {


a[i] = n % 2;
n = n / 2;
}

for (i = i - 1; i >= 0; i--)


cout << a[i];

return 0;
}
Program #13
Now can you revert back the original number from binary? Convert Binary to Decimal
number.
Answer: Multiply each digit by position power of 2, 10 = 121+020.
CODE: OUTPUT:
#include <iostream>
#include <cmath> 23

using namespace std;

int convertBinaryToDecimal(int n) {
int decimalNumber = 0, i = 0, dig;
while (n != 0) {
dig = n % 10;
n /= 10;
decimalNumber += dig * pow(2, i);
++i;
}
return decimalNumber;
}

int main() {
int n = 10111;
cout << convertBinaryToDecimal(n) << endl;
return 0;
}

Program #14
Do you know about Fibonacci Series? The series following 1,1,2,3,5,8…, can you try to
print the series upto n elements?
Answer: Fibonacci series can be given by Fn=Fn-1+F(n-2), where F1=1, F2=1. We need to keep
track of previous two elements and when we get our next element change the value of previous
variables to new ones
CODE: OUTPUT:
#include <iostream>
using namespace std; 1 1 2 3 5 8 13 21 34 55

void fib(int n) {
if (n == 1) {
cout << 1;
return;
}
if (n == 2) {
cout << "1 1 ";
return;
}
int a = 1, b = 1;
cout << "1 1 ";
for (int i = 3; i <= n; i++) {
int c = a + b;
cout << c << " ";
a = b;
b = c;
}
}
int main() {
int n = 10; // You can change this to any positive integer
fib(n);
return 0;
}

Program #15
Write a C++ program to count all the vowels in a given string.
Answer: Iterate through the string and increase count every time we find a vowel.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter a string: Hello World
Number of vowels in the given string: 3
int main() {
string inputString;
cout << "Enter a string: ";
getline(cin, inputString);

int vowelCount = 0;

for (char ch : inputString) {


char lowercaseChar = tolower(ch);
if (lowercaseChar == 'a' || lowercaseChar == 'e' ||
lowercaseChar == 'i' || lowercaseChar == 'o' ||
lowercaseChar == 'u') {
vowelCount++;
}
}

cout << "Number of vowels in the given string: " <<


vowelCount << endl;

return 0;
}

Program #16
Can you search for an element in a given array? Try to print that number if present
else print -1.
Answer: Can you search for an element in a given array? Try to print that number if present else
print -1.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter the size of the array: 5
Enter the elements of the array:
int main() { 25793
int n; // Size of the array
Enter the number to search: 7
cout << "Enter the size of the array: ";
cin >> n; Number found at index 2

int arr[n]; // Declare an array of size n

cout << "Enter the elements of the array:" << endl;


for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int searchNumber;
cout << "Enter the number to search: ";
cin >> searchNumber;

bool found = false;

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


if (arr[i] == searchNumber) {
cout << "Number found at index " << i << endl;
found = true;
break;
}
}

if (!found) {
cout << "Number not found in the array. -1" << endl;
}

return 0;
}

Program #17
Find GCD of two number.
Answer: GCD of two numbers is the greatest number which is a factor of both numbers and
divides both numbers.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter the first number: 24
Enter the second number: 36
// Function to calculate GCD using Euclidean algorithm GCD of 24 and 36 is: 12
int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

int main() {
int num1, num2;

cout << "Enter the first number: ";


cin >> num1;

cout << "Enter the second number: ";


cin >> num2;

int gcd = findGCD(num1, num2);

cout << "GCD of " << num1 << " and " << num2 << " is:
" << gcd << endl;

return 0;
}
Program #18
Print out the Fibonacci Triangle.
Answer: Fibonacci triangle is given by following –
1
11
112
1123
1 1 2 3 5 and so on
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter the number of rows for Fibonacci Triangle: 5
0
int main() { 11
int n;
011
cout << "Enter the number of rows for Fibonacci Triangle:
"; 1011
cin >> n; 01011

int a = 0, b = 1, c;

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


a = 0;
b = 1;
for (int j = 1; j <= i; j++) {
cout << a << " ";
c = a + b;
a = b;
b = c;
}
cout << endl;
}

return 0;
}

Program #19
Check if a year is a leap year or not.
Answer: A year is a leap year if:
The year is multiple of 400.
The year is multiple of 4 and not multiple of 100.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter a year: 2020
2020 is a leap year!
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400
== 0);
}

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

if (isLeapYear(year)) {
cout << year << " is a leap year!" << endl;
} else {
cout << year << " is not a leap year." << endl;
}

return 0;
}

Program #20
Given an array of integers, sort the given array in ascending order.
Answer: We will use a simple algorithm here. It is called Bubble Sort. The concept here is very
simple – we just need to swap the bigger element with the end of the loop elements. This will
bubble out the bigger elements to the end of the array and hence we will have smaller elements at
the left of the array and bigger elements to the right of the array.
CODE: OUTPUT:
#include <iostream>
using namespace std; 12345

void swap(int *a, int *b)


{
int temp = *a;
*a = *b;
*b = temp;
}

void bubbleSort(int arr[], int n)


{
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

int main() {
int arr[5] = {4, 3, 5, 1, 2};
int n = sizeof(arr) / sizeof(arr[0]);

bubbleSort(arr, n);

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


cout << arr[i] << " ";
cout << endl;

return 0;
}
Program #21
Write a program for Adding two numbers in C++.
Answer: To Add two numbers in C++ we will read two numbers a and b from the user then
perform add operation to add a and b together to print the addition of two numbers in C++.
CODE: OUTPUT:
#include <iostream>
using namespace std; Input: 2 5
Output: 7
int main() {
int a;
int b;

cin >> a >> b;


cout << a + b;

return 0;
}

Program #22
C++ program to Check if a number is even or odd.
Answer: TO Check if a given number is even or odd in C++, we simply divide the given number by
2, if the remainder is 0 then it is even otherwise odd.
CODE: OUTPUT:
#include <iostream>
using namespace std; Input: 8
int main() { Output: even
int a ;
cin>>a;
if(a%2 == 0) // if remainder is zero then even number
cout<<”even”;
else
cout<<”odd”;
return 0;
}

Program #23
Write a C++ program to find the largest number among three numbers.
Answer: A number will be largest if number is greater than both the other numbers.
CODE: OUTPUT:
#include <iostream>
using namespace std; Input: 1 2 3
int main() { Largest number: 3
float a, b, c;
cin >> a >> b >> c;
if(a >= b && a >= c)
cout << "Largest number: " << a;
if(b >= a && b >= c)
cout << "Largest number: " << b;
if(c >= a && c >= b)
cout << "Largest number: " << c;
return 0;
}
Program #25
Write a C++ Program to Find the sum of all the natural numbers from 1 to n.
Answer: To find the sum of all the natural number from 1 to n in C++, We have two methods, one
is by iterating from 1 to n and adding them up while the other way is using the summation formula

CODE: OUTPUT:
summation of i from 1 to n=n(n+1)/2=1+2+3+4+..+(n-1)+n
#include <iostream> Input: 5
using namespace std; Output: 15
int main()
{
int n, sum = 0;
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
// or sum = n*(n+1)/2;
cout << sum;
return 0;
}

Program #26
Write a C++ program to Compute the power a given number to a given power.
Answer: To compute the power of a given number in C++, We initialize a variable result to 1.
Then, we’ll use a while loop to multiply the result by base for power number of times.
CODE: OUTPUT:
3^3=3*3*3=27
#include <iostream> Input: 3 3
using namespace std; Output: 27
int main()
{
int power;
float base, result = 1;
cin >> base >>power;
while (power != 0) {
result *= base;
power--;
}
cout << result;
return 0;
}

Program #27
Write a C++ program to Compute the power a given number to a given power.
Answer: To compute the power of a given number in C++, We initialize a variable result to 1.
Then, we’ll use a while loop to multiply the result by base for power number of times.
CODE: OUTPUT:
average= summation〖arr[i]〗/n
#include <iostream> Input: 3
using namespace std; 145
int main() Output: 3.33333
{
int n;
cin>>n;
int arr[n];
float sum = 0.0;
for(int i = 0;i<n;i++)
cin>>arr[i];
for(int i = 0;i<n;i++)
sum += arr[i];
cout<<(float)(sum/(float)n);
return 0;
}

Program #28
Write a program to find the GCD of two numbers in C++.
Answer: GCD is the greatest common divisor of the two numbers.
CODE: OUTPUT:
#include <iostream>
using namespace std; Input: 35 25
int gcd(int a,int b){ Output: 5
if(b == 0)
return a;
return gcd(b,a%b);
}
int main() {
int a ,b ;
cin>>a>>b;
cout<<gcd(a,b);
return 0;
}

Program #29
Write a function to find the length of a string in C++.
Answer: To find the length of a string in C++, we will Iterate through the string and increase count
by 1 till we reach the end of the string.
CODE: OUTPUT:
#include <iostream>
using namespace std; Input: abcde
int main() Output: 5
{
string str;
cin>>str;
int count = 0;
for(int i = 0;str[i];i++) // till the string character is null
count++;
cout<<count;
}
Program #30
Write a program to print the ASCII value of a character.
Answer:
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter a character: A
int main() { ASCII value of 'A' is: 65
char character;

cout << "Enter a character: ";


cin >> character;
cout << "ASCII value of '" << character << "' is: " << int(character) << endl;
return 0;
}

Program #31
Write a program to take the marks obtained by a student in five different subjects
through the keyboard, find out the aggregate marks and percentage marks obtained
by the student. Assume that the maximum marks that can be obtained by a student in
each subject is 100.
CODE: OUTPUT:
#include <iostream>
Enter marks for five subjects:
using namespace std; Subject 1: 75
Subject 2: 85
int main() {
Subject 3: 90
int marks[5];
int totalMarks = 500; Subject 4: 92
Subject 5: 88
cout << "Enter marks for five subjects:\n";
Aggregate Marks: 430/500
for (int i = 0; i < 5; ++i) { Percentage Marks: 86%
cout << "Subject " << i + 1 << ": ";
cin >> marks[i];

if (marks[i] < 0 || marks[i] > 100) {


cout << "Invalid marks! Marks should be between 0 and 100.\n";
return 1;
}
}

int aggregateMarks = 0;

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


aggregateMarks += marks[i];
}

float percentage = float(aggregateMarks) / totalMarks * 100;

cout << "\nAggregate Marks: " << aggregateMarks << "/" << totalMarks << endl;
cout << "Percentage Marks: " << percentage << "%" << endl;

return 0;
}
Program #32
Write a program to take the marks obtained by a student in five different subjects
through the keyboard, find out the aggregate marks and percentage marks obtained
by the student. Assume that the maximum marks that can be obtained by a student in
each subject is 100.(without array)
CODE: OUTPUT:
#include <iostream>
Enter marks for five subjects:
using namespace std; Subject 1: 75
Subject 2: 85
int main() {
Subject 3: 90
int marks1, marks2, marks3, marks4, marks5;
int totalMarks = 500; Subject 4: 92
Subject 5: 88
cout << "Enter marks for five subjects:\n";
Aggregate Marks: 430/500
cout << "Subject 1: "; Percentage Marks: 86%
cin >> marks1;
if (marks1 < 0 || marks1 > 100) {
cout << "Invalid marks! Marks should be between 0 and 100.\n";
return 1;
}

cout << "Subject 2: ";


cin >> marks2;
if (marks2 < 0 || marks2 > 100) {
cout << "Invalid marks! Marks should be between 0 and 100.\n";
return 1;
}

cout << "Subject 3: ";


cin >> marks3;
if (marks3 < 0 || marks3 > 100) {
cout << "Invalid marks! Marks should be between 0 and 100.\n";
return 1;
}

cout << "Subject 4: ";


cin >> marks4;
if (marks4 < 0 || marks4 > 100) {
cout << "Invalid marks! Marks should be between 0 and 100.\n";
return 1;
}

cout << "Subject 5: ";


cin >> marks5;
if (marks5 < 0 || marks5 > 100) {
cout << "Invalid marks! Marks should be between 0 and 100.\n";
return 1;
}

int aggregateMarks = marks1 + marks2 + marks3 + marks4 + marks5;


float percentage = float(aggregateMarks) / totalMarks * 100;

cout << "\nAggregate Marks: " << aggregateMarks << "/" << totalMarks << endl;
cout << "Percentage Marks: " << percentage << "%" << endl;

return 0;
}
Program #33
Write a program to calculate the arithmetic mean of 5 numbers.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter five numbers:
int main() { 10 15 20 25 30
float num1, num2, num3, num4, num5;
cout << "Enter five numbers:\n";
Arithmetic Mean: 20
cin >> num1 >> num2 >> num3 >> num4 >> num5;
float mean = (num1 + num2 + num3 + num4 + num5) / 5;
cout << "Arithmetic Mean: " << mean << endl;
return 0;
}

Program #34
Write a program to find the square root of a number.
CODE: OUTPUT:
#include <iostream>
#include <cmath> Enter a number: 25
using namespace std;
int main() { Square Root: 5
double number;
cout << "Enter a number: ";
cin >> number;
if (number < 0) {
cout << "Cannot calculate square root of a negative number.\n";
} else {
double squareRoot = sqrt(number);
cout << "Square Root: " << squareRoot << endl;
}
return 0;
}

Program #35
Write a program to find SIN, COS, sec, TAN, and COSEC of an angle.
CODE: OUTPUT:
#include <iostream>
#include <cmath> Enter the angle in degrees: 45

using namespace std; SIN: 0.707107


COS: 0.707107
int main() {
double angleInDegrees;
TAN: 1
SEC: 1.41421
cout << "Enter the angle in degrees: "; COSEC: 1.41421
cin >> angleInDegrees;

double angleInRadians = angleInDegrees * M_PI / 180.0;

double sinValue = sin(angleInRadians);


double cosValue = cos(angleInRadians);
double tanValue = tan(angleInRadians);

if (cosValue == 0) {
cout << "Cannot calculate sec and cosec, as cos(angle) is zero.\n";
} else {
cout << "SIN: " << sinValue << endl;
cout << "COS: " << cosValue << endl;
cout << "TAN: " << tanValue << endl;
cout << "SEC: " << 1 / cosValue << endl;
cout << "COSEC: " << 1 / sinValue << endl;
}

return 0;
}

Program #36
Write a program to find quotient and remainder.
CODE: OUTPUT:
#include <iostream>
Enter dividend: 25
using namespace std; Enter divisor: 4
int main() {
Quotient: 6
int dividend, divisor;
Remainder: 1
cout << "Enter dividend: ";
cin >> dividend;

cout << "Enter divisor: ";


cin >> divisor;

if (divisor == 0) {
cout << "Cannot divide by zero.\n";
} else {
int quotient = dividend / divisor;
int remainder = dividend % divisor;

cout << "Quotient: " << quotient << endl;


cout << "Remainder: " << remainder << endl;
}

return 0;
}

Program #37
Write a program to print the sum of digits of a three-digit number.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter a three-digit number: 456
int main() {
int number; Sum of digits: 15
cout << "Enter a three-digit number: ";
cin >> number;
if (number < 100 || number > 999) {
cout << "Invalid input. Please enter a three-digit number.\n";
} else {
int digit1 = number % 10;
int digit2 = (number / 10) % 10;
int digit3 = (number / 100) % 10;
int sumOfDigits = digit1 + digit2 + digit3;
cout << "Sum of digits: " << sumOfDigits << endl;
}
return 0;
}
Program #38
If a four-digit number is input through the keyboard, write a program to obtain the
sum of the first and last digit of this number.
CODE: OUTPUT:
#include <iostream>
Enter a four-digit number: 4567
using namespace std; Sum of the first and last digit: 11
int main() {
int fourDigitNumber;

cout << "Enter a four-digit number: ";


cin >> fourDigitNumber;

if (fourDigitNumber < 1000 || fourDigitNumber > 9999) {


cout << "Invalid input. Please enter a four-digit number.\n";
} else {
int firstDigit = fourDigitNumber / 1000;
int lastDigit = fourDigitNumber % 10;

int sumOfFirstAndLast = firstDigit + lastDigit;

cout << "Sum of the first and last digit: " << sumOfFirstAndLast << endl;
}

return 0;
}

Program #39
Write a program that take a 4-digit number form user (i.e., 4185) and show sum of
cubes of all digits in the number. (hint: Sum = 43+13+83+53)
CODE: OUTPUT:
#include <iostream>
Enter a four-digit number: 4185
using namespace std; Sum of cubes of digits: 1193
int main() {
int fourDigitNumber;

cout << "Enter a four-digit number: ";


cin >> fourDigitNumber;

if (fourDigitNumber < 1000 || fourDigitNumber > 9999) {


cout << "Invalid input. Please enter a four-digit number.\n";
} else {
int sumOfCubes = 0;
int temp = fourDigitNumber;

while (temp != 0) {
int digit = temp % 10;
sumOfCubes += digit * digit * digit;
temp /= 10;
}

cout << "Sum of cubes of digits: " << sumOfCubes << endl;
}

return 0;
}
Program #40
Write a program that take length of a side and calculate area of a square using
formula area = side x side.
CODE: OUTPUT:
#include <iostream>
Enter the length of a side of the square: 4.5
using namespace std; Area of the square: 20.25
int main() {
double side;

cout << "Enter the length of a side of the square: ";


cin >> side;

if (side <= 0) {
cout << "Invalid input. Please enter a positive value for the side
length.\n";
} else {
double area = side * side;

cout << "Area of the square: " << area << endl;
}

return 0;
}

Program #41
Write a program that take length of a side and calculate area of a square using
formula area = side x side.
CODE: OUTPUT:
#include <iostream>
Enter the length of the rectangle: 5
using namespace std; Enter the width of the rectangle: 3
Area of the rectangle: 15
int main() {
Perimeter of the rectangle: 16
double length, width;

cout << "Enter the length of the rectangle: ";


cin >> length;

cout << "Enter the width of the rectangle: ";


cin >> width;

if (length <= 0 || width <= 0) {


cout << "Invalid input. Please enter positive values for length and
width.\n";
} else {
double area = length * width;
double perimeter = 2 * (length + width);

cout << "Area of the rectangle: " << area << endl;
cout << "Perimeter of the rectangle: " << perimeter << endl;
}

return 0;
}
Program #42
Write a program to find the area of a triangle using the formula.
CODE: OUTPUT:
#include <iostream>
Enter the base of the triangle: 8
using namespace std; Enter the height of the triangle: 6
Area of the triangle: 24
int main() {
double base, height;

cout << "Enter the base of the triangle: ";


cin >> base;

cout << "Enter the height of the triangle: ";


cin >> height;

if (base <= 0 || height <= 0) {


cout << "Invalid input. Please enter positive values for the base and
height.\n";
} else {
double area = 0.5 * base * height;

cout << "Area of the triangle: " << area << endl;
}

return 0;
}

Program #43
Write a program to find surface area and volume of a cone.
CODE: OUTPUT:
#include <iostream>
#include <cmath> Enter the radius of the cone: 4
using namespace std; Enter the slant height of the cone: 5
int main() { Enter the height of the cone: 6
double radius, slantHeight, height;
Surface Area of the cone: 130.729
cout << "Enter the radius of the cone: "; Volume of the cone: 100.530
cin >> radius;

cout << "Enter the slant height of the cone: ";


cin >> slantHeight;

cout << "Enter the height of the cone: ";


cin >> height;

if (radius <= 0 || slantHeight <= 0 || height <= 0) {


cout << "Invalid input. Please enter positive values for radius, slant
height, and height.\n";
} else {
double surfaceArea = M_PI * radius * (radius + slantHeight);
double volume = (1.0 / 3.0) * M_PI * pow(radius, 2) * height;

cout << "Surface Area of the cone: " << surfaceArea << endl;
cout << "Volume of the cone: " << volume << endl;
}

return 0;
}
Program #44
Write a program to find the perimeter of a parallelogram, using the formula perimeter
= 2 (side + base).
CODE: OUTPUT:
#include <iostream>
Enter the length of a side of the
using namespace std; parallelogram: 6
Enter the length of the base of the
int main() {
parallelogram: 8
double side, base;
Perimeter of the parallelogram: 28
cout << "Enter the length of a side of the parallelogram: ";
cin >> side;

cout << "Enter the length of the base of the parallelogram: ";
cin >> base;

if (side <= 0 || base <= 0) {


cout << "Invalid input. Please enter positive values for side and
base.\n";
} else {
double perimeter = 2 * (side + base);

cout << "Perimeter of the parallelogram: " << perimeter << endl;
}

return 0;
}

Program #45
Write a program to take radius of a sphere and calculate its Area, circumference and
volume.
CODE: OUTPUT:
#include <iostream>
#include <cmath> Enter the radius of the sphere: 3
Surface Area of the sphere: 113.097
using namespace std; Circumference of the sphere: 18.8501
Volume of the sphere: 113.097
int main() {
double radius;

cout << "Enter the radius of the sphere: ";


cin >> radius;

if (radius <= 0) {
cout << "Invalid input. Please enter a positive value for the
radius.\n";
} else {
double surfaceArea = 4 * M_PI * pow(radius, 2);
double circumference = 2 * M_PI * radius;
double volume = (4.0 / 3.0) * M_PI * pow(radius, 3);

cout << "Surface Area of the sphere: " << surfaceArea << endl;
cout << "Circumference of the sphere: " << circumference << endl;
cout << "Volume of the sphere: " << volume << endl;
}

return 0;
}
Program #46
Write a program to find the area and circumference of a circle, using the formula area
= π *radius2 and circumference = 2 * π * radius.
CODE: OUTPUT:
#include <iostream>
#include <cmath> Enter the radius of the circle: 5
Area of the circle: 78.5398
using namespace std; Circumference of the circle: 31.4159
int main() {
double radius;

cout << "Enter the radius of the circle: ";


cin >> radius;

if (radius <= 0) {
cout << "Invalid input. Please enter a positive value for the
radius.\n";
} else {
double area = M_PI * pow(radius, 2);
double circumference = 2 * M_PI * radius;

cout << "Area of the circle: " << area << endl;
cout << "Circumference of the circle: " << circumference << endl;
}

return 0;
}

Program #47
Write a program to compute the area of a sector of a circle. It inputs the radii and
angle in radians of a sector of a circle. Formula = (radii*radii*angle)/2
CODE: OUTPUT:
#include <iostream>
#include <cmath> Enter the radius of the circle: 7
Enter the angle in radians: 1.2
using namespace std; Area of the sector: 14.6596
int main() {
double radius, angleInRadians;

cout << "Enter the radius of the circle: ";


cin >> radius;

cout << "Enter the angle in radians: ";


cin >> angleInRadians;

if (radius <= 0) {
cout << "Invalid input. Please enter a positive value for the
radius.\n";
} else {
double area = (radius * radius * angleInRadians) / 2;

cout << "Area of the sector: " << area << endl;
}

return 0;
}
Program #48
Write a program that take length of three sides of a triangle and calculate the area of a
triangle.
CODE: OUTPUT:
#include <iostream>
#include <cmath> Enter the length of side 1 of the triangle: 3
Enter the length of side 2 of the triangle: 4
using namespace std;
int main() { Enter the length of side 3 of the triangle: 5
double side1, side2, side3; Area of the triangle: 6
cout << "Enter the length of side 1 of the triangle: ";
cin >> side1;
cout << "Enter the length of side 2 of the triangle: ";
cin >> side2;
cout << "Enter the length of side 3 of the triangle: ";
cin >> side3;
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
cout << "Invalid input. Please enter positive values for all sides.\n";
} else {
// Heron's formula to calculate the area of the triangle
double s = (side1 + side2 + side3) / 2;
double area = sqrt(s * (s - side1) * (s - side2) * (s - side3));
cout << "Area of the triangle: " << area << endl;
}
return 0;
}

Program #49
Write a program to convert centigrade to Fahrenheit using formula, t(°f) = t(°c) × 9/5 +
32 and Fahrenheit to centigrade using formula, t(°c) = (t(°f) – 32) × 5/9.
CODE: OUTPUT:
#include <iostream>
Enter temperature in Centigrade: 20
using namespace std; Temperature in Fahrenheit: 68
Enter temperature in Fahrenheit: 68
int main() {
Temperature in Centigrade: 20
double temperatureCelsius, temperatureFahrenheit;

// Convert Centigrade to Fahrenheit


cout << "Enter temperature in Centigrade: ";
cin >> temperatureCelsius;

double convertedToFahrenheit = (temperatureCelsius * 9 / 5) + 32;


cout << "Temperature in Fahrenheit: " << convertedToFahrenheit <<
endl;

// Convert Fahrenheit to Centigrade


cout << "Enter temperature in Fahrenheit: ";
cin >> temperatureFahrenheit;

double convertedToCelsius = (temperatureFahrenheit - 32) * 5 / 9;


cout << "Temperature in Centigrade: " << convertedToCelsius <<
endl;

return 0;
}
Program #50
Write a program to find simple interest using the formula, simple interest = (p * t *
r)/100, where p = principal amount, t= time period and r= rate of interest.
CODE: OUTPUT:
#include <iostream>
Enter the principal amount: 1000
using namespace std; Enter the time period (in years): 2
Enter the rate of interest (per annum): 5
int main() {
Simple Interest: 100
double principalAmount, timePeriod, rateOfInterest;

cout << "Enter the principal amount: ";


cin >> principalAmount;
cout << "Enter the time period (in years): ";
cin >> timePeriod;
cout << "Enter the rate of interest (per annum): ";
cin >> rateOfInterest;
if (principalAmount < 0 || timePeriod < 0 || rateOfInterest < 0) {
cout << "Invalid input. Please enter non-negative values for principal
amount, time period, and rate of interest.\n";
} else {
double simpleInterest = (principalAmount * timePeriod *
rateOfInterest) / 100;

cout << "Simple Interest: " << simpleInterest << endl;


}

return 0;
}

Program #51
A program that asks the user how many eggs he has and then tells the user how many
dozen eggs he has and how many extra eggs are leftover.
CODE: OUTPUT:
#include <iostream>
Enter the total number of eggs: 36
using namespace std; You have 3 dozen eggs and 0 leftover eggs.
int main() {
int totalEggs;

cout << "Enter the total number of eggs: ";


cin >> totalEggs;

if (totalEggs < 0) {
cout << "Invalid input. Please enter a non-negative number of
eggs.\n";
} else {
int dozen = totalEggs / 12;
int leftoverEggs = totalEggs % 12;

cout << "You have " << dozen << " dozen eggs and " <<
leftoverEggs << " leftover eggs.\n";
}

return 0;
}
Program #52
Write a program to solve the equation, y = b2 – 4ac. The program should ask the
values of variables a, b and c from the user and display the result.
CODE: OUTPUT:
#include <iostream>
Enter the value of variable a: 1
using namespace std; Enter the value of variable b: 5
Enter the value of variable c: 6
int main() {
The result of the equation y = b^2 - 4ac is: 1
double a, b, c;

cout << "Enter the value of variable a: ";


cin >> a;

cout << "Enter the value of variable b: ";


cin >> b;

cout << "Enter the value of variable c: ";


cin >> c;

double result = b * b - 4 * a * c;

cout << "The result of the equation y = b^2 - 4ac is: " << result <<
endl;

return 0;
}

Program #53
Write a program that get a number from user and display its square and cube.
CODE: OUTPUT:
#include <iostream>
Enter a number: 2.5
using namespace std; Square of the number: 6.25
Cube of the number: 15.625
int main() {
double number;

cout << "Enter a number: ";


cin >> number;

double square = number * number;


double cube = number * number * number;

cout << "Square of the number: " << square << endl;
cout << "Cube of the number: " << cube << endl;

return 0;
}
Program #54
Write a program that take age of a person in year and show his age in days and
months.
CODE: OUTPUT:
#include <iostream>
Enter the age in years: 25
using namespace std; Age in months: 300
Age in days: 9125
int main() {
int ageInYears;

cout << "Enter the age in years: ";


cin >> ageInYears;

if (ageInYears < 0) {
cout << "Invalid input. Please enter a non-negative age.\n";
} else {
// Assuming an average of 30.44 days in a month
int ageInMonths = ageInYears * 12;
int ageInDays = ageInYears * 365; // Not considering leap years for
simplicity

cout << "Age in months: " << ageInMonths << endl;


cout << "Age in days: " << ageInDays << endl;
}

return 0;
}

Program #55
Write a program that take price of book and number of books from user and calculate
bill.
CODE: OUTPUT:
#include <iostream>
Enter the price of one book: $15.5
using namespace std; Enter the number of books: 3
Total bill: $46.5
int main() {
double pricePerBook;
int numberOfBooks;

cout << "Enter the price of one book: $";


cin >> pricePerBook;

cout << "Enter the number of books: ";


cin >> numberOfBooks;

if (pricePerBook < 0 || numberOfBooks < 0) {


cout << "Invalid input. Please enter non-negative values.\n";
} else {
double totalBill = pricePerBook * numberOfBooks;

cout << "Total bill: $" << totalBill << endl;


}

return 0;
}
Program #56
Write a program that asks the user for his basic salary. It calculates 35% house Rent,
25 % medical allowance 15% dearness allowance and show its gross salary.
CODE: OUTPUT:
#include <iostream>
Enter your basic salary: $5000
using namespace std; House Rent (35%): $1750
Medical Allowance (25%): $1250
int main() {
Dearness Allowance (15%): $750
double basicSalary;
Gross Salary: $7750
cout << "Enter your basic salary: $";
cin >> basicSalary;

if (basicSalary < 0) {
cout << "Invalid input. Please enter a non-negative basic salary.\n";
} else {
// Calculating allowances
double houseRent = 0.35 * basicSalary;
double medicalAllowance = 0.25 * basicSalary;
double dearnessAllowance = 0.15 * basicSalary;

// Calculating gross salary


double grossSalary = basicSalary + houseRent + medicalAllowance
+ dearnessAllowance;

cout << "House Rent (35%): $" << houseRent << endl;
cout << "Medical Allowance (25%): $" << medicalAllowance <<
endl;
cout << "Dearness Allowance (15%): $" << dearnessAllowance <<
endl;
cout << "Gross Salary: $" << grossSalary << endl;
}

return 0;
}

Program #57
Write a program that take total marks and obtained marks and print its percentage.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter the total marks: 500
int main() { Enter the obtained marks: 420
double totalMarks, obtainedMarks; Percentage: 84%
cout << "Enter the total marks: ";
cin >> totalMarks;
cout << "Enter the obtained marks: ";
cin >> obtainedMarks;
if (totalMarks < 0 || obtainedMarks < 0 || obtainedMarks > totalMarks)
{
cout << "Invalid input. Please enter valid values.\n";
} else {
double percentage = (obtainedMarks / totalMarks) * 100;
cout << "Percentage: " << percentage << "%" << endl;
}
return 0;
}
Program #58
Write a program to calculate covered distance S. Take Time t, initial velocity vi and
acceleration a from user and use formula s = vit+1/2at2
CODE: OUTPUT:
#include <iostream>
Enter the time (t) in seconds: 5
using namespace std; Enter the initial velocity (vi) in meters per
second: 10
int main() {
Enter the acceleration (a) in meters per
double time, initialVelocity, acceleration;
second squared: 2
cout << "Enter the time (t) in seconds: "; Covered Distance (S): 100 meters
cin >> time;

cout << "Enter the initial velocity (vi) in meters per second: ";
cin >> initialVelocity;

cout << "Enter the acceleration (a) in meters per second squared: ";
cin >> acceleration;

if (time < 0 || initialVelocity < 0) {


cout << "Invalid input. Please enter non-negative values for time
and initial velocity.\n";
} else {
double coveredDistance = initialVelocity * time + 0.5 * acceleration
* time * time;

cout << "Covered Distance (S): " << coveredDistance << " meters"
<< endl;
}

return 0;
}

Program #59
Write a program to take distance in KM and convert it into miles. 1 Mile = 1.69 KM
CODE: OUTPUT:
#include <iostream>
Enter the distance in kilometers: 16.9
using namespace std; Distance in Miles: 10 miles
int main() {
double distanceInKM;

cout << "Enter the distance in kilometers: ";


cin >> distanceInKM;

if (distanceInKM < 0) {
cout << "Invalid input. Please enter a non-negative distance.\n";
} else {
double distanceInMiles = distanceInKM / 1.69;

cout << "Distance in Miles: " << distanceInMiles << " miles" <<
endl;
}
return 0;
}
Program #60
Write a program to take weight in pounds and convert into Kg.1 pound =0.453592kg.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter the weight in pounds: 150
int main() { Weight in Kilograms: 68.1818 kg
double weightInPounds;
cout << "Enter the weight in pounds: ";
cin >> weightInPounds;

if (weightInPounds < 0) {
cout << "Invalid input. Please enter a non-negative weight.\n";
} else {
double weightInKg = weightInPounds * 0.453592;
cout << "Weight in Kilograms: " << weightInKg << " kg" << endl;
}
return 0;
}

Program #61
Write a program to take marks of five books of a student and calculate its total marks
and percentage.
CODE: OUTPUT:
#include <iostream>
Enter marks for five books:
using namespace std; Book 1: 85
Book 2: 90
int main() {
Book 3: 75
int marks[5];
int totalMarks = 500; // Assuming each book has a maximum of 100
Book 4: 92
marks Book 5: 88

cout << "Enter marks for five books:\n"; Total Marks: 430/500
Percentage Marks: 86%
for (int i = 0; i < 5; ++i) {
cout << "Book " << i + 1 << ": ";
cin >> marks[i];

if (marks[i] < 0 || marks[i] > 100) {


cout << "Invalid marks! Marks should be between 0 and 100.\n";
return 1;
}
}

int aggregateMarks = 0;

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


aggregateMarks += marks[i];
}

float percentage = float(aggregateMarks) / totalMarks * 100;

cout << "\nTotal Marks: " << aggregateMarks << "/" << totalMarks <<
endl;
cout << "Percentage Marks: " << percentage << "%" << endl;

return 0;
}
Program #62
Write a program that takes number of gallons form user and display it in cubic foot
(hint 1 cubic foot = 7.481 gallons)
CODE: OUTPUT:
#include <iostream>
Enter the number of gallons: 22.443
using namespace std; Equivalent in Cubic Feet: 2.99998 cubic feet
int main() {
double gallons;

cout << "Enter the number of gallons: ";


cin >> gallons;

if (gallons < 0) {
cout << "Invalid input. Please enter a non-negative number of
gallons.\n";
} else {
double cubicFeet = gallons / 7.481;

cout << "Equivalent in Cubic Feet: " << cubicFeet << " cubic feet"
<< endl;
}

return 0;
}

Program #63
Write a program that take rainfall in mm and convert it into rainfall in inches (hint: 1
inch = 25.4mm)
CODE: OUTPUT:
#include <iostream>
Enter the rainfall in millimeters: 50.8
using namespace std; Equivalent in Inches: 2 inches
int main() {
double rainfallInMM;

cout << "Enter the rainfall in millimeters: ";


cin >> rainfallInMM;

if (rainfallInMM < 0) {
cout << "Invalid input. Please enter a non-negative amount of
rainfall.\n";
} else {
double rainfallInInches = rainfallInMM / 25.4;

cout << "Equivalent in Inches: " << rainfallInInches << " inches" <<
endl;
}

return 0;
}
Program #64
The distance between two cities (in km.) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimeters.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter the distance between two cities in kilometers: 150
int main() { Distance in Meters: 150000 meters
double distanceInKM; Distance in Feet: 492126 feet
cout << "Enter the distance between two cities in kilometers: "; Distance in Inches: 5905512.99 inches
cin >> distanceInKM;
Distance in Centimeters: 15000000 centimeters
if (distanceInKM < 0) {
cout << "Invalid input. Please enter a non-negative distance.\n";
} else {
// Conversion factors
double metersConversion = 1000.0;
double feetConversion = 3280.84;
double inchesConversion = 39370.1;
double centimetersConversion = 100000.0;
// Convert distance to different units
double distanceInMeters = distanceInKM * metersConversion;
double distanceInFeet = distanceInKM * feetConversion;
double distanceInInches = distanceInKM * inchesConversion;
double distanceInCentimeters = distanceInKM *
centimetersConversion;
cout << "Distance in Meters: " << distanceInMeters << " meters" <<
endl;
cout << "Distance in Feet: " << distanceInFeet << " feet" << endl;
cout << "Distance in Inches: " << distanceInInches << " inches" <<
endl;
cout << "Distance in Centimeters: " << distanceInCentimeters << "
centimeters" << endl;
}
return 0;
}

Program #65
The town has a population of 80,000, with 52% men and 48% total literacy. Among the
entire population, 35% are literate men. A program can be written to calculate the
number of illiterate men and women.
CODE: OUTPUT:
#include <iostream>
using namespace std; Total Illiterate Men: 16960
int main() { Total Illiterate Women: 34240
double percentageOfMen = 52;
double percentageOfTotalLiteracy = 48;
double percentageOfLiterateMen = 35;
// Total population of the town
int totalPopulation = 80000;
// Calculating the number of literate men
double literateMen = (percentageOfLiterateMen / 100) * totalPopulation;
// Calculating the number of illiterate men
double illiterateMen = (percentageOfMen / 100) * totalPopulation -
literateMen;
// Calculating the number of literate women
double literateWomen = (percentageOfTotalLiteracy / 100) *
totalPopulation - literateMen;
// Calculating the number of illiterate women
double illiterateWomen = totalPopulation - literateMen - literateWomen;
// Displaying the results
cout << "Total Illiterate Men: " << illiterateMen << endl;
cout << "Total Illiterate Women: " << illiterateWomen << endl;
return 0;
}
Program #66
A cashier has currency notes of denominations 10, 50 and 100. If the amount to be
withdrawn is input through the keyboard in hundreds, find the total number of
currency notes of each denomination the cashier will have to give to the withdrawer.
CODE: OUTPUT:
#include <iostream>
using namespace std; Enter the amount to be withdrawn in hundreds: 5
int main() { Number of 10 Rupee Notes: 50
// Denominations Number of 50 Rupee Notes: 0
int denomination10 = 10; Number of 100 Rupee Notes: 0
int denomination50 = 50;
int denomination100 = 100;
int amountInHundreds;
cout << "Enter the amount to be withdrawn in hundreds: ";
cin >> amountInHundreds;
if (amountInHundreds < 0) {
cout << "Invalid input. Please enter a non-negative amount.\n";
} else {
int totalAmount = amountInHundreds * 100;
int notes10 = totalAmount / denomination10;
int notes50 = (totalAmount % denomination100) / denomination50;
int notes100 = (totalAmount % denomination100) % denomination50 /
denomination10;
cout << "Number of 10 Rupee Notes: " << notes10 << endl;
cout << "Number of 50 Rupee Notes: " << notes50 << endl;
cout << "Number of 100 Rupee Notes: " << notes100 << endl;
}
return 0;
}

Program #67
If the total selling price of 15 items and the total profit earned on them is input
through the keyboard, write a program to find the cost price of one item.
CODE: OUTPUT:
#include<iostream>
using namespace std; Enter the total selling price of 15 items: 7500
Enter the total profit earned on 15 items: 1500
int main() { Cost Price of One Item: 500
int numberOfItems = 15;
double totalSellingPrice, totalProfit;

cout << "Enter the total selling price of 15 items: ";


cin >> totalSellingPrice;

cout << "Enter the total profit earned on 15 items: ";


cin >> totalProfit;

if (totalSellingPrice < 0 || totalProfit < 0) {


cout << "Invalid input. Please enter non-negative values.\n";
} else {
double costPricePerItem = (totalSellingPrice - totalProfit) /
numberOfItems;
cout << "Cost Price of One Item: " << costPricePerItem << endl;
}

return 0;
}

You might also like