Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

C - Problem Solving-Sheet (Premium Version) - Code With Redoy

Uploaded by

ashfaquem2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

C - Problem Solving-Sheet (Premium Version) - Code With Redoy

Uploaded by

ashfaquem2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 218

1

Code with Redoy


C++ Problem-Solving Sheet (Premium Version) ||
250+ Problems with Solution code and Tutorials(Making)

Facing a problem? Need mentor support?


Join our what’s App group

Web version

Code With Redoy Interactive Coding PDF


2

Basic Problems (18 Problems)......................................................... 3


IF-Else (25 Problems).....................................................................12
Switch Case (9 Problems).............................................................. 32
Loops (41 Problems)...................................................................... 42
1D Array (29 Problems).................................................................. 71
2D Array (17 Problems).................................................................. 97
Pattern (16 Problems)...................................................................116
Series (30 Problems).................................................................... 129
String (36 Problems).....................................................................146
Function (11 Problems).................................................................182
Pointer (6 Problems).....................................................................200
Files (12 Problems).......................................................................206

Code With Redoy Interactive Coding PDF


3

Basic Problems (18 Problems)


1. Write a program to print your name, date of birth, and mobile number.
#include <iostream>
using namespace std;
int main(){

cout<<"Md Fuadul Islam Redoy";


cout<<"\n5 April 2000";
cout<<"\nPhone Number : +8801236987";

return 0;
}

2. Write a program to enter two numbers and perform all arithmetic operations.
#include<iostream>
using namespace std;
int main ()
{
int x,y,sum,sub,mul;
float div;
printf("Enter Two Numbers = ");
scanf("%d %d",&x,&y);
sum = x+y;
sub = x-y;
mul = x*y;
div = x/y;

cout<<endl<<"Summation of Two Numbers = "<<sum<<endl;


cout<<"Subtraction of Two Numbers = "<<sub<<endl;
cout<<"Multiplication of Two Numbers = "<<mul<<endl;
cout<<"Division of Two Numbers = "<<div<<endl;

return 0;
}

3. Write a program to enter the length, and breadth of a rectangle and find its perimeter
and area.
#include<iostream>
using namespace std;
int main()
{
float length, width, perimeter, area;
cout<<"Enter length of rectangle: ";

Code With Redoy Interactive Coding PDF


4

cin>>length;
cout<<"Enter width of rectangle: ";
cin>>width;

area = length * width;


perimeter = 2 * (length + width);
cout<<"Area of rectangle: "<<area<<endl;
cout<<"Perimeter of rectangle: "<<perimeter;
return 0;
}

4. Write a Program to calculate the area of an equilateral triangle.


#include<iostream>
#include<math.h>
using namespace std;
int main(){
float side, area;
cout<<" Input the value of the side of the equilateral triangle: ";
cin>>side;

area = (sqrt(3) / 4) * (side * side);

cout<<" The area of equilateral triangle is: "<<area<<endl;


return 0;
}

5. Write a program to calculate the perimeter and area of a circle with a given radius.
#include <iostream>
using namespace std;
int main()
{
int radius;
float area, perimeter;
radius = 6;

perimeter = (2*3.1416*radius);
area = (3.1416*radius*radius);

cout<<"Perimeter of the Circle = "<< perimeter << " inches\n";


cout<<"Area of the Circle = "<< area << " square inches\n";

return 0;
}

Code With Redoy Interactive Coding PDF


5

6. Write a program to find the third angle of a triangle if two angles are given.
#include <iostream>
using namespace std;
int main()
{
int ang1, ang2, ang3;
cout<<"Input two angles of triangle separated by comma : ";
cin>>ang1>>ang2;

ang3 = 180 - (ang1 + ang2);

cout<<"Third angle of the triangle: " << ang3;


return 0;
}

7. Write a program that converts Centigrade to Fahrenheit.


#include<iostream>
using namespace std;

int main ()
{
float f, c;
cout<<"Enter Celsius temperature: ";
cin>>f;

f = ((9 * c) / 5) + 32;

cout<<"Fahrenheit: "<< f;

return 0;
}

8. Write a program that converts Fahrenheit to Centigrade.


#include <iostream>
using namespace std;

int main()
{
float frh, cel;
cout << "Input the temperature in Fahrenheit : ";
cin >> frh;

cel = ((frh * 5.0)-(5.0 * 32))/9;

cout << " The temperature in Fahrenheit : " << frh << endl;
cout << " The temperature in Celsius : " << cel << endl;

Code With Redoy Interactive Coding PDF


6

return 0;
}

9. Write a Program to enter marks of five subjects and calculate the total, average, and
percentage.
#include <iostream>
using namespace std;

int main(){
float phy, math, chem, bio, ict, total, average, per;
cout<< "Enter the marks of all subject = ";
cin >> phy >> math >> bio >> chem >> ict;

total = phy + math + chem + bio + ict;


average = (phy + math + chem + bio + ict) / 5;
per = (total / 500) * 100;

cout << "Total number = " << total;


cout << "\nAverage number = " << average;
cout << "\nPercentage = " << per;

return 0;
}

10. Write a Program to enter P, T, and R and calculate simple interest.


#include <iostream>
using namespace std;

int main(){
float p, t, r, si, ci;
cout << "Enter the value of p, t, r = ";
cin>>p>>t>>r;

si = (p * t * r) / 100;

cout << "You compound interest = " << ci;


cout << "\nYou total amount with interest = " << (ci + p);

return 0;
}

Code With Redoy Interactive Coding PDF


7

11. Write a Program to enter P, T, and R and calculate compound interest.


#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float principle, rate, time, CI;
cout<<"Enter principle (amount): ";
cin>>principle;

cout<<"Enter time: ";


cin>>time;

cout<<"Enter rate: ";


cin>>rate;

CI = principle* (pow((1 + rate / 100), time));

cout<<"Compound Interest = "<<CI;


return 0;
}

12. Write a Program that takes minutes as input and displays the total number of hours
and minutes.
#include<iostream>
using namespace std;
int main(){
int min, restMin, h;
cout<<"Enter total minutes = ";
cin>>min;

h = min / 60;
restMin = min % 60;

cout<<min<<" minutes = "<< h << " hours and " << restMin
<< " minutes.";

return 0;
}

Code With Redoy Interactive Coding PDF


8

13. Write a program that reads a first name, last name, and year of birth and displays the
names and the year one after another sequentially.
#include<iostream>
using namespace std;
int main(){
string fName, lName;
int year;

cout<<"Enter your first name = ";


cin>>fName;
cout<<"Enter your last name = ";
cin>>lName;
cout<<"Enter your date of birth = ";
cin>>year;

cout<<"\n\nYour first name = "<<fName;


cout<<"\nYour last name = "<<lName;
cout<<"\nYour date of birth = "<<year;

return 0;
}

14. Write a program to convert specified days into years, weeks and the rest of the days.
#include <iostream>
using namespace std;
int main()
{
int days, years, weeks;
cout<<"Enter days: ";
cin>>days;

/* Conversion */
years = (days / 365);
weeks = (days % 365) / 7;
days = days - ((years * 365) + (weeks * 7));

cout<<"YEARS: " << years;


cout<<"\nWEEKS: " << weeks;
cout<<"\nDAYS: " << days;

return 0;
}

15. Write a program that accepts an employee's ID, totally worked hours of a month, and
the amount he received per hour. Print the employee's ID and salary for a particular
month.
#include<iostream>

Code With Redoy Interactive Coding PDF


9

int main(){
int id, workHour, hourlyRate, monthlySalary;
cout << "Enter your Employee ID: ";
cin >> id;

cout << "Enter your work hour: ";


cin >> workHour;

cout << "Enter your hourly rate: ";


cin >> hourlyRate;

monthlySalary = (workHour * hourlyRate);

cout << "Your Employee Id: " << id;


cout << "\nYour monthly salaray is: " << monthlySalary;

return 0;
}

16. Write a program to find the power of any number x ^ y.


#include<iostream>
using namespace std;
#include<math.h>
int main()
{
int base, power, result;
cout<<"Enter the value of base = ";
cin>>base;
cout<<"Enter the value of power = ";
cin>>power;

result = ceil(pow(base, power));

cout<<"Result = "<<result;

return 0;
}

17. Write a program to enter any number and calculate its square root.
#include <iostream>
#include<math.h>
using namespace std;
int main(){
int num, result;
cout<<"Enter a number: ";

Code With Redoy Interactive Coding PDF


10

cin>>num;

result = sqrt(num);

cout<<"Square root = "<<result;


return 0;
}

18. Write a program to calculate a bike’s total consumption from the given total distance
(integer value) traveled (in km) and spent fuel (in liters, float number – 2 decimal
points.
#include <iostream>
using namespace std;
int main(){
int x;
float y;
cout<<"Input total distance in km: ";
cin>>x;

cout<<"Input total fuel spent in liters: ";


cin>>y;

cout<<"Average consumption (km/lt) " << x/y;

return 0;
}

Code With Redoy Interactive Coding PDF


11

IF-Else (25 Problems)


19. Write a program to find the maximum between two numbers.
#include<iostream>
using namespace std;
int main(){
int num1, num2;
cout<<"Enter two numbers = ";
cin>>num1>>num2;

if(num1 > num2){


cout<<num1<<" is big.";
}
else{
cout<<num2<<" is big.";
}

return 0;
}

20. Write a program to find the maximum between three numbers.


#include<iostream>
using namespace std;
int main(){
int num1, num2, num3;
cout<<"Enter three numbers = ";
cin>>num1>>num2>>num3;

if((num1 > num2) && (num1 > num3)){


cout<<num1<<" is big.";
}
else if((num2 > num1) && (num2 > num3)){
cout<<num2<<" is big.";
}
else{
cout<<num3<<" is big.";
}

return 0;
}

21. Write a program to check whether a number is even or odd.


#include <iostream>
using namespace std;
int main()

Code With Redoy Interactive Coding PDF


12

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

if(num %2 == 0)
cout<<num<<" is an EVEN number."<<endl;
else
cout<<num<<" is an ODD number."<<endl;

return 0;
}

22. Write a program to enter the week number and print the day of
the week.
#include<iostream>
using namespace std;
int main(){
int week;
cout<<"Enter week number (1-7): ";
cin>>week;

if(week == 1){
cout<<"Saturday";
}
else if(week == 2){
cout<<"Sunday";
}
else if(week == 3){
cout<<"Monday";
}
else if(week == 4){
cout<<"Tuesday";
}
else if(week == 5){
cout<<"Wednesday";
}
else if(week == 6){
cout<<"Thursday";
}
else if(week == 7){
cout<<"Friday";
}
else{
cout<<"Invalid Input! Please enter week number between
1-7.";
}
}

Code With Redoy Interactive Coding PDF


13

23. Write a program to check whether a number is negative or


positive or zero.
#include<iostream>
using namespace std;
int main(){
int num;
cout<<"Enter a Number: ";
cin>>num;

if(num < 0){


cout<<num<<" is negative number.";
}
else if(num == 0){
cout<<num<<" is zero.";
}
else{
cout<<num<<" is positive number.";
}

return 0;
}

24. Write a program to check whether a number is divisible by 5 or


11 or not.
#include <iostream>
using namespace std;

int main() {
int num;

cout << "Enter a number: ";


cin >> num;

if (num % 5 == 0) {
cout << num << " is divisible by 5" << endl;
}

if (num % 11 == 0) {
cout << num << " is divisible by 11" << endl;
}

if (num % 5 != 0 && num % 11 != 0) {


cout << num << " is not divisible by 5 or 11" << endl;

Code With Redoy Interactive Coding PDF


14

return 0;
}

25. Write a program to input any character and check whether it is the
alphabet, digit, or special character.
#include <iostream>
using namespace std;

int main() {
char ch;

cout << "Enter a character: ";


cin >> ch;

if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
cout << ch << " is an alphabet" << endl;
}

else if (ch >= '0' && ch <= '9') {


cout << ch << " is a digit" << endl;
}

else {
cout << ch << " is a special character" << endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF


15

26. Write a program to check whether you are eligible to make a NID
Card or not.
#include <iostream>
using namespace std;

int main() {
int age;
char nationality;

cout << "Enter your age: ";


cin >> age;

cout << "Enter your nationality (B for Bangladeshi, F for


foreigner): ";
cin >> nationality;

if (nationality == 'B' && age >= 18) {


cout << "You are eligible to make a NID Card.";
}
else if (nationality == 'F' && age >= 18) {
cout << "You are eligible to make a NID Card, but with
certain restrictions.";
}
else {
cout << "Sorry, you are not eligible to make a NID
Card.";
}

return 0;
}

27. Write a program to check whether the year is a leap year or not.
#include <iostream>
using namespace std;

Code With Redoy Interactive Coding PDF


16

int main() {
int year;

cout << "Enter a year: ";


cin >> year;

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))


{
cout << year << " is a leap year." << endl;
}
else {
cout << year << " is not a leap year." << endl;
}

return 0;
}

28. Your younger brother studied in a primary school. He is fluent in


the English alphabet. But he doesn't know about vowels and
consonants. Your mother assigns you to teach him to know about
which alphabets are vowels and consonants. So you will make a
program (using else if ladder) where your brother writes any
alphabet and your program will tell him that it is a vowel or
consonant.
#include <iostream>
using namespace std;

int main() {
char ch;

cout << "Enter an alphabet: ";


cin >> ch;

Code With Redoy Interactive Coding PDF


17

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch


== 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch
== 'U') {
cout << ch << " is a vowel." << endl;
}
else {
cout << ch << " is a consonant." << endl;
}

return 0;
}

29. Write a program to check whether the character is an alphabet or


not.
#include <iostream>
using namespace std;

int main() {
char c;

cout << "Enter a character: ";


cin >> c;

if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
cout << "The character is an alphabet.";
}
else {
cout << "The character is not an alphabet.";
}

return 0;
}

Code With Redoy Interactive Coding PDF


18

30. Write a program to check the uppercase or lowercase alphabet.


#include <iostream>
using namespace std;

int main() {
char c;

cout << "Enter a character: ";


cin >> c;

if (c >= 'a' && c <= 'z') {


cout << "The character is a lowercase alphabet.";
}
else if (c >= 'A' && c <= 'Z') {
cout << "The character is an uppercase alphabet.";
}
else {
cout << "The character is not an alphabet.";
}

return 0;
}

31. Write a program to input the week number and print the weekday.
#include <iostream>
using namespace std;

int main() {
int weekNum;

cout << "Enter the week number (1-7): ";

Code With Redoy Interactive Coding PDF


19

cin >> weekNum;

if (weekNum == 1) {
cout << "Monday" << endl;
}
else if (weekNum == 2) {
cout << "Tuesday" << endl;
}
else if (weekNum == 3) {
cout << "Wednesday" << endl;
}
else if (weekNum == 4) {
cout << "Thursday" << endl;
}
else if (weekNum == 5) {
cout << "Friday" << endl;
}
else if (weekNum == 6) {
cout << "Saturday" << endl;
}
else if (weekNum == 7) {
cout << "Sunday" << endl;
}
else {
cout << "Invalid input!" << endl;
}

return 0;
}

32. Write a program to input the month number and print the number
of days in that month.
#include <iostream>
using namespace std;

Code With Redoy Interactive Coding PDF


20

int main() {
int month;

cout << "Enter month number (1-12): ";


cin >> month;

if (month == 2) {
cout << "28 or 29 days depending on
whether it is a leap year.";
}
else if (month == 4 || month == 6 || month ==
9 || month == 11) {
cout << "30 days";
}
else {
cout << "31 days";
}

return 0;
}

33. Write a program to check whether two integers are equal or not.
#include <iostream>
using namespace std;

int main() {
int a, b;

cout << "Enter two integers: ";

Code With Redoy Interactive Coding PDF


21

cin >> a >> b;

if (a == b) {
cout << "The two integers are equal.";
}
else {
cout << "The two integers are not equal.";
}

return 0;
}

34. Write a program to input the angles of a triangle and check


whether a triangle is valid or not.
#include <iostream>
using namespace std;

int main() {
int angle1, angle2, angle3, sum;

cout << "Enter three angles of a triangle: ";


cin >> angle1 >> angle2 >> angle3;

sum = angle1 + angle2 + angle3;

if (sum == 180) {
cout << "The triangle is valid.";
}
else {
cout << "The triangle is not valid.";
}

return 0;
}

Code With Redoy Interactive Coding PDF


22

35. Write a program to check whether the triangle is an equilateral,


isosceles, or scalene triangle.
#include <iostream>
using namespace std;

int main() {
int side1, side2, side3;

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


cin >> side1 >> side2 >> side3;

if (side1 == side2 && side2 == side3) {


cout << "It is an equilateral triangle." << endl;
}
else if (side1 == side2 || side2 == side3 || side1 == side3)
{
cout << "It is an isosceles triangle." << endl;
}
else {
cout << "It is a scalene triangle." << endl;
}

return 0;
}

36. Write a program to find all roots of a quadratic equation.


#include <iostream>
#include <cmath>
using namespace std;

int main() {
double a, b, c, root1, root2, discriminant;

Code With Redoy Interactive Coding PDF


23

cout << "Enter the coefficients a, b, and c of the quadratic


equation: ";
cin >> a >> b >> c;

discriminant = b * b - 4 * a * c;

if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "The roots are real and different." << endl;
cout << "Root 1 = " << root1 << endl;
cout << "Root 2 = " << root2 << endl;
}
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
cout << "The roots are real and equal." << endl;
cout << "Root 1 = Root 2 = " << root1 << endl;
}
else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
cout << "The roots are complex and different." << endl;
cout << "Root 1 = " << realPart << " + " << imaginaryPart
<< "i" << endl;
cout << "Root 2 = " << realPart << " - " << imaginaryPart;
}
}

37. Your younger brother studied in a primary school. He is fluent in


the English alphabet. But he doesn't know about the vowels and
consonants. Your mother assigns you to teach him to know about
which alphabets are vowels and consonants.
#include <iostream>
using namespace std;

Code With Redoy Interactive Coding PDF


24

int main() {
char ch;

cout << "Enter an alphabet: ";


cin >> ch;

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch


== 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch
== 'U') {
cout << ch << " is a vowel." << endl;
}
else {
cout << ch << " is a consonant." << endl;
}

return 0;
}

38. So you will make a program (using else if ladder) where your
brother writes any alphabet and your program will tell him that it is a
vowel or consonant.
#include <iostream>
using namespace std;

int main() {
char ch;

cout << "Enter an alphabet: ";


cin >> ch;

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch


== 'u' ||

Code With Redoy Interactive Coding PDF


25

ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch


== 'U') {
cout << ch << " is a vowel." << endl;
}
else {
cout << ch << " is a consonant." << endl;
}

return 0;
}

39. Write a program to find the eligibility for admission to a


professional course base on the following criteria:
Marks in MATHS >= 65
Marks in PHY >= 55
Marks in CHEM >= 50
Total in all three subjects => 180
Or,
Total in Math and physics >=140.
#include <iostream>
using namespace std;

int main() {
int math, phy, chem, total;
cout << "Enter the marks in Maths, Physics, and Chemistry (out
of 100):\n";
cin >> math >> phy >> chem;
total = math + phy + chem;
if (math >= 65 && phy >= 55 && chem >= 50 && total >= 180) {
cout << "Congratulations! You are eligible for admission
to the professional course.\n";
}
else if (math + phy >= 140) {
cout << "Congratulations! You are eligible for admission
to the professional course.\n";
}
else {

Code With Redoy Interactive Coding PDF


26

cout << "Sorry, you are not eligible for admission to the
professional course.\n";
}
return 0;
}

40. Write a program to read the temperature in centigrade and display


a suitable message according to the temperature state below:
Temp < 0 then Freezing weather
Temp 0-10 then very cold weather
Temp 10-20 then cold weather
Temp 20-30 then Normal in Temp
Temp 30-40 then it’s hot
Temp >=40 then it’s very hot.
#include <iostream>
using namespace std;

int main() {
float temp;

cout << "Enter the temperature in Celsius: ";


cin >> temp;

if (temp < 0) {
cout << "Freezing weather" << endl;
}
else if (temp >= 0 && temp <= 10) {
cout << "Very cold weather" << endl;
}
else if (temp > 10 && temp <= 20) {
cout << "Cold weather" << endl;
}
else if (temp > 20 && temp <= 30) {
cout << "Normal in temp" << endl;
}
else if (temp > 30 && temp <= 40) {

Code With Redoy Interactive Coding PDF


27

cout << "It's hot" << endl;


}
else if (temp > 40) {
cout << "It's very hot" << endl;
}

return 0;
}

41. Write a program to read four values a, b, c, and d from the


terminal, evaluate the value of (a+b) to (c-d), and print the result, if
c-d is not equal to zero.
#include <iostream>
using namespace std;

int main() {
int a, b, c, d, result;

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


cin >> a;

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


cin >> b;

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


cin >> c;

cout << "Enter the value of d: ";


cin >> d;

if (c - d != 0) {
result = (a + b) / (c - d);
cout << "Result: " << result << endl;
}

Code With Redoy Interactive Coding PDF


28

return 0;
}

42. Write a program to input the basic salary of an employee and


calculate its Gross salary according to the following:
Basic Salary <= 10000: HRA = 20%, DA = 80%
Basic Salary <= 20000: HRA = 25%, DA = 90%
Basic Salary > 20000: HRA = 30%, DA = 95%.
#include <iostream>
using namespace std;

int main() {
float basic_salary, gross_salary, hra, da;

cout << "Enter the basic salary of the employee: ";


cin >> basic_salary;

if (basic_salary <= 10000) {


hra = basic_salary * 0.2;
da = basic_salary * 0.8;
}
else if (basic_salary <= 20000) {
hra = basic_salary * 0.25;
da = basic_salary * 0.9;
}
else {
hra = basic_salary * 0.3;
da = basic_salary * 0.95;
}

gross_salary = basic_salary + hra + da;

cout << "Gross Salary: " << gross_salary << endl;

return 0;

Code With Redoy Interactive Coding PDF


29

43. Write a program to input electricity unit charges and calculate the
total electricity bill according to the given condition:
For the first 50 units, Rs. 0.50/unit
For the next 100 units Rs. 0.75/unit
For the next 100 units Rs. 1.20/unit
For units above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill.
#include <iostream>
using namespace std;

int main() {
int units;
float total_bill, surcharge = 0.2;

cout << "Enter electricity units consumed: ";


cin >> units;

if(units <= 50) {


total_bill = units * 0.5;
}
else if(units <= 150) {
total_bill = 25 + (units - 50) * 0.75;
}
else if(units <= 250) {
total_bill = 100 + (units - 150) * 1.20;
}
else {
total_bill = 220 + (units - 250) * 1.50;
}

total_bill += total_bill * surcharge;

cout << "Electricity Bill = Rs. " << total_bill;

Code With Redoy Interactive Coding PDF


30

return 0;
}

Code With Redoy Interactive Coding PDF


31

Switch Case (9 Problems)

44. Write a program to print the day of the week name using a
switch case.
#include <iostream>
using namespace std;

int main() {
int day;
cout << "Enter the day number (1-7): ";
cin >> day;

switch(day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day number" << endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF


32

45. Write a program to print the total number of days in a month


using a switch case.
#include <iostream>
using namespace std;

int main() {
int month, days;
cout << "Enter the month number (1-12): ";
cin >> month;

switch(month) {
case 1:
days = 31;
break;
case 2:
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;

Code With Redoy Interactive Coding PDF


33

break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
cout << "Invalid month number" << endl;
return 0;
}

cout << "The month has " << days << " days." << endl;
return 0;
}

46. Write a program to check whether an alphabet is a vowel or


consonant using a switch case.
#include <iostream>
using namespace std;

int main() {
char alphabet;
cout << "Enter an alphabet: ";
cin >> alphabet;

switch(alphabet) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout << alphabet << " is a vowel." << endl;
break;
default:

Code With Redoy Interactive Coding PDF


34

cout << alphabet << " is a consonant." << endl;


}

return 0;
}

47. Write a program to find the maximum between two numbers


using a switch case.
#include <iostream>
using namespace std;

int main() {
double num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

switch(num1 > num2) {


case true:
cout << num1 << " is the maximum." << endl;
break;
case false:
cout << num2 << " is the maximum." << endl;
break;
}

return 0;
}

48. Write a program to check whether a number is even or odd using


a switch case.
#include <iostream>
using namespace std;

int main() {
int num;

Code With Redoy Interactive Coding PDF


35

cout << "Enter a number: ";


cin >> num;

switch(num % 2) {
case 0:
cout << num << " is even." << endl;
break;
case 1:
cout << num << " is odd." << endl;
break;
}

return 0;
}

49. Write a program to check whether a number is positive, negative,


or zero using a switch case.
#include <iostream>
using namespace std;

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

switch(num > 0) {
case true:
cout << num << " is positive." << endl;
break;
case false:
switch(num < 0) {
case true:
cout << num << " is negative." << endl;
break;
case false:
cout << num << " is zero." << endl;
break;
}

Code With Redoy Interactive Coding PDF


36

break;
}

return 0;
}

50. Write a program to find the roots of a quadratic equation using a


switch case.
#include <iostream>
#include <cmath>
using namespace std;

int main() {
double a, b, c, x1, x2, discriminant;
cout << "Enter the coefficients a, b, and c: ";
cin >> a >> b >> c;

discriminant = b * b - 4 * a * c;

switch(discriminant > 0) {
case true:
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "The roots are real and different." << endl;
cout << "x1 = " << x1 << ", x2 = " << x2 << endl;
break;
case false:
switch(discriminant < 0) {
case true:
cout << "The roots are complex and different."
<< endl;
cout << "x1 = " << -b / (2 * a) << "+" <<
sqrt(-discriminant) / (2 * a) << "i" << endl;
cout << "x2 = " << -b / (2 * a) << "-" <<
sqrt(-discriminant) / (2 * a) << "i" << endl;
break;
case false:
x1 = -b / (2 * a);

Code With Redoy Interactive Coding PDF


37

cout << "The roots are real and same." <<


endl;
cout << "x1 = x2 = " << x1 << endl;
break;
}
break;
}

return 0;
}

51. Write a program to create a Simple Calculator using a switch


case.
#include <iostream>
using namespace std;

int main() {
char operation;
double num1, num2;
cout << "Enter the operation (+, -, *, /): ";
cin >> operation;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

switch(operation) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2
<< endl;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2
<< endl;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2
<< endl;
break;
case '/':

Code With Redoy Interactive Coding PDF


38

if(num2 != 0) {
cout << num1 << " / " << num2 << " = " << num1 /
num2 << endl;
}
else {
cout << "Error: division by zero." << endl;
}
break;
default:
cout << "Error: invalid operation." << endl;
break;
}

return 0;
}

52. Write a program that takes the integer number of a student and
finds out the grade using a switch case statement following the
grading system.
A = 90-100
B+ = 87-89
B = 84-86
B- = 80-83
C+ = 77-79
C = 74-76
C- = 70-73
D+ = 65-69
D = 60-64
F = Below 60
#include <iostream>
using namespace std;

int main() {
int score;
cout << "Enter the student's score: ";
cin >> score;

char grade;

Code With Redoy Interactive Coding PDF


39

switch(score/10) {
case 10:
case 9:
grade = 'A';
break;
case 8:
if(score >= 87) {
grade = 'B';
}
else if(score >= 84) {
grade = 'B';
cout << "+";
}
else if(score >= 80) {
grade = 'B';
cout << "-";
}
break;
case 7:
if(score >= 77) {
grade = 'C';
}
else if(score >= 74) {
grade = 'C';
cout << "+";
}
else if(score >= 70) {
grade = 'C';
cout << "-";
}
break;
case 6:
if(score >= 65) {
grade = 'D';
}
else if(score >= 60) {
grade = 'D';
cout << "+";
}
break;
default:

Code With Redoy Interactive Coding PDF


40

grade = 'F';
break;
}

cout << "The student's grade is " << grade << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


41

Loops (41 Problems)

53. Write a program to Print your name 20 times using a for loop,
while loop and do while loop.
#include <iostream>
using namespace std;

int main() {
int i = 1;

// Using a for loop


cout << "Using a for loop:" << endl;
for(i = 1; i <= 20; i++) {
cout << i << ". Your name" << endl;
}

// Using a while loop


i = 1;
cout << "\nUsing a while loop:" << endl;
while(i <= 20) {
cout << i << ". Your name" << endl;
i++;
}

// Using a do-while loop


i = 1;
cout << "\nUsing a do-while loop:" << endl;
do {
cout << i << ". Your name" << endl;
i++;
} while(i <= 20);

return 0;
}

Code With Redoy Interactive Coding PDF


42

54. Write a program to print 1-10 using a for loop, while loop and do
while loop.
#include <iostream>
using namespace std;

int main() {
int i;

// Using a for loop


cout << "Using a for loop:" << endl;
for(i = 1; i <= 10; i++) {
cout << i << " ";
}
cout << endl;

// Using a while loop


i = 1;
cout << "\nUsing a while loop:" << endl;
while(i <= 10) {
cout << i << " ";
i++;
}
cout << endl;

// Using a do-while loop


i = 1;
cout << "\nUsing a do-while loop:" << endl;
do {
cout << i << " ";
i++;
} while(i <= 10);
cout << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


43

55. Write a program to Calculate the Sum of 1 to 10 numbers using a


for loop, while loop and do while loop.
#include <iostream>
using namespace std;

int main() {
int i, sum = 0;

// Using a for loop


cout << "Using a for loop:" << endl;
for(i = 1; i <= 10; i++) {
sum += i;
}
cout << "The sum of 1 to 10 is: " << sum << endl;

// Using a while loop


i = 1;
sum = 0;
cout << "\nUsing a while loop:" << endl;
while(i <= 10) {
sum += i;
i++;
}
cout << "The sum of 1 to 10 is: " << sum << endl;

// Using a do-while loop


i = 1;
sum = 0;
cout << "\nUsing a do-while loop:" << endl;
do {
sum += i;
i++;
} while(i <= 10);
cout << "The sum of 1 to 10 is: " << sum << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


44

56. Write an infinite loop. An infinite loop never ends. Condition is


always true.
#include <iostream>
using namespace std;

int main() {
while(true) {
cout << "This is an infinite loop." << endl;
}

return 0;
}

57. Write a program to print even numbers up to N.


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

cout << "Even numbers up to " << n << " are: ";
for(int i=2; i<=n; i+=2) {
cout << i << " ";
}
cout << endl;

return 0;
}

58. Write a program to print odd numbers up to N.


#include <iostream>

Code With Redoy Interactive Coding PDF


45

using namespace std;

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

cout << "Odd numbers up to " << n << " are: ";
for(int i=1; i<=n; i+=2) {
cout << i << " ";
}
cout << endl;

return 0;
}

59. Write a program to find the sum of all natural numbers between 1
to n.
#include <iostream>
using namespace std;

int main() {
int n, sum=0;
cout << "Enter a positive integer: ";
cin >> n;

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


sum += i;
}

cout << "The sum of all natural numbers between 1 to " << n <<
" is: " << sum << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


46

60. Write a program to find the sum of all even numbers between 1 to
n.
#include <iostream>
using namespace std;

int main() {
int n, sum=0;
cout << "Enter a positive integer: ";
cin >> n;

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


sum += i;
}

cout << "The sum of all even numbers between 1 to " << n << "
is: " << sum << endl;

return 0;
}

61. Write a program to print all natural numbers in reverse (from n to


1).
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

cout << "Natural numbers in reverse order from " << n << " to
1 are: ";
for(int i=n; i>=1; i--) {
cout << i << " ";

Code With Redoy Interactive Coding PDF


47

}
cout << endl;

return 0;
}

62. Write a program to print those numbers from 1 to 100 which are
divisible by 7.
#include<iostream>
using namespace std;

int main() {
for(int i=1;i<=100;i++) {
if(i%7 == 0) {
cout<<i<<" ";
}
}
return 0;
}

63. Write a program to print all alphabets from a to z.


#include<iostream>
using namespace std;

int main() {
for(char c='a';c<='z';c++) {
cout<<c<<" ";
}
return 0;
}

Code With Redoy Interactive Coding PDF


48

64. Write a program to count the number of digits in a number.


#include<iostream>
using namespace std;

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

while(num!=0) {
num/=10;
count++;
}
cout<<"The number of digits in the given number is:
"<<count<<endl;
return 0;
}

65. Write a program to find the last digit of a given number.


#include<iostream>
using namespace std;

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

last_digit = num%10;
cout<<"The last digit of the given number is:
"<<last_digit<<endl;
return 0;
}

Code With Redoy Interactive Coding PDF


49

66. Write a program to find the first digit of a given number.


#include<iostream>
using namespace std;

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

while(num>=10) {
num/=10;
}
first_digit = num;
cout<<"The first digit of the given number is:
"<<first_digit<<endl;
return 0;
}

67. Write a program to find the sum of the first and last digits of a
number.
#include<iostream>
using namespace std;

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

last_digit = num%10;
while(num>=10) {
num/=10;
}
first_digit = num;

sum = first_digit + last_digit;

Code With Redoy Interactive Coding PDF


50

cout<<"The sum of first and last digits of the given number


is: "<<sum<<endl;
return 0;
}

68. Write a program to swap the first and last digits of a number.
#include<iostream>
using namespace std;

int main() {
int num, temp, last_digit, first_digit, digits=0;
cout<<"Enter a number: ";
cin>>num;

temp = num;
last_digit = temp%10;
while(temp>=10) {
temp/=10;
digits++;
}
first_digit = temp;

int multiplier = 1;
for(int i=0;i<digits;i++) {
multiplier *= 10;
}

int swapped_num = last_digit*multiplier + num%multiplier -


last_digit + first_digit;
cout<<"The swapped number is: "<<swapped_num<<endl;
return 0;
}

Code With Redoy Interactive Coding PDF


51

69. Write a program to calculate the sum of the digits of a number.


#include <iostream>
using namespace std;

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

while (num > 0) {


sum += num % 10;
num /= 10;
}

cout << "Sum of digits: " << sum;


return 0;
}

70. Write a program to calculate the product of the digits of a number.


#include <iostream>
using namespace std;

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

while (num > 0) {


product *= num % 10;
num /= 10;
}

cout << "Product of digits: " << product;


return 0;
}

Code With Redoy Interactive Coding PDF


52

71. Write a program to enter a number and print its reverse.


e.x. The number 12345 should be written as 54321.
#include <iostream>
using namespace std;

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

while (num > 0) {


reversed = reversed * 10 + num % 10;
num /= 10;
}

cout << "Reversed number: " << reversed;


return 0;
}

72. Write a program to check whether a number is a palindrome or


not.
#include <iostream>
using namespace std;

int main() {
int num, original, reversed = 0;
cout << "Enter a number: ";
cin >> num;

original = num;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}

Code With Redoy Interactive Coding PDF


53

if (original == reversed)
cout << original << " is a palindrome.";
else
cout << original << " is not a palindrome.";

return 0;
}

73. Write a program to find the frequency of each digit in a given


integer.
#include <iostream>
using namespace std;

int main() {
int num, freq[10] = {0};
cout << "Enter a number: ";
cin >> num;

while (num > 0) {


freq[num % 10]++;
num /= 10;
}

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


if (freq[i] > 0)
cout << "Frequency of " << i << " is " << freq[i] <<
endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF


54

74. Write a program to print the multiplication table of any number.


#include <iostream>
using namespace std;

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

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


cout << num << " x " << i << " = " << num * i << endl;
}

return 0;
}

75. Write a program to enter a number and print it in words.


#include <iostream>
#include <string>

using namespace std;

int main() {
string ones[] = {"", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"};
string tens[] = {"", "", "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety"};
string teens[] = {"ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"};
int num, digit;
string word;

cout << "Enter a number: ";


cin >> num;

if (num == 0) {

Code With Redoy Interactive Coding PDF


55

cout << "zero";


} else if (num < 0) {
cout << "minus ";
num = -num;
}

if (num >= 1000) {


digit = num / 1000;
word = ones[digit] + " thousand ";
num = num % 1000;
}

if (num >= 100) {


digit = num / 100;
word += ones[digit] + " hundred ";
num = num % 100;
}

if (num >= 10 && num < 20) {


word += teens[num % 10];
} else {
if (num >= 20) {
digit = num / 10;
word += tens[digit] + " ";
num = num % 10;
}

if (num >= 1 && num <= 9) {


word += ones[num];
}
}

cout << word << endl;


return 0;
}

76. Write a program to print all ASCII characters with their values.

Code With Redoy Interactive Coding PDF


56

#include <iostream>

using namespace std;

int main() {
for (int i = 0; i <= 127; i++) {
cout << "ASCII value of " << char(i) << " is " << i <<
endl;
}

return 0;
}

77. Write a program to find the power of a number using for loop.
#include <iostream>
using namespace std;

int main() {
int base, exponent, result = 1;

cout << "Enter base and exponent: ";


cin >> base >> exponent;

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


result *= base;
}

cout << base << "^" << exponent << " = " << result << endl;

return 0;
}

78. Write a program to find all factors of a number.

Code With Redoy Interactive Coding PDF


57

#include <iostream>
using namespace std;

int main() {
int num;

cout << "Enter a number: ";


cin >> num;

cout << "Factors of " << num << " are: ";
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
cout << i << " ";
}
}
cout << endl;

return 0;
}

79. Write a program to calculate the factorial of a number.


#include <iostream>
using namespace std;

int main() {
int num, fact = 1;

cout << "Enter a number: ";


cin >> num;

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


fact *= i;
}

cout << num << "! = " << fact << endl;

return 0;

Code With Redoy Interactive Coding PDF


58

80. Write a program to find the HCF (GCD) and LCM of two
numbers.
#include <iostream>
using namespace std;

int main() {
int num1, num2, hcf, lcm;

cout << "Enter two numbers: ";


cin >> num1 >> num2;

for (int i = 1; i <= num1 && i <= num2; i++) {


if (num1 % i == 0 && num2 % i == 0) {
hcf = i;
}
}

lcm = (num1 * num2) / hcf;

cout << "HCF of " << num1 << " and " << num2 << " is " << hcf
<< endl;
cout << "LCM of " << num1 << " and " << num2 << " is " << lcm
<< endl;

return 0;
}

81. Write a program to check whether a number is a Prime number or


not.
#include <iostream>
using namespace std;

Code With Redoy Interactive Coding PDF


59

int main() {
int num, count = 0;

cout << "Enter a number: ";


cin >> num;

for (int i = 2; i <= num/2; i++) {


if (num % i == 0) {
count++;
break;
}
}

if (count == 0 && num != 1) {


cout << num << " is a prime number" << endl;
} else {
cout << num << " is not a prime number" << endl;
}

return 0;
}

82. Write a program to find the sum of all prime numbers between 1
to n.
#include <iostream>
using namespace std;

bool isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}

Code With Redoy Interactive Coding PDF


60

return true;
}

int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;

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


if (isPrime(i)) {
sum += i;
}
}

cout << "The sum of all prime numbers between 1 and " << n <<
" is: " << sum << endl;
return 0;
}

83. Write a program to find all prime factors of a number.


#include <iostream>
using namespace std;

void primeFactors(int n) {
while (n % 2 == 0) {
cout << 2 << " ";
n /= 2;
}

for (int i = 3; i <= sqrt(n); i += 2) {


while (n % i == 0) {
cout << i << " ";
n /= i;
}
}

if (n > 2) {

Code With Redoy Interactive Coding PDF


61

cout << n;
}
}

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

cout << "Prime factors of " << n << " are: ";
primeFactors(n);

return 0;
}

84. Write a program to check whether a number is an Armstrong


number or not.
#include<iostream>
using namespace std;
int main(){
int num, sum = 0, rem, cNum;
cout<<"Enter a number - ";
cin>>num;
cNum = num;

while(num != 0){
rem = num % 10;
sum += (rem * rem * rem);
num /= 10;
}

if(cNum == sum){
cout<<cNum<<" is armstrong number.";
}
else{
cout<<cNum<<" isn't armstrong number.";
}
}

85. Write a program to print all Armstrong numbers between 1 to n.


#include <iostream>

Code With Redoy Interactive Coding PDF


62

#include <math.h>
using namespace std;

int power(int base, int exponent) {


int result = 1;
while (exponent != 0) {
result *= base;
--exponent;
}
return result;
}

bool isArmstrong(int n) {
int originalNum, numDigits, sum = 0;
originalNum = n;
numDigits = (int) log10(n) + 1;
while (n > 0) {
int remainder = n % 10;
sum += power(remainder, numDigits);
n /= 10;
}
return (sum == originalNum);
}

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

cout << "Armstrong numbers between 1 and " << n << " are: ";
for (int i = 1; i <= n; i++) {
if (isArmstrong(i)) {
cout << i << " ";
}
}

return 0;
}

Code With Redoy Interactive Coding PDF


63

86. Write a program to check whether a number is a Perfect number


or not.
#include <iostream>
using namespace std;

int main() {
int n, sum = 0;

cout << "Enter a number: ";


cin >> n;

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


if (n % i == 0) {
sum += i;
}
}

if (sum == n) {
cout << n << " is a Perfect number." << endl;
}
else {
cout << n << " is not a Perfect number." << endl;
}

return 0;
}

87. Write a program to print all Perfect numbers between 1 to n.


#include <iostream>
using namespace std;

int main() {
int n, sum;

Code With Redoy Interactive Coding PDF


64

cout << "Enter a number: ";


cin >> n;

cout << "Perfect numbers between 1 and " << n << " are: ";
for (int i = 1; i <= n; i++) {
sum = 0;
for (int j = 1; j <= i/2; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
cout << i << " ";
}
}

return 0;
}

88. Write a program to check whether a number is a Strong number


or not.
#include <iostream>
using namespace std;

int main() {
int n, fact, sum = 0, temp;

cout << "Enter a number: ";


cin >> n;

temp = n;

while (temp != 0) {
fact = 1;
int digit = temp % 10;
for (int i = 1; i <= digit; i++) {
fact *= i;

Code With Redoy Interactive Coding PDF


65

}
sum += fact;
temp /= 10;
}

if (sum == n) {
cout << n << " is a Strong number." << endl;
}
else {
cout << n << " is not a Strong number." << endl;
}

return 0;
}

89. Write a program to print all Strong numbers between 1 to n.


#include <iostream>
using namespace std;

int main() {
int n, fact, sum, temp;

cout << "Enter a number: ";


cin >> n;

cout << "Strong numbers between 1 and " << n << " are: ";
for (int i = 1; i <= n; i++) {
sum = 0;
temp = i;
while (temp != 0) {
fact = 1;
int digit = temp % 10;
for (int j = 1; j <= digit; j++) {
fact *= j;
}
sum += fact;
temp /= 10;

Code With Redoy Interactive Coding PDF


66

}
if (sum == i) {
cout << i << " ";
}
}

return 0;
}

90. Write a program to print the Fibonacci series up to n terms.


#include<iostream>
using namespace std;

int main()
{
int n, t1 = 0, t2 = 1, nextTerm = 0;
cout << "Enter the number of terms: ";
cin >> n;

cout << "Fibonacci Series: ";

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


{
// Prints the first two terms.
if(i == 1)
{
cout << " " << t1;
continue;
}
if(i == 2)
{
cout << t2 << " ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;

Code With Redoy Interactive Coding PDF


67

cout << nextTerm << " ";


}
return 0;
}

91. Write a program to check whether a number is a spy number or


not.
#include<iostream>
using namespace std;

int main()
{
int num, originalNum, sum = 0, product = 1, lastDigit;

cout << "Enter a positive integer: ";


cin >> num;

// Storing the original number


originalNum = num;

// Finding the sum and product of the digits of the number


while(num > 0)
{
// Finding the last digit
lastDigit = num % 10;

// Adding the last digit to the sum variable


sum = sum + lastDigit;

// Multiplying the last digit to the product variable


product = product * lastDigit;

// Removing the last digit


num = num / 10;
}

Code With Redoy Interactive Coding PDF


68

// Checking whether the number is a spy number or not


if(sum == product)
{
cout << originalNum << " is a Spy number.";
}
else
{
cout << originalNum << " is not a Spy number.";
}

return 0;
}

92. Write a program to print the spy numbers up to N.


#include<iostream>
using namespace std;

int main()
{
int n;
cout << "Enter the value of N: ";
cin >> n;
cout << "Spy numbers from 1 to " << n << ": ";
for(int i = 1; i <= n; i++)
{
int num = i, sum = 0, product = 1, lastDigit;
while(num > 0)
{
lastDigit = num % 10;
sum = sum + lastDigit;
product = product * lastDigit;
num = num / 10;
}
if(sum == product)
{
cout << i << " ";
}

Code With Redoy Interactive Coding PDF


69

}
return 0;
}

Code With Redoy Interactive Coding PDF


70

1D Array (29 Problems)

93. Write a program to read and print elements of an array.


#include <iostream>
using namespace std;

int main() {
int arr[5];
cout << "Enter 5 elements of the array: ";
for(int i=0; i<5; i++) {
cin >> arr[i];
}
cout << "The elements of the array are: ";
for(int i=0; i<5; i++) {
cout << arr[i] << " ";
}
return 0;
}

94. Write a program to insert an element in an array.


#include <iostream>
using namespace std;

int main() {
int arr[6] = {1, 2, 3, 4, 5};
int n, pos;
cout << "Enter the number to insert: ";
cin >> n;
cout << "Enter the position to insert: ";
cin >> pos;
for(int i=5; i>=pos; i--) {
arr[i] = arr[i-1];
}
arr[pos-1] = n;
cout << "The updated array is: ";
for(int i=0; i<6; i++) {

Code With Redoy Interactive Coding PDF


71

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


}
return 0;
}

95. Write a program to calculate the sum of 5 numbers using an array.


#include <iostream>
using namespace std;

int main() {
int arr[5], sum=0;
cout << "Enter 5 elements of the array: ";
for(int i=0; i<5; i++) {
cin >> arr[i];
sum += arr[i];
}
cout << "The sum of the elements of the array is: " << sum;
return 0;
}

96. Write a program to calculate the sum of 5 numbers using an array


(Numbers should be taken from the user).
#include <iostream>
using namespace std;

int main() {
int arr[5], sum=0;
cout << "Enter 5 numbers: ";
for(int i=0; i<5; i++) {
cin >> arr[i];
sum += arr[i];
}
cout << "The sum of the numbers is: " << sum;

Code With Redoy Interactive Coding PDF


72

return 0;
}

97. Write a program to calculate the sum and average of N numbers


using an array.
#include <iostream>
using namespace std;

int main() {
int arr[100], n, sum=0;
float avg;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements of the array: ";
for(int i=0; i<n; i++) {
cin >> arr[i];
sum += arr[i];
}
avg = (float) sum / n;
cout << "The sum of the elements is: " << sum << endl;
cout << "The average of the elements is: " << avg;
return 0;
}

98. Write a program to find the maximum and minimum elements in


an array.
#include <iostream>
using namespace std;

int main() {
int arr[10] = {3, 5, 2, 7, 1, 9, 4, 8, 6, 0};
int max = arr[0], min = arr[0];
int n = 10;

Code With Redoy Interactive Coding PDF


73

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


if(arr[i] > max)
max = arr[i];
if(arr[i] < min)
min = arr[i];
}

cout << "Maximum element in the array is " << max << endl;
cout << "Minimum element in the array is " << min << endl;

return 0;
}

99. Write a program to print the positive and negative numbers of an


array.
#include <iostream>
using namespace std;

int main() {
int arr[10] = {3, -5, 2, -7, 1, 9, -4, 8, -6, 0};
int n = 10;

cout << "Positive elements in the array are: ";


for(int i = 0; i < n; i++) {
if(arr[i] > 0)
cout << arr[i] << " ";
}

cout << "\nNegative elements in the array are: ";


for(int i = 0; i < n; i++) {
if(arr[i] < 0)
cout << arr[i] << " ";
}

return 0;
}

Code With Redoy Interactive Coding PDF


74

100. Write a program to copy all elements from an array to another


array.
#include <iostream>
using namespace std;

int main() {
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5];

// Copying elements from arr1 to arr2


for(int i = 0; i < 5; i++) {
arr2[i] = arr1[i];
}

// Displaying elements of arr2


cout << "Elements of arr2: ";
for(int i = 0; i < 5; i++) {
cout << arr2[i] << " ";
}
return 0;
}

101. Write a program to sort all the elements of an array and find the
largest element from that array.
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};

Code With Redoy Interactive Coding PDF


75

int size = sizeof(arr) / sizeof(arr[0]);

sort(arr, arr + size);


int largest = arr[size - 1];

cout << "Sorted Array: ";


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}

cout << "\nLargest Element: " << largest << endl;

return 0;
}

102. Write a program to find the largest element in an array.


#include <iostream>

using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);

int largest = arr[0];


for (int i = 1; i < size; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

cout << "Largest Element: " << largest << endl;

return 0;

Code With Redoy Interactive Coding PDF


76

103. Write a program to find the second largest element in an array.


#include <iostream>
#include <algorithm>

using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);

sort(arr, arr + size);


int secondLargest = arr[size - 2];

cout << "Second Largest Element: " << secondLargest <<


endl;

return 0;
}

104. Write a program to count the total number of negative, even, and
odd numbers in an array.
#include <iostream>

using namespace std;

int main() {
int arr[] = {5, -2, 9, 0, -5, 6};
int size = sizeof(arr) / sizeof(arr[0]);

Code With Redoy Interactive Coding PDF


77

int negativeCount = 0, evenCount = 0, oddCount = 0;

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


if (arr[i] < 0)
negativeCount++;
else if (arr[i] % 2 == 0)
evenCount++;
else
oddCount++;
}

cout << "Negative Numbers: " << negativeCount << endl;


cout << "Even Numbers: " << evenCount << endl;
cout << "Odd Numbers: " << oddCount << endl;

return 0;
}

105. Write a program to delete an element from an array at a specified


position.
#include <iostream>

using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int positionToDelete = 2; // Specify the position to
delete (0-based index)

if (positionToDelete < 0 || positionToDelete >= size) {


cout << "Invalid position to delete." << endl;
} else {
for (int i = positionToDelete; i < size - 1; i++) {

Code With Redoy Interactive Coding PDF


78

arr[i] = arr[i + 1];


}
size--;

cout << "Array after deletion: ";


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

return 0;
}

106. Write a program to count the frequency of each element in an


array.
#include <iostream>
#include <unordered_map>

using namespace std;

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

unordered_map<int, int> frequencyMap;

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


frequencyMap[arr[i]]++;
}

for (const auto& pair : frequencyMap) {


cout << "Element: " << pair.first << ", Frequency: "
<< pair.second << endl;

Code With Redoy Interactive Coding PDF


79

return 0;
}

107. Write a program to print all unique elements in the array.


#include <iostream>
#include <unordered_map>

using namespace std;

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

unordered_map<int, int> frequencyMap;

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


frequencyMap[arr[i]]++;
}

for (const auto& pair : frequencyMap) {


cout << "Element: " << pair.first << ", Frequency: "
<< pair.second << endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF


80

108. Write a program to count the total number of duplicate elements


in an array.
#include <iostream>
#include <unordered_map>

using namespace std;

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

unordered_map<int, int> frequencyMap;

int duplicateCount = 0;

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


frequencyMap[arr[i]]++;
if (frequencyMap[arr[i]] > 1) {
duplicateCount++;
}
}

cout << "Total Duplicate Elements: " << duplicateCount << endl;

return 0;
}

109. Write a program to delete all duplicate elements from an array.


#include <iostream>
#include <unordered_set>

using namespace std;

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

unordered_set<int> uniqueElements;
int newArray[size];
int newSize = 0;

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

Code With Redoy Interactive Coding PDF


81

if (uniqueElements.find(arr[i]) ==
uniqueElements.end()) {
newArray[newSize] = arr[i];
uniqueElements.insert(arr[i]);
newSize++;
}
}

cout << "Array after deleting duplicates: ";


for (int i = 0; i < newSize; i++) {
cout << newArray[i] << " ";
}
cout << endl;

return 0;
}

110. Write a program to merge two arrays to a third array.


#include <iostream>

using namespace std;

int main() {
int arr1[] = {1, 2, 3};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {4, 5, 6};
int size2 = sizeof(arr2) / sizeof(arr2[0]);

int mergedArray[size1 + size2];

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


mergedArray[i] = arr1[i];
}

Code With Redoy Interactive Coding PDF


82

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


mergedArray[size1 + i] = arr2[i];
}

cout << "Merged Array: ";


for (int i = 0; i < size1 + size2; i++) {
cout << mergedArray[i] << " ";
}
cout << endl;

return 0;
}

111. Write a program to find the reverse of an array.


#include <iostream>

using namespace std;

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

int reversedArray[size];

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


reversedArray[i] = arr[size - i - 1];
}

cout << "Reversed Array: ";


for (int i = 0; i < size; i++) {
cout << reversedArray[i] << " ";
}
cout << endl;

Code With Redoy Interactive Coding PDF


83

return 0;
}

112. Write a program to put the even and odd elements of an array in
two separate arrays.
#include <iostream>

using namespace std;

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

int even[size], odd[size];


int evenSize = 0, oddSize = 0;

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


if (arr[i] % 2 == 0) {
even[evenSize] = arr[i];
evenSize++;
} else {
odd[oddSize] = arr[i];
oddSize++;
}
}

cout << "Even Elements: ";


for (int i = 0; i < evenSize; i++) {
cout << even[i] << " ";
}
cout << endl;

cout << "Odd Elements: ";


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

Code With Redoy Interactive Coding PDF


84

cout << odd[i] << " ";


}
cout << endl;

return 0;
}

113. Write a program to search for an element in an array.


#include <iostream>

using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3; // Element to search for
bool found = false;

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


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

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

return 0;
}

Code With Redoy Interactive Coding PDF


85

114. Write a program to sort array elements in ascending or


descending order.
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);

// Sorting in ascending order


sort(arr, arr + size);

// Printing sorted array in ascending order


cout << "Ascending Order: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

// Sorting in descending order


sort(arr, arr + size, greater<int>());

// Printing sorted array in descending order


cout << "Descending Order: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


86

115. Write a program to sort even and odd elements of an array


separately.
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);

int even[size], odd[size];


int evenSize = 0, oddSize = 0;

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


if (arr[i] % 2 == 0) {
even[evenSize] = arr[i];
evenSize++;
} else {
odd[oddSize] = arr[i];
oddSize++;
}
}

// Sorting even elements in ascending order


sort(even, even + evenSize);

// Sorting odd elements in ascending order


sort(odd, odd + oddSize);

cout << "Even Elements (Sorted): ";


for (int i = 0; i < evenSize; i++) {
cout << even[i] << " ";
}
cout << endl;

Code With Redoy Interactive Coding PDF


87

cout << "Odd Elements (Sorted): ";


for (int i = 0; i < oddSize; i++) {
cout << odd[i] << " ";
}
cout << endl;

return 0;
}

116. Write a program to the left rotate an array.


#include <iostream>

using namespace std;

void leftRotate(int arr[], int n, int d) {


int temp[d];

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


temp[i] = arr[i];
}

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


arr[i - d] = arr[i];
}

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


arr[n - d + i] = temp[i];
}
}

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

Code With Redoy Interactive Coding PDF


88

int d = 2; // Number of positions to left rotate

leftRotate(arr, size, d);

cout << "Left Rotated Array: ";


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

117. Write a program to right rotate an array.


#include <iostream>

using namespace std;

void rightRotate(int arr[], int n, int d) {


int temp[d];

for (int i = n - d; i < n; i++) {


temp[i - (n - d)] = arr[i];
}

for (int i = n - d - 1; i >= 0; i--) {


arr[i + d] = arr[i];
}

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


arr[i] = temp[i];
}
}

Code With Redoy Interactive Coding PDF


89

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int d = 2; // Number of positions to right rotate

rightRotate(arr, size, d);

cout << "Right Rotated Array: ";


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

118. Suppose you have an Array with the size of 10. Your program
will input all the array elements from the user. Now using a loop,
traverse the array. During traversing, if the array contains an odd
number in the odd index, take the odd value from that odd index
from the array and make the summation of those numbers and
replace that index value with 0. Print the summation and the array.
The given sample is for your understanding. You must use your own
sample.

Example:
Before the operation:

Index 1 2 3 4 5 6 7 8 9 10
Elements 1 3 6 5 7 9 11 8 3 8

After the operation:

Code With Redoy Interactive Coding PDF


90

Elements:
Elements 0 3 6 5 0 9 0 8 0 8
Summation = 22
#include <iostream>

using namespace std;

int main() {
int arr[10];
int sum = 0;

// Input array elements from the user


cout << "Enter 10 elements of the array:" << endl;
for (int i = 0; i < 10; i++) {
cin >> arr[i];
}

// Traverse the array and perform odd number replacement


and summation
for (int i = 0; i < 10; i++) {
if (i % 2 != 0 && arr[i] % 2 != 0) {
sum += arr[i];
arr[i] = 0;
}
}

// Print the modified array and summation


cout << "Modified Array: ";
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;

cout << "Sum of Odd Numbers in Odd Indices: " << sum <<
endl;

Code With Redoy Interactive Coding PDF


91

return 0;
}

119. The scenario in front of any virtual Bank is like Men and women
standing in a single line. It looks so bad. Now separate men and
women into different two line that looks like a gentle management
system and develop the above program to find the majority of
gender in the line.

M = male
W = Women

Disarranged line scenario is like - M M W W M M M M W M


M M W W M M M M W M

After operation:
M M M M M M M

W W W
#include <iostream>
#include <vector>

using namespace std;

int main() {
vector<char> bankLine; // Use 'M' for men and 'F' for
women

// Input the people in the bank line


cout << "Enter the people in the bank line (M for men, F
for women, 'X' to stop):" << endl;
char person;

Code With Redoy Interactive Coding PDF


92

while (true) {
cin >> person;
if (person == 'X' || person == 'x') {
break;
}
bankLine.push_back(person);
}

int menCount = 0, womenCount = 0;


for (char gender : bankLine) {
if (gender == 'M' || gender == 'm') {
menCount++;
} else if (gender == 'F' || gender == 'f') {
womenCount++;
}
}

if (menCount > womenCount) {


cout << "Majority: Men" << endl;
} else if (womenCount > menCount) {
cout << "Majority: Women" << endl;
} else {
cout << "Equal number of men and women." << endl;
}

return 0;
}

120. There’s a list of numbers in a row on the table. Your teacher is


telling a number which is the addition of any of the two numbers
from the given number list on the table. Your job is to find two
numbers whose addition is equal to the number given by your
teacher. If there’s no pair of numbers in a list that is equal to the

Code With Redoy Interactive Coding PDF


93

given number by your teacher, then you will say “Sir, there’s no pair
of numbers equal to your number” otherwise you will show that two
numbers which addition is equal to the given number by your
teacher. Write a program to solve the situation.
#include <iostream>
#include <unordered_set>

using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 9; // Number given by the teacher

unordered_set<int> numbers;

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


int complement = target - arr[i];
if (numbers.find(complement) != numbers.end()) {
cout << "Pair found: " << arr[i] << " + " <<
complement << " = " << target << endl;
return 0;
}
numbers.insert(arr[i]);
}

cout << "Sir, there's no pair of numbers equal to your


number." << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


94

121. Suppose you have taken some values in an array of any size. For
example, array1 = [5, 2, 3, 1, 9, 4]. Now your friend requests you to
shift array values one cell to the right side (Right Shift). As per the
request of your friend, array 1 will be now [4, 5, 2, 3, 1, 9]. Now
write a C program to satisfy the request of your friend by choosing
an appropriate technique to shift the array values to the right.

Note: The array values and size will be defined by the user. Sample
Input: 9 3 8 2 7 1
Sample Output: 1 9 3 8 2 7
#include <iostream>

using namespace std;

void rightShift(int arr[], int size) {


int temp = arr[size - 1];
for (int i = size - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = temp;
}

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

// Right shift the array


rightShift(arr, size);

cout << "Array after right shift: ";


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;

Code With Redoy Interactive Coding PDF


95

Code With Redoy Interactive Coding PDF


96

2D Array (17 Problems)


122. Write a program to print a 2D Array or a matrix like the
given below.

#include <iostream>

using namespace std;

int main() {
int rows = 3;
int cols = 3;
int matrix[3][3] = {{1, 2, 3},
{1, 2, 3},
{1, 2, 3}};

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


for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}

return 0;
}

123. Write a program to take input from the user of a 2D Array or a


matrix.
#include <iostream>

using namespace std;

int main() {

Code With Redoy Interactive Coding PDF


97

int rows, cols;


cout << "Enter the number of rows: ";
cin >> rows;
cout << "Enter the number of columns: ";
cin >> cols;

int matrix[rows][cols];

cout << "Enter matrix elements:" << endl;


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}

return 0;
}

124. Write a program to add, subtract and multiply two matrices.


#include <iostream>

using namespace std;

int main() {
int rows, cols;
cout << "Enter the number of rows and columns for
matrices: ";
cin >> rows >> cols;

int matrix1[rows][cols], matrix2[rows][cols],


sum[rows][cols], diff[rows][cols], product[rows][cols];

cout << "Enter the elements of the first matrix:" << endl;
for (int i = 0; i < rows; i++) {

Code With Redoy Interactive Coding PDF


98

for (int j = 0; j < cols; j++) {


cin >> matrix1[i][j];
}
}

cout << "Enter the elements of the second matrix:" <<


endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix2[i][j];
}
}

// Addition
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Subtraction
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
diff[i][j] = matrix1[i][j] - matrix2[i][j];
}
}

// Multiplication
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
product[i][j] = 0;
for (int k = 0; k < cols; k++) {
product[i][j] += matrix1[i][k] *
matrix2[k][j];
}
}
}

Code With Redoy Interactive Coding PDF


99

return 0;
}

125. Write a program to perform Scalar matrix multiplication.


#include <iostream>

using namespace std;

int main() {
int rows, cols;
cout << "Enter the number of rows and columns for the
matrix: ";
cin >> rows >> cols;

int matrix[rows][cols], scalar;

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


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}

cout << "Enter the scalar value: ";


cin >> scalar;

// Scalar Matrix Multiplication


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] *= scalar;
}
}

Code With Redoy Interactive Coding PDF


100

return 0;
}

126. Write a program to check whether two matrices are equal or not
and find the multiply of those two matrices.
#include <iostream>

using namespace std;

int main() {
int rows, cols;
cout << "Enter the number of rows and columns for
matrices: ";
cin >> rows >> cols;

int matrix1[rows][cols], matrix2[rows][cols],


product[rows][cols];
bool equal = true;

cout << "Enter the elements of the first matrix:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix1[i][j];
}
}

cout << "Enter the elements of the second matrix:" <<


endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix2[i][j];
if (matrix1[i][j] != matrix2[i][j]) {
equal = false;
}

Code With Redoy Interactive Coding PDF


101

}
}

if (equal) {
// Matrices are equal, calculate their product
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
product[i][j] = matrix1[i][j] * matrix2[i][j];
}
}
}

return 0;
}

127. Write a program to find the sum of the main diagonal elements of
a matrix.
#include <iostream>

using namespace std;

int main() {
int n;
cout << "Enter the size of the square matrix: ";
cin >> n;

int matrix[n][n];
int sum = 0;

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
if (i == j) {

Code With Redoy Interactive Coding PDF


102

sum += matrix[i][j];
}
}
}

cout << "Sum of the main diagonal elements: " << sum <<
endl;

return 0;
}

128. Write a program to find the sum of minor diagonal elements of a


matrix.
#include <iostream>

using namespace std;

int main() {
int n;
cout << "Enter the size of the square matrix: ";
cin >> n;

int matrix[n][n];
int sum = 0;

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
if (i + j == n - 1) {
sum += matrix[i][j];
}
}
}

Code With Redoy Interactive Coding PDF


103

cout << "Sum of the minor diagonal elements: " << sum <<
endl;

return 0;
}

129. Write a program to find the sum of each row and column of a
matrix.
#include <iostream>

using namespace std;

int main() {
int rows, cols;
cout << "Enter the number of rows and columns for the
matrix: ";
cin >> rows >> cols;

int matrix[rows][cols];

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


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}

// Calculate and print the sum of each row


cout << "Sum of each row:" << endl;
for (int i = 0; i < rows; i++) {
int rowSum = 0;
for (int j = 0; j < cols; j++) {
rowSum += matrix[i][j];

Code With Redoy Interactive Coding PDF


104

}
cout << "Row " << i + 1 << ": " << rowSum << endl;
}

// Calculate and print the sum of each column


cout << "Sum of each column:" << endl;
for (int j = 0; j < cols; j++) {
int colSum = 0;
for (int i = 0; i < rows; i++) {
colSum += matrix[i][j];
}
cout << "Column " << j + 1 << ": " << colSum << endl;
}

return 0;
}

130. Write a program to interchange diagonals of a matrix.


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the size of the matrix: ";
cin >> n;

int matrix[n][n];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

Code With Redoy Interactive Coding PDF


105

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


int temp = matrix[i][i];
matrix[i][i] = matrix[i][n - i - 1];
matrix[i][n - i - 1] = temp;
}

cout << "Matrix after interchanging diagonals:" << endl;


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}

return 0;
}

131. Write a program to find the upper triangular matrix.


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the size of the matrix: ";
cin >> n;

int matrix[n][n];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}

Code With Redoy Interactive Coding PDF


106

cout << "Upper Triangular Matrix:" << endl;


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j < i) {
cout << "0 ";
} else {
cout << matrix[i][j] << " ";
}
}
cout << endl;
}

return 0;
}

132. Write a program to find a lower triangular matrix.


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the size of the matrix: ";
cin >> n;

int matrix[n][n];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

Code With Redoy Interactive Coding PDF


107

cout << "Lower Triangular Matrix:" << endl;


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j > i) {
cout << "0 ";
} else {
cout << matrix[i][j] << " ";
}
}
cout << endl;
}

return 0;
}

133. Write a program to find the sum of the upper and lower triangular
matrix.
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the size of the matrix: ";
cin >> n;

int matrix[n][n];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

Code With Redoy Interactive Coding PDF


108

int upperSum = 0, lowerSum = 0;


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j < i) {
lowerSum += matrix[i][j];
} else if (j > i) {
upperSum += matrix[i][j];
}
}
}

cout << "Sum of elements in upper triangular matrix: " <<


upperSum << endl;
cout << "Sum of elements in lower triangular matrix: " <<
lowerSum << endl;

return 0;
}

134. Write a program to find the transpose of a matrix.


#include <iostream>
using namespace std;

int main() {
int m, n;
cout << "Enter the number of rows: ";
cin >> m;
cout << "Enter the number of columns: ";
cin >> n;

int matrix[m][n];

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

Code With Redoy Interactive Coding PDF


109

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


for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

cout << "Transpose of the matrix:" << endl;


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << matrix[j][i] << " ";
}
cout << endl;
}

return 0;
}

135. Write a program to find the determinant of a matrix.


#include <iostream>
using namespace std;

const int MAX_SIZE = 10;

float determinant(float matrix[MAX_SIZE][MAX_SIZE], int n) {


if (n == 1) {
return matrix[0][0];
}

float det = 0;
float submatrix[MAX_SIZE][MAX_SIZE];

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


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

Code With Redoy Interactive Coding PDF


110

int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[subi][subj] = matrix[i][j];
subj++;
}
subi++;
}
det += (x % 2 == 0 ? 1 : -1) * matrix[0][x] *
determinant(submatrix, n - 1);
}

return det;
}

int main() {
int n;
cout << "Enter the size of the square matrix: ";
cin >> n;

float matrix[MAX_SIZE][MAX_SIZE];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

float det = determinant(matrix, n);


cout << "Determinant of the matrix: " << det << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


111

136. Write a program to check the Identity matrix.


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the size of the square matrix: ";
cin >> n;

int matrix[10][10];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

bool isIdentity = true;


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((i == j && matrix[i][j] != 1) || (i != j &&
matrix[i][j] != 0)) {
isIdentity = false;
break;
}
}
if (!isIdentity) {
break;
}
}

if (isIdentity) {
cout << "The matrix is an Identity matrix." << endl;
} else {

Code With Redoy Interactive Coding PDF


112

cout << "The matrix is not an Identity matrix." <<


endl;
}

return 0;
}

137. Write a program to check Sparse matrices.


#include <iostream>
using namespace std;

int main() {
int m, n;
cout << "Enter the number of rows: ";
cin >> m;
cout << "Enter the number of columns: ";
cin >> n;

int matrix[10][10];

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


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

int zeroCount = 0, nonZeroCount = 0;


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
zeroCount++;
} else {
nonZeroCount++;

Code With Redoy Interactive Coding PDF


113

}
}
}

if (zeroCount > nonZeroCount) {


cout << "The matrix is a Sparse matrix." << endl;
} else {
cout << "The matrix is not a Sparse matrix." << endl;
}

return 0;
}

138. Write a program to check Symmetric matrices.


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the size of the square matrix: ";
cin >> n;

int matrix[10][10];

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


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

bool isSymmetric = true;


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

Code With Redoy Interactive Coding PDF


114

if (matrix[i][j] != matrix[j][i]) {
isSymmetric = false;
break;
}
}
if (!isSymmetric) {
break;
}
}

if (isSymmetric) {
cout << "The matrix is a Symmetric matrix." << endl;
} else {
cout << "The matrix is not a Symmetric matrix." <<
endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF


115

Pattern (16 Problems)

139. Write a program to print the Square star pattern.


*****
*****
*****
*****
*****
#include<iostream>
using namespace std;
int main(){
int i, j;
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
printf("*");
}
printf("\n");
}
return 0;
}

140. Write a program to print the Right Triangle Star pattern.


*
**
***
****
*****
#include<iostream>
using namespace std;
int main(){
int i, j;
for(i = 1; i <= 5; i++){
for(j = 1; j <= i; j++){

Code With Redoy Interactive Coding PDF


116

cout<<"*";
}
cout<<endl;
}
return 0;
}

141. Write a program to make a pattern like below:

#include<iostream>
using namespace std;
int main(){
int i, j;
for(i = 1; i <= 4; i++){
for(j = 4; j >= i; j--){
cout<<"*";
}
cout<<endl;
}
return 0;
}

142. Write a program to make a pattern like given below:

#include <iostream>
using namespace std;

Code With Redoy Interactive Coding PDF


117

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

for(int i = rows; i >= 1; --i) {


for(int space = 0; space < rows-i; ++space)
cout << " ";

for(int j = i; j <= 2*i-1; ++j)


cout << "* ";

for(int j = 0; j < i-1; ++j)


cout << "* ";

cout << endl;


}

return 0;
}

143. Write a program to print the Pyramid Star Pattern.

#include<iostream>
using namespace std;
int main(){
for(int i = 1; i <= 5; i++){

//for loop to create spaces


for(int space = 1; space <= 5-i; space++){
cout<<" ";

Code With Redoy Interactive Coding PDF


118

//for loop to print *


for(int star = 1; star <= i; star++){
cout<<"* ";
}
cout<<"\n";
}
return 0;
}

144. Write a program to display the pattern like a right angle triangle
with a number.
1
12
123
1234
#include<iostream>
using namespace std;
int main(){
int i, j;
for(i = 1; i <= 4; i++){
for(j = 1; j <= i; j++){
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}

145.

Code With Redoy Interactive Coding PDF


119

#include <iostream>
using namespace std;

int main() {

int rows, count = 0, count1 = 0, k = 0;

cout << "Enter number of rows: ";


cin >> rows;

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


for(int space = 1; space <= rows-i; ++space) {
cout << " ";
++count;
}

while(k != 2*i-1) {
if (count <= rows-1) {
cout << i+k << " ";
++count;
}
else {
++count1;
cout << i+k-2*count1 << " ";
}
++k;
}
count1 = count = k = 0;

cout << endl;


}
return 0;

Code With Redoy Interactive Coding PDF


120

146.
*
**
***
****
*****
****
***
**
*
#include <iostream>
using namespace std;

int main() {
int n = 5; // Change this to the desired number of rows

// Upper part of the pattern


for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
if (j < i) {
cout << " ";
}
}
cout << endl;
}

// Lower part of the pattern


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

Code With Redoy Interactive Coding PDF


121

cout << "*";


if (j < i) {
cout << " ";
}
}
cout << endl;
}

return 0;
}

147. Write a program to make such a pattern as a right-angle triangle


with a number that will repeat a number in a row.
The pattern is like
1
22
333
4444
#include<iostream>
using namespace std;
int main(){
int i, j;
for(i = 1; i <= 4; i++){
for(j = 1; j <= i; j++){
Cout << i<< " ";
}
cout<<endl;
}
return 0;
}

Code With Redoy Interactive Coding PDF


122

148. Write a program to make such a pattern like a right angle triangle
with the number increased by 1.

#include<iostream>
using namespace std;
int main(){
//i = row number
//j = how many columns
int temp = 1;

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


for(int j = 1; j <= i; j++){
cout<<temp<<" ";
temp++;
}
cout<<"\n";
}

return 0;
}

149. Print Pascal's Triangle

#include <iostream>
using namespace std;

int main() {

int rows, coef = 1;

cout << "Enter number of rows: ";


cin >> rows;

Code With Redoy Interactive Coding PDF


123

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


for(int space = 1; space <= rows-i; space++)
cout <<" ";

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


if (j == 0 || i == 0)
coef = 1;
else
coef = coef*(i-j+1)/j;

cout << coef << " ";


}
cout << endl;
}

return 0;
}

150. Write a program to make such a pattern as a pyramid with a


number that will repeat the number in the same row.
1
22
333
4444
#include <iostream>
using namespace std;

int main() {
int n = 4; // Number of rows

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


// Print spaces
for (int j = 1; j <= n - i; j++) {

Code With Redoy Interactive Coding PDF


124

cout << " ";


}

// Print numbers
for (int j = 1; j <= i; j++) {
cout << i;
if (j < i) {
cout << " ";
}
}

cout << endl;


}

return 0;
}

151. Write a program to make a pattern like the below:

#include <iostream>
using namespace std;

int main() {
int n = 5; // Size of the pattern
int center = n / 2; // Center position

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


for (int j = 0; j < n; j++) {
if (i == center && j == center) {
cout << "O ";
} else {

Code With Redoy Interactive Coding PDF


125

cout << "S ";


}
}
cout << endl;
}

return 0;
}

152. Write a program to make a pattern like the below:

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

int main()
{
int n=4; // took a default value
for (int i = n; i >= 1; --i) { // loop for iterating
for (int j = 1; j <= i; ++j) { // loop for printing
cout << j << " ";
}
cout << endl;
}
return 0;
}

Code With Redoy Interactive Coding PDF


126

153. Write a program to make a pattern like the below:

#include <iostream>
using namespace std;

int main() {

char input, alphabet = 'A';

cout << "Enter the uppercase character you want to print


in the last row: ";
cin >> input;

// convert input character to uppercase


input = toupper(input);

for(int i = 1; i <= (input-'A'+1); ++i) {


for(int j = 1; j <= i; ++j) {
cout << alphabet << " ";
}
++alphabet;

cout << endl;


}
return 0;
}

154. Write a program to print the pattern like below(Row


number should be odd and between 3 to 49).

Code With Redoy Interactive Coding PDF


127

#include <iostream>
using namespace std;

int main() {
int n;
cin >> n;

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


for (int j = 0; j < n; j++) {
if (i == j) {
if (((n - 1) / 2) == i && ((n - 1) / 2) == j)
{
cout << "X";
} else {
cout << "\\";
}
} else if (i + j == n - 1) {
cout << "/";
} else {
cout << "*";
}
}
cout << endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF


128

Series (30 Problems)

155. 1 + 2 + 3 + 4 + 5 + 6 =?
#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 1; i <= 6; i++) {
sum += i;
}
cout << "Sum of numbers from 1 to 6: " << sum << endl;
return 0;
}

156. 1 + 2 + 3 + 4 + 5 + 6 + …… + 20 =?
#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
sum += i;
}
cout << "Sum of numbers from 1 to 20: " << sum << endl;
return 0;
}

157. 1 + 2 + 3 + 4 + 5 + …… + N = ?(Use for loop)


#include <iostream>

Code With Redoy Interactive Coding PDF


129

using namespace std;

int main() {
int N;
cout << "Enter a value for N: ";
cin >> N;

int sum = 0;
for (int i = 1; i <= N; i++) {
sum += i;
}
cout << "Sum of numbers from 1 to " << N << ": " << sum <<
endl;
return 0;
}

158. 1 + 2 + 3 + 4 + 5 + …… + N = ?(without loop)


#include <iostream>
using namespace std;

// Function to find the sum of series


int seriesSum(int n)
{
return (n * (n + 1) * (n + 2)) / 6;
}

// Driver code
int main()
{
int n = 4;
cout << seriesSum(n);
return 0;
}

Code With Redoy Interactive Coding PDF


130

159. Write a program to find the summation between 10 to 50 using a


for loop.
#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 10; i <= 50; i++) {
sum += i;
}
cout << "The summation between 10 to 50 is: " << sum <<
endl;
return 0;
}

160. Write a program to find the summation between 10 to 50 without


any loop.
#include <iostream>
using namespace std;

int main() {
int oneToFifty, ontToNine;

oneToFifty = (50 * (50 + 1) * (50 + 2)) / 6;


ontToNine = (9 * (9 + 1) * (9 + 2)) / 6;

int result = oneToFifty - ontToNine;

Code With Redoy Interactive Coding PDF


131

cout << "The summation between 10 to 50 is: " << result <<
endl;
return 0;
}

161. 2 + 4 + 6 + ……… + 10 = ?
#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 2; i <= 10; i += 2) {
sum += i;
}
cout << "Sum of even numbers from 2 to 10: " << sum <<
endl;
return 0;
}

162. 2 + 4 + 6 + ……… + N = ?(Use for loop)


#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter a value for N: ";
cin >> N;

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

Code With Redoy Interactive Coding PDF


132

sum += i;
}
cout << "Sum of even numbers from 2 to " << N << ": " <<
sum << endl;
return 0;
}

163. 2 + 4 + 6 + ……… + N = ?(without loop)


#include <bits/stdc++.h>
using namespace std;

int evenSum(int n)
{
return (n * (n + 1));
}

// Driver program to test above


int main()
{
int n = 20;
cout << "Sum of first " << n
<< " Even numbers is: " << evenSum(n);
return 0;
}

164. Write a program to find the summation of even numbers between


10 to 50 by any loop.
#include <iostream>
using namespace std;

int main() {

Code With Redoy Interactive Coding PDF


133

int sum = 0;
for (int i = 10; i <= 50; i++) {
if (i % 2 == 0) {
sum += i;
}
}
cout << "The summation of even numbers between 10 to 50
is: " << sum << endl;
return 0;
}

165. Write a program to find the summation of even numbers between


10 to 50 without any loop.
#include <iostream>
using namespace std;

int main() {
int sum = 0;
sum = (10 + 50) * 21 / 2;
cout << "The summation of even numbers between 10 to 50
is: " << sum << endl;
return 0;
}

166. 1 + 3 + 5 + ……… + 9 = ?
#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 1; i <= 9; i += 2) {

Code With Redoy Interactive Coding PDF


134

sum += i;
}
cout << "Sum of odd numbers from 1 to 9: " << sum << endl;
return 0;
}

167. 1 + 3 + 5 + ……… + N = ? (Use for loop)


#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter a value for N: ";
cin >> N;

int sum = 0;
for (int i = 1; i <= N; i += 2) {
sum += i;
}
cout << "Sum of odd numbers from 1 to " << N << ": " <<
sum << endl;
return 0;
}

168. 1 + 3 + 5 + ……… + N = ?(without loop)


#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter a value for N: ";

Code With Redoy Interactive Coding PDF


135

cin >> N;

int sum = (N + 1) / 2 * (N + 1) / 2;
cout << "Sum of odd numbers from 1 to " << N << ": " <<
sum << endl;
return 0;
}

169. Write a program to find the summation of odd numbers between


10 to 50 by any loop.
#include <iostream>
using namespace std;

int main() {
int sum = 0;

// Loop through the numbers from start to end


for (int i = 10; i <= 50; i++) {
// Check if the number is odd
if (i % 2 != 0) {
sum += i; // Add the odd number to the sum
}
}

cout << "Sum of odd numbers between " << 10 << " and " <<
50 << " is: " << sum << endl;

return 0;
}
Output: Sum of odd numbers between 10 and 50 is: 600

Code With Redoy Interactive Coding PDF


136

170. Write a program to find the summation of odd numbers between


10 to 50 without any loop.
#include <iostream>
using namespace std;

int main() {
int start = 11; // The first odd number in the range
int end = 49; // The last odd number in the range
int numberOfOdds = (end - start) / 2 + 1; // Calculate the
number of odd numbers
int sum;

// Use the arithmetic progression formula for odd numbers:


Sum = n/2 * (2*a + (n-1)*d)
// where n is the number of terms (numberOfOdds), a is the
first term (start), and d is the common difference (2)
sum = numberOfOdds * (2 * start + (numberOfOdds - 1) * 2)
/ 2;

cout << "Sum of odd numbers between 10 and 50 is: " << sum
<< endl;

return 0;
}

Output: Sum of odd numbers between 10 and 50 is: 600

2 2 2
171. 1 + 2 + 3 = ?
#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 1; i <= 3; i++) {

Code With Redoy Interactive Coding PDF


137

sum += i * i;
}
cout << "Sum of squares of numbers from 1 to 3: " << sum
<< endl;
return 0;
}

2 2 2 2
172. 1 + 2 + 3 + ……………………. + 𝑁 = ?
#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter a value for N: ";
cin >> N;

int sum = 0;
for (int i = 1; i <= N; i++) {
sum += i * i;
}
cout << "Sum of squares of numbers from 1 to " << N << ":
" << sum << endl;
return 0;
}

173. 1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n = ?


Test Data:
Input the number of terms: 5
Expected Output:
1/1 + 1/2 + 1/3 + 1/4 + 1/5 +

Code With Redoy Interactive Coding PDF


138

Sum of Series up to 5 terms: 2.283334


#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter a value for N: ";
cin >> N;

double sum = 0.0;


for (int i = 1; i <= N; i++) {
sum += 1.0 / i;
}
cout << "Sum of reciprocals from 1 to " << N << ": " <<
sum << endl;
return 0;
}

174. 9 + 99 + 999 + 9999 ……. =?


Test Data:
Input the number of terms:5
Expected Output:
9 99 999 9999 99999
The summation of the series = 111105
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;

int sum = 0;

Code With Redoy Interactive Coding PDF


139

int term = 9;
for (int i = 1; i <= n; i++) {
sum += term;
term = term * 10 + 9;
}
cout << "Sum of the series: " << sum << endl;
return 0;
}

175. Find the sum of the first 10 terms of the arithmetic series: 3, 7,
11, 15, ...
#include <iostream>
using namespace std;

int main() {
int firstTerm = 3;
int commonDifference = 4;
int n = 10; // Number of terms

int sum = (n * (2 * firstTerm + (n - 1) *


commonDifference)) / 2;
cout << "Sum of the first 10 terms: " << sum << endl;
return 0;
}

Output: Sum of the first 10 terms: 210

176. Find the sum of the first 5 terms of the geometric series: 2, 4, 8,
16, ...
#include <iostream>
#include<math.h>
using namespace std;

Code With Redoy Interactive Coding PDF


140

int main() {
int firstTerm = 2;
int commonRatio = 2;
int n = 5; // Number of terms

int sum = firstTerm * (pow(commonRatio, n) - 1) /


(commonRatio - 1);
cout << "Sum of the first 5 terms: " << sum << endl;
return 0;
}

Output: Sum of the first 5 terms: 62

177. Find the nth term of the arithmetic series: 5, 8, 11, 14, ...
#include <iostream>
using namespace std;

int main() {
int firstTerm = 5;
int commonDifference = 3;
int n;

cout << "Enter the value of n: ";


cin >> n;

int nthTerm = firstTerm + (n - 1) * commonDifference;


cout << "The nth term of the series: " << nthTerm << endl;
return 0;
}

Output: The nth term of the series: 17

Code With Redoy Interactive Coding PDF


141

178. Find the sum of the first 12 terms of the series: 1/2, 2/3, 3/4, 4/5,
...
#include <iostream>
using namespace std;

int main() {
int n = 12; // Number of terms

double sum = 0.0;


for (int i = 1; i <= n; i++) {
sum += static_cast<double>(i) / (i + 1);
}
cout << "Sum of the first 12 terms: " << sum << endl;
return 0;
}

Output: Sum of the first 12 terms: 9.81987

179. Find the sum of the infinite series: 1/2 + 1/4 + 1/8 + 1/16 + ...
#include <iostream>
using namespace std;

int main() {
double sum = 0.0;
double term = 1.0;
int n = 10; // You can change the value of n for more
accuracy

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


sum += term;
term /= 2;
}
cout << "Sum of the series: " << sum << endl;
return 0;
}

Code With Redoy Interactive Coding PDF


142

Output: Sum of the series: 1.99805

180. Find the sum of the first 10 terms of the series: 1 + 4 + 9 + 16 + ...
#include <iostream>
using namespace std;

int main() {
int sum = 0;
int n = 10; // Number of terms

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


sum += i * i;
}
cout << "Sum of the first 10 terms: " << sum << endl;
return 0;
}

Output: Sum of the first 10 terms: 385

181. Find the nth term of the geometric series: 3, 6, 12, 24, ...
#include <iostream>
#include<math.h>
using namespace std;

int main() {
int firstTerm = 3;
int commonRatio = 2;
int n;

cout << "Enter the value of n: ";


cin >> n;

int nthTerm = firstTerm * pow(commonRatio, n - 1);


cout << "The nth term of the series: " << nthTerm << endl;
return 0;

Code With Redoy Interactive Coding PDF


143

Output: The nth term of the series: 48

182. Find the sum of the first 20 terms of the series: 2, 4, 6, 8, 10, ...
#include <iostream>
using namespace std;

int main() {
int sum = 0;
int n = 20; // Number of terms

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


sum += 2 * i;
}
cout << "Sum of the first 20 terms: " << sum << endl;
return 0;
}

Output: Sum of the first 20 terms: 420

183. Find the sum of the first 6 terms of the series: -1, -3, -5, -7, ...
#include <iostream>
using namespace std;

int main() {
int sum = 0;
int n = 6; // Number of terms

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


sum += -2 * i + 1;
}
cout << "Sum of the first 6 terms: " << sum << endl;
return 0;
}

Code With Redoy Interactive Coding PDF


144

Output: Sum of the first 6 terms: -36

184. Find the sum of the infinite series: 1 + 1/2 + 1/4 + 1/8 + ...
#include <iostream>
using namespace std;

int main() {
double a = 1.0; // First term
double r = 1.0 / 2.0; // Common ratio

double sum = a / (1 - r);

cout << "Sum of the infinite series: " << sum << endl;

return 0;
}

Output: Sum of the infinite series: 2

Code With Redoy Interactive Coding PDF


145

String (36 Problems)

185. Write a program to find the length of a string.


#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

int length = strlen(str);

cout << "Length of the string: " << length << endl;

return 0;
}

186. Write a program to copy one string to another string.


#include <iostream>
#include <cstring>
using namespace std;

int main() {
char source[100], destination[100];

cout << "Enter a string to copy: ";


cin.getline(source, 100);

strcpy(destination, source);

Code With Redoy Interactive Coding PDF


146

cout << "Copied string: " << destination << endl;

return 0;
}

187. Write a program to concatenate two strings.


#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str1[100], str2[100];

cout << "Enter the first string: ";


cin.getline(str1, 100);

cout << "Enter the second string: ";


cin.getline(str2, 100);

strcat(str1, str2);

cout << "Concatenated string: " << str1 << endl;

return 0;
}

188. Write a program to compare two strings.


#include <iostream>
#include <cstring>
using namespace std;

Code With Redoy Interactive Coding PDF


147

int main() {
char str1[100], str2[100];

cout << "Enter the first string: ";


cin.getline(str1, 100);

cout << "Enter the second string: ";


cin.getline(str2, 100);

int result = strcmp(str1, str2);

if (result == 0) {
cout << "Both strings are equal." << endl;
} else if (result < 0) {
cout << "String 1 is less than String 2." << endl;
} else {
cout << "String 1 is greater than String 2." << endl;
}

return 0;
}

189. Write a program to convert lowercase string to uppercase and


uppercase string to lowercase string.
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

Code With Redoy Interactive Coding PDF


148

for (int i = 0; str[i]; i++) {


if (islower(str[i])) {
str[i] = toupper(str[i]);
} else if (isupper(str[i])) {
str[i] = tolower(str[i]);
}
}

cout << "Converted string: " << str << endl;

return 0;
}

190. Write a program to toggle the case of each character of a string.


#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

for (int i = 0; str[i] != '\0'; i++) {


if (islower(str[i])) {
str[i] = toupper(str[i]);
} else if (isupper(str[i])) {
str[i] = tolower(str[i]);
}
}

cout << "Toggled case string: " << str << endl;

Code With Redoy Interactive Coding PDF


149

return 0;
}

191. Write a program to find the total number of alphabets, digits, or


special characters in a string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

int alphabets = 0, digits = 0, specialChars = 0;

for (int i = 0; str[i] != '\0'; i++) {


if (isalpha(str[i])) {
alphabets++;
} else if (isdigit(str[i])) {
digits++;
} else {
specialChars++;
}
}

cout << "Alphabets: " << alphabets << endl;


cout << "Digits: " << digits << endl;
cout << "Special Characters: " << specialChars << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


150

192. Write a program to count the total number of vowels, consonants,


and words in a string.
#include <iostream>
#include <cstring>
using namespace std;

bool isVowel(char c) {
c = tolower(c);
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c
== 'u');
}

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

int vowels = 0, consonants = 0, words = 1; // Initialize


words to 1 to account for the first word.

for (int i = 0; str[i] != '\0'; i++) {


if (isalpha(str[i])) {
if (isVowel(str[i])) {
vowels++;
} else {
consonants++;
}
} else if (isspace(str[i])) {
words++;
}
}

Code With Redoy Interactive Coding PDF


151

cout << "Vowels: " << vowels << endl;


cout << "Consonants: " << consonants << endl;
cout << "Words: " << words << endl;

return 0;
}

193. Write a program to check whether a string is a palindrome or not.


#include <iostream>
#include <cstring>
using namespace std;

bool isPalindrome(char str[]) {


int left = 0;
int right = strlen(str) - 1;

while (left < right) {


if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

if (isPalindrome(str)) {
cout << "The string is a palindrome." << endl;

Code With Redoy Interactive Coding PDF


152

} else {
cout << "The string is not a palindrome." << endl;
}

return 0;
}

194. Write a program to reverse the order of words in a given string.


#include <iostream>
#include <cstring>
using namespace std;

void reverseWords(char str[]) {


int start = 0;
int end = strlen(str) - 1;

// Reverse the entire string.


while (start < end) {
swap(str[start], str[end]);
start++;
end--;
}

// Reverse each word in the string.


int wordStart = 0;
for (int i = 0; i <= strlen(str); i++) {
if (str[i] == ' ' || str[i] == '\0') {
int wordEnd = i - 1;
while (wordStart < wordEnd) {
swap(str[wordStart], str[wordEnd]);
wordStart++;
wordEnd--;
}
wordStart = i + 1;

Code With Redoy Interactive Coding PDF


153

}
}
}

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

reverseWords(str);

cout << "Reversed string: " << str << endl;

return 0;
}

195. Write a program to find the first and last occurrence of a character
in a given string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target;

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a character to search: ";


cin >> target;

int firstOccurrence = -1, lastOccurrence = -1;

Code With Redoy Interactive Coding PDF


154

for (int i = 0; str[i] != '\0'; i++) {


if (str[i] == target) {
if (firstOccurrence == -1) {
firstOccurrence = i;
}
lastOccurrence = i;
}
}

if (firstOccurrence != -1) {
cout << "First occurrence of '" << target << "' at
index: " << firstOccurrence << endl;
cout << "Last occurrence of '" << target << "' at
index: " << lastOccurrence << endl;
} else {
cout << "Character '" << target << "' not found in the
string." << endl;
}

return 0;
}

196. Write a program to search all occurrences of a character in a


given string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target;

cout << "Enter a string: ";

Code With Redoy Interactive Coding PDF


155

cin.getline(str, 100);

cout << "Enter a character to search: ";


cin >> target;

cout << "Occurrences of '" << target << "': ";

for (int i = 0; str[i] != '\0'; i++) {


if (str[i] == target) {
cout << i << " ";
}
}

cout << endl;

return 0;
}

197. Write a program to count occurrences of a character in a given


string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target;

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a character to count: ";


cin >> target;

Code With Redoy Interactive Coding PDF


156

int count = 0;

for (int i = 0; str[i] != '\0'; i++) {


if (str[i] == target) {
count++;
}
}

cout << "Occurrences of '" << target << "': " << count <<
endl;

return 0;
}

198. Write a program to find the highest and lowest frequency


character in a string.
#include <iostream>
#include <cstring>
#include <map>
using namespace std;

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

map<char, int> freq;

for (int i = 0; str[i] != '\0'; i++) {


if (isalpha(str[i])) {
freq[str[i]]++;
}
}

Code With Redoy Interactive Coding PDF


157

char highestFreqChar = '\0', lowestFreqChar = '\0';


int highestFreq = 0, lowestFreq = INT_MAX;

for (auto it = freq.begin(); it != freq.end(); it++) {


if (it->second > highestFreq) {
highestFreq = it->second;
highestFreqChar = it->first;
}
if (it->second < lowestFreq) {
lowestFreq = it->second;
lowestFreqChar = it->first;
}
}

cout << "Highest frequency character: " << highestFreqChar


<< " (" << highestFreq << " times)" << endl;
cout << "Lowest frequency character: " << lowestFreqChar
<< " (" << lowestFreq << " times)" << endl;

return 0;
}

199. Write a program to count the frequency of each character in a


string.
#include <iostream>
#include <cstring>
#include <map>
using namespace std;

int main() {
char str[100];

cout << "Enter a string: ";

Code With Redoy Interactive Coding PDF


158

cin.getline(str, 100);

map<char, int> freq;

for (int i = 0; str[i] != '\0'; i++) {


if (isalpha(str[i])) {
freq[str[i]]++;
}
}

cout << "Character frequencies: " << endl;

for (auto it = freq.begin(); it != freq.end(); it++) {


cout << "'" << it->first << "': " << it->second << "
times" << endl;
}

return 0;
}

200. Write a program to remove the first occurrence of a character


from a string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target;

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a character to remove: ";

Code With Redoy Interactive Coding PDF


159

cin >> target;

bool removed = false;

for (int i = 0; str[i] != '\0'; i++) {


if (str[i] == target && !removed) {
for (int j = i; str[j] != '\0'; j++) {
str[j] = str[j + 1];
}
removed = true;
}
}

cout << "String after removing the first occurrence of '"


<< target << "': " << str << endl;

return 0;
}

201. Write a program to remove the last occurrence of a character from


a string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target;

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a character to remove: ";


cin >> target;

Code With Redoy Interactive Coding PDF


160

int lastOccurrence = -1;

for (int i = 0; str[i] != '\0'; i++) {


if (str[i] == target) {
lastOccurrence = i;
}
}

if (lastOccurrence != -1) {
for (int j = lastOccurrence; str[j] != '\0'; j++) {
str[j] = str[j + 1];
}
}

cout << "String after removing the last occurrence of '"


<< target << "': " << str << endl;

return 0;
}

202. Write a program to remove all occurrences of a character from a


string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target;

cout << "Enter a string: ";


cin.getline(str, 100);

Code With Redoy Interactive Coding PDF


161

cout << "Enter a character to remove: ";


cin >> target;

int length = strlen(str);


int j = 0;

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


if (str[i] != target) {
str[j] = str[i];
j++;
}
}
str[j] = '\0';

cout << "String after removing all occurrences of '" <<


target << "': " << str << endl;

return 0;
}

203. Write a program to remove all repeated characters from a given


string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

int length = strlen(str);


bool unique[256] = {false}; // Assuming ASCII characters.

Code With Redoy Interactive Coding PDF


162

int j = 0;
for (int i = 0; i < length; i++) {
if (!unique[str[i]]) {
str[j] = str[i];
j++;
unique[str[i]] = true;
}
}
str[j] = '\0';

cout << "String after removing repeated characters: " <<


str << endl;

return 0;
}

204. Write a program to replace the first occurrence of a character with


another in a string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target, replacement;

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a character to replace: ";


cin >> target;

cout << "Enter a replacement character: ";

Code With Redoy Interactive Coding PDF


163

cin >> replacement;

int length = strlen(str);

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


if (str[i] == target) {
str[i] = replacement;
break; // Replace only the first occurrence.
}
}

cout << "String after replacement: " << str << endl;

return 0;
}

205. Write a program to replace the last occurrence of a character with


another in a string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target, replacement;

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a character to replace: ";


cin >> target;

cout << "Enter a replacement character: ";


cin >> replacement;

Code With Redoy Interactive Coding PDF


164

int length = strlen(str);


int lastOccurrence = -1;

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


if (str[i] == target) {
lastOccurrence = i;
}
}

if (lastOccurrence != -1) {
str[lastOccurrence] = replacement;
}

cout << "String after replacement: " << str << endl;

return 0;
}

206. Write a program to replace all occurrences of a character with


another in a string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char target, replacement;

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a character to replace: ";


cin >> target;

Code With Redoy Interactive Coding PDF


165

cout << "Enter a replacement character: ";


cin >> replacement;

int length = strlen(str);

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


if (str[i] == target) {
str[i] = replacement;
}
}

cout << "String after replacement: " << str << endl;

return 0;
}

207. Write a program to find the first and last occurrence of a word in
a given string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char word[20];

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a word to search: ";


cin >> word;

int length = strlen(str);

Code With Redoy Interactive Coding PDF


166

int wordLength = strlen(word);


int firstOccurrence = -1, lastOccurrence = -1;

for (int i = 0; i <= length - wordLength; i++) {


if (strncmp(str + i, word, wordLength) == 0) {
if (firstOccurrence == -1) {
firstOccurrence = i;
}
lastOccurrence = i;
}
}

if (firstOccurrence != -1) {
cout << "First occurrence of '" << word << "' at
index: " << firstOccurrence << endl;
cout << "Last occurrence of '" << word << "' at index:
" << lastOccurrence << endl;
} else {
cout << "Word '" << word << "' not found in the
string." << endl;
}

return 0;
}

208. Write a program to search all occurrences of a word in a given


string.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char word[20];

Code With Redoy Interactive Coding PDF


167

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a word to search: ";


cin >> word;

int length = strlen(str);


int wordLength = strlen(word);

cout << "Occurrences of '" << word << "': ";

for (int i = 0; i <= length - wordLength; i++) {


if (strncmp(str + i, word, wordLength) == 0) {
cout << i << " ";
}
}

cout << endl;

return 0;
}

209. Write a program to count occurrences of a word in a given string.


#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
char word[20];

cout << "Enter a string: ";


cin.getline(str, 100);

Code With Redoy Interactive Coding PDF


168

cout << "Enter a word to count: ";


cin >> word;

int length = strlen(str);


int wordLength = strlen(word);
int count = 0;

for (int i = 0; i <= length - wordLength; i++) {


if (strncmp(str + i, word, wordLength) == 0) {
count++;
}
}

cout << "Occurrences of '" << word << "': " << count <<
endl;

return 0;
}

210. Write a program to remove the first occurrence of a word from a


string.
#include <iostream>
#include <cstring>
using namespace std;

void removeFirstWord(char str[], const char word[]) {


int length = strlen(str);
int wordLength = strlen(word);

for (int i = 0; i <= length - wordLength; i++) {


if (strncmp(str + i, word, wordLength) == 0) {
for (int j = i; j <= length - wordLength; j++) {
str[j] = str[j + wordLength];

Code With Redoy Interactive Coding PDF


169

}
break;
}
}
}

int main() {
char str[100];
char word[20];

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a word to remove: ";


cin >> word;

removeFirstWord(str, word);

cout << "String after removing the first occurrence of '"


<< word << "': " << str << endl;

return 0;
}

211. Write a program to remove the last occurrence of a word in a


given string.
#include <iostream>
#include <cstring>
using namespace std;

void removeLastWord(char str[], const char word[]) {


int length = strlen(str);
int wordLength = strlen(word);
int lastOccurrence = -1;

Code With Redoy Interactive Coding PDF


170

for (int i = 0; i <= length - wordLength; i++) {


if (strncmp(str + i, word, wordLength) == 0) {
lastOccurrence = i;
}
}

if (lastOccurrence != -1) {
for (int j = lastOccurrence; j <= length - wordLength;
j++) {
str[j] = str[j + wordLength];
}
}
}

int main() {
char str[100];
char word[20];

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a word to remove: ";


cin >> word;

removeLastWord(str, word);

cout << "String after removing the last occurrence of '"


<< word << "': " << str << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


171

212. Write a program to remove all occurrences of a word in a given


string.
#include <iostream>
#include <cstring>
using namespace std;

void removeAllOccurrences(char str[], const char word[]) {


int length = strlen(str);
int wordLength = strlen(word);
int i = 0, j;

while (i <= length - wordLength) {


if (strncmp(str + i, word, wordLength) == 0) {
for (j = i; j <= length - wordLength; j++) {
str[j] = str[j + wordLength];
}
length -= wordLength;
} else {
i++;
}
}
}

int main() {
char str[100];
char word[20];

cout << "Enter a string: ";


cin.getline(str, 100);

cout << "Enter a word to remove: ";


cin >> word;

removeAllOccurrences(str, word);

cout << "String after removing all occurrences of '" <<


word << "': " << str << endl;

Code With Redoy Interactive Coding PDF


172

return 0;
}

213. Write a program to trim leading white space characters from a


given string.
#include <iostream>
#include <cstring>
using namespace std;

void trimLeadingWhitespace(char str[]) {


int length = strlen(str);
int i = 0;

while (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')


{
i++;
}

if (i > 0) {
for (int j = 0; j <= length - i; j++) {
str[j] = str[j + i];
}
}
}

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

trimLeadingWhitespace(str);

Code With Redoy Interactive Coding PDF


173

cout << "String after trimming leading white space


characters: " << str << endl;

return 0;
}

214. Write a program to trim trailing white space characters from a


given string.
#include <iostream>
#include <cstring>
using namespace std;

void trimTrailingWhitespace(char str[]) {


int length = strlen(str);
int i = length - 1;

while (i >= 0 && (str[i] == ' ' || str[i] == '\t' ||


str[i] == '\n')) {
str[i] = '\0';
i--;
}
}

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

trimTrailingWhitespace(str);

cout << "String after trimming trailing white space


characters: " << str << endl;

Code With Redoy Interactive Coding PDF


174

return 0;
}

215. Write a program to trim both leading and trailing white space
characters from a given string.
#include <iostream>
#include <cstring>
using namespace std;

void trimWhitespace(char str[]) {


int length = strlen(str);
int leadingSpaces = 0;
int trailingSpaces = length - 1;

// Count leading spaces.


while (leadingSpaces < length && (str[leadingSpaces] == '
' || str[leadingSpaces] == '\t' || str[leadingSpaces] ==
'\n')) {
leadingSpaces++;
}

// Count trailing spaces.


while (trailingSpaces >= 0 && (str[trailingSpaces] == ' '
|| str[trailingSpaces] == '\t' || str[trailingSpaces] ==
'\n')) {
str[trailingSpaces] = '\0';
trailingSpaces--;
}

// Shift the remaining characters to the beginning of the


string.
int i, j;
for (i = 0, j = leadingSpaces; j <= trailingSpaces; i++,
j++) {

Code With Redoy Interactive Coding PDF


175

str[i] = str[j];
}
str[i] = '\0';
}

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

trimWhitespace(str);

cout << "String after trimming leading and trailing white


space characters: " << str << endl;

return 0;
}

216. Write a program to remove all extra blank spaces from a given
string.
#include <iostream>
#include <cstring>
using namespace std;

void removeExtraSpaces(char str[]) {


int length = strlen(str);
bool inSpace = false;
int j = 0;

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


if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
{
if (!inSpace) {

Code With Redoy Interactive Coding PDF


176

str[j] = ' ';


j++;
inSpace = true;
}
} else {
str[j] = str[i];
j++;
inSpace = false;
}
}

// Remove trailing spaces, if any.


if (j > 0 && str[j - 1] == ' ') {
j--;
}

str[j] = '\0';
}

int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

removeExtraSpaces(str);

cout << "String after removing extra blank spaces: " <<
str << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


177

217.
Given a string S. Print the origin string after replacing the following:
● Replace every comma character ',' with a space character.
● Replace every capital character in S with its respective small
character and Vice Versa.

Input Expected Output

happy,NewYear,enjoy HAPPY nEWyEAR ENJOY

#include <iostream>
#include <cctype> // For isupper and islower
using namespace std;

int main() {
string s;
getline(cin, s); // Read input as a string

string emptyS = "";

for (char i : s) {
if (i == ',') {
emptyS += " ";
} else if (isupper(i)) {
emptyS += tolower(i);
} else if (islower(i)) {
emptyS += toupper(i);
}
}

cout << emptyS << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


178

218. Given a string S. Print the number of times that "EGYPT" word
can be formed from S's characters.
Note: Case of the letters doesn't matter. For example: "Egypt", "egypt" and
"eGyPt" are the same.

Input Expected Output

EgYpTaz 1

pemigdbeigyypetet 2

#include <iostream>
#include <string>
#include <algorithm> // For min
#include <climits> // For INT_MAX
using namespace std;

int main() {
string s;
getline(cin, s); // Read input as a string

// Convert the string to lowercase


transform(s.begin(), s.end(), s.begin(), ::tolower);

int minCount = INT_MAX; // Initialize minCount with a


large value

for (char c : "egypt") {


int count = std::count(s.begin(), s.end(), c); // Use
std::count
minCount = min(minCount, count);
}

cout << minCount << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


179

219. Given a string S. Print S after replacing every sub-string that is


equal to "EGYPT" with space.

Input Output
BRITISHEGYPTGHANA BRITISH GHANA
ITALYKOREAEGYPTEGYPTAL ITALYKOREA ALGERIA Z
GERIAEGYPTZ
#include <iostream>
#include <string>
using namespace std;

int main() {
string s;
getline(cin, s); // Read input as a string

string subString = "EGYPT";

size_t found = s.find(subString);

while (found != string::npos) {


s.replace(found, subString.length(), " ");
found = s.find(subString);
}

cout << s << endl;

return 0;
}

220. Given a string S. Print the summation of its digits. It's guaranteed
that S contains only digits from 0 to 9.

Code With Redoy Interactive Coding PDF


180

Input Output
351 9
123 6
#include <iostream>
#include <string>
using namespace std;

int main() {
string input;
getline(cin, input); // Read input as a string

int sum = 0;

for (char c : input) {


if (isdigit(c)) {
int digit = c - '0'; // Convert character to
integer
sum += digit;
}
}

cout << sum << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


181

Function (11 Problems)

221. Write a program to calculate the sum of two numbers using a


user-defined function.
#include<iostream>
using namespace std;
void sum(int a, int b)
{
int total;
total = a+b;
cout<<total<<endl;
}
int main(){
sum(10, 20);
return 0;
}

222. Write a program to calculate the sum of two numbers using a


user-defined function [Input must be taken from user].
#include<iostream>
using namespace std;
void output()
{
int num1, num2, total;
cout<<"Enter two numbers: ";
cin>>num1>>num2;

total = num1 + num2;

cout<<total<<endl;
}

int main(){
output();

Code With Redoy Interactive Coding PDF


182

return 0;
}

223. Write a program to make a calculator using a user-defined


function.
#include <iostream>
using namespace std;

// Function to perform addition


double add(double a, double b) {
return a + b;
}

// Function to perform subtraction


double subtract(double a, double b) {
return a - b;
}

// Function to perform multiplication


double multiply(double a, double b) {
return a * b;
}

// Function to perform division


double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
cout << "Error! Division by zero." << endl;
return 0;
}
}

int main() {
double num1, num2;

Code With Redoy Interactive Coding PDF


183

char operation;

cout << "Enter two numbers: ";


cin >> num1 >> num2;

cout << "Enter an operation (+, -, *, /): ";


cin >> operation;

double result;

switch (operation) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
result = divide(num1, num2);
break;
default:
cout << "Invalid operation." << endl;
return 1;
}

cout << "Result: " << result << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


184

224. Write a program to find a cube of any number using a


user-defined function.
#include <iostream>
using namespace std;

// Function to calculate the cube of a number


double cube(double num) {
return num * num * num;
}

int main() {
double number;

cout << "Enter a number: ";


cin >> number;

double result = cube(number);

cout << "Cube of " << number << " is " << result << endl;

return 0;
}

225. Write a program to find a circle's diameter, circumference, and


area using a user-defined function.
#include <iostream>
using namespace std;

const double PI = 3.14159265359;

// Function to calculate diameter


double calculateDiameter(double radius) {
return 2 * radius;
}

Code With Redoy Interactive Coding PDF


185

// Function to calculate circumference


double calculateCircumference(double radius) {
return 2 * PI * radius;
}

// Function to calculate area


double calculateArea(double radius) {
return PI * radius * radius;
}

int main() {
double radius;

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


cin >> radius;

double diameter = calculateDiameter(radius);


double circumference = calculateCircumference(radius);
double area = calculateArea(radius);

cout << "Diameter: " << diameter << endl;


cout << "Circumference: " << circumference << endl;
cout << "Area: " << area << endl;

return 0;
}

226. Write a program to find maximum and minimum numbers


between two numbers using a user-defined function.
#include <iostream>
using namespace std;

// Function to find maximum of two numbers

Code With Redoy Interactive Coding PDF


186

double findMax(double a, double b) {


return (a > b) ? a : b;
}

// Function to find minimum of two numbers


double findMin(double a, double b) {
return (a < b) ? a : b;
}

int main() {
double num1, num2;

cout << "Enter two numbers: ";


cin >> num1 >> num2;

double maximum = findMax(num1, num2);


double minimum = findMin(num1, num2);

cout << "Maximum: " << maximum << endl;


cout << "Minimum: " << minimum << endl;

return 0;
}

227. Write a program to check whether a number is even or odd using


a user-defined function.
#include <iostream>
using namespace std;

// Function to check if a number is even


bool isEven(int num) {
return (num % 2 == 0);
}

Code With Redoy Interactive Coding PDF


187

int main() {
int number;

cout << "Enter a number: ";


cin >> number;

if (isEven(number)) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}

return 0;
}

228. Write a program to check whether a number is a prime,


Armstrong, or perfect number using a user-defined function.[Must
be used 3 individual functions to check prime, Armstrong, or perfect
number. ].
#include <iostream>
#include <cmath>
using namespace std;

// Function to check if a number is prime


bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;

Code With Redoy Interactive Coding PDF


188

// Function to check if a number is Armstrong


bool isArmstrong(int num) {
int originalNum = num;
int sum = 0;
int numDigits = 0;

while (num > 0) {


numDigits++;
num /= 10;
}

num = originalNum;
while (num > 0) {
int digit = num % 10;
sum += pow(digit, numDigits);
num /= 10;
}

return (sum == originalNum);


}

// Function to check if a number is perfect


bool isPerfect(int num) {
int sum = 1;

for (int i = 2; i * i <= num; i++) {


if (num % i == 0) {
sum += i;
if (i != num / i) {
sum += num / i;
}
}
}

return (sum == num);

Code With Redoy Interactive Coding PDF


189

int main() {
int start, end;

cout << "Enter the start of the interval: ";


cin >> start;

cout << "Enter the end of the interval: ";


cin >> end;

cout << "Prime numbers in the interval: ";


for (int i = start; i <= end; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
cout << endl;

cout << "Armstrong numbers in the interval: ";


for (int i = start; i <= end; i++) {
if (isArmstrong(i)) {
cout << i << " ";
}
}
cout << endl;

cout << "Perfect numbers in the interval: ";


for (int i = start; i <= end; i++) {
if (isPerfect(i)) {
cout << i << " ";
}
}
cout << endl;

return 0;
}

Code With Redoy Interactive Coding PDF


190

229. Write a program to find all prime, strong, and Armstrong


numbers between a given interval. [Must be used 3 individual
functions for prime, strong, and Armstrong numbers. ].
#include <iostream>
#include <cmath>
using namespace std;

// Function to check if a number is prime


bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

// Function to check if a number is strong


bool isStrong(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
int digit = num % 10;
int factorial = 1;
for (int i = 1; i <= digit; i++) {
factorial *= i;
}
sum += factorial;
num /= 10;
}

Code With Redoy Interactive Coding PDF


191

return sum == originalNum;


}

// Function to check if a number is Armstrong


bool isArmstrong(int num) {
int originalNum = num;
int sum = 0;
int numDigits = 0;

while (num > 0) {


numDigits++;
num /= 10;
}

num = originalNum;
while (num > 0) {
int digit = num % 10;
sum += pow(digit, numDigits);
num /= 10;
}

return (sum == originalNum);


}

int main() {
int start, end;

cout << "Enter the start of the interval: ";


cin >> start;

cout << "Enter the end of the interval: ";


cin >> end;

cout << "Prime numbers in the interval: ";


for (int i = start; i <= end; i++) {
if (isPrime(i)) {
cout << i << " ";

Code With Redoy Interactive Coding PDF


192

}
}
cout << endl;

cout << "Strong numbers in the interval: ";


for (int i = start; i <= end; i++) {
if (isStrong(i)) {
cout << i << " ";
}
}
cout << endl;

cout << "Armstrong numbers in the interval: ";


for (int i = start; i <= end; i++) {
if (isArmstrong(i)) {
cout << i << " ";
}
}
cout << endl;

return 0;
}

230. Write a program to add two matrices or 2D arrays using a


function.
#include <iostream>
using namespace std;

const int MAX_ROWS = 100;


const int MAX_COLS = 100;

// Function to add two matrices

Code With Redoy Interactive Coding PDF


193

void addMatrices(int mat1[MAX_ROWS][MAX_COLS], int


mat2[MAX_ROWS][MAX_COLS], int result[MAX_ROWS][MAX_COLS], 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 rows, cols;

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


cin >> rows;
cout << "Enter the number of columns: ";
cin >> cols;

int mat1[MAX_ROWS][MAX_COLS];
int mat2[MAX_ROWS][MAX_COLS];
int result[MAX_ROWS][MAX_COLS];

cout << "Enter elements of the first matrix:" << endl;


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> mat1[i][j];
}
}

cout << "Enter elements of the second matrix:" << endl;


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> mat2[i][j];
}
}

addMatrices(mat1, mat2, result, rows, cols);

Code With Redoy Interactive Coding PDF


194

cout << "Sum of the matrices:" << endl;


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}

return 0;
}

231. Write a program to do addition, subtraction, multiplication, and


division between two matrices or 2D arrays using a function. [Must
be used 4 functions for addition, subtraction, multiplication, and
division].
#include <iostream>
using namespace std;

const int MAX_ROWS = 100;


const int MAX_COLS = 100;

// Function to add two matrices


void addMatrices(int mat1[MAX_ROWS][MAX_COLS], int
mat2[MAX_ROWS][MAX_COLS], int result[MAX_ROWS][MAX_COLS], 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];
}
}
}

// Function to subtract two matrices

Code With Redoy Interactive Coding PDF


195

void subtractMatrices(int mat1[MAX_ROWS][MAX_COLS], int


mat2[MAX_ROWS][MAX_COLS], int result[MAX_ROWS][MAX_COLS], 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];
}
}
}

// Function to multiply two matrices


void multiplyMatrices(int mat1[MAX_ROWS][MAX_COLS], int
mat2[MAX_ROWS][MAX_COLS], int result[MAX_ROWS][MAX_COLS], int
rows1, int cols1, int cols2) {
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

// Function to divide two matrices (element-wise division)


void divideMatrices(int mat1[MAX_ROWS][MAX_COLS], int
mat2[MAX_ROWS][MAX_COLS], int result[MAX_ROWS][MAX_COLS], int
rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (mat2[i][j] != 0) {
result[i][j] = mat1[i][j] / mat2[i][j];
} else {
// Handle division by zero
cout << "Division by zero encountered." <<
endl;
return;

Code With Redoy Interactive Coding PDF


196

}
}
}
}

int main() {
int rows1, cols1, rows2, cols2;

cout << "Enter the number of rows for matrix 1: ";


cin >> rows1;
cout << "Enter the number of columns for matrix 1: ";
cin >> cols1;

int mat1[MAX_ROWS][MAX_COLS];

cout << "Enter elements of matrix 1:" << endl;


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
cin >> mat1[i][j];
}
}

cout << "Enter the number of rows for matrix 2: ";


cin >> rows2;
cout << "Enter the number of columns for matrix 2: ";
cin >> cols2;

int mat2[MAX_ROWS][MAX_COLS];

cout << "Enter elements of matrix 2:" << endl;


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
cin >> mat2[i][j];
}
}

if (rows1 != rows2 || cols1 != cols2) {

Code With Redoy Interactive Coding PDF


197

cout << "Matrix dimensions do not match for addition,


subtraction, multiplication, and division." << endl;
return 1;
}

int result[MAX_ROWS][MAX_COLS];

// Perform addition
addMatrices(mat1, mat2, result, rows1, cols1);

cout << "Sum of the matrices:" << endl;


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}

// Perform subtraction
subtractMatrices(mat1, mat2, result, rows1, cols1);

cout << "Difference of the matrices:" << endl;


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}

// Perform multiplication
multiplyMatrices(mat1, mat2, result, rows1, cols1, cols2);

cout << "Product of the matrices:" << endl;


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
cout << result[i][j] << " ";
}

Code With Redoy Interactive Coding PDF


198

cout << endl;


}

// Perform division
divideMatrices(mat1, mat2, result, rows1, cols1);

cout << "Division of the matrices:" << endl;


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF


199

Pointer (6 Problems)

232. Write a program to create, initialize and use pointers.


#include <iostream>
using namespace std;

int main() {
int num = 42;
int* ptr = &num;

cout << "Value of num: " << num << endl;


cout << "Address of num: " << &num << endl;
cout << "Value of ptr (address of num): " << ptr << endl;
cout << "Value pointed to by ptr: " << *ptr << endl;

return 0;
}

233. Write a program to add two numbers using pointers.


#include <iostream>
using namespace std;

int main() {
int num1 = 10, num2 = 20;
int* ptr1 = &num1;
int* ptr2 = &num2;

int sum = *ptr1 + *ptr2;

cout << "Sum of " << *ptr1 << " and " << *ptr2 << " is: "
<< sum << endl;

return 0;

Code With Redoy Interactive Coding PDF


200

234. Write a program to swap two numbers using pointers.


#include <iostream>
using namespace std;

void swapNumbers(int* a, int* b) {


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

int main() {
int num1 = 10, num2 = 20;

cout << "Before swapping: num1 = " << num1 << ", num2 = "
<< num2 << endl;

swapNumbers(&num1, &num2);

cout << "After swapping: num1 = " << num1 << ", num2 = "
<< num2 << endl;

return 0;
}

235. Write a program to input and print array elements using a pointer.
#include <iostream>
using namespace std;

int main() {

Code With Redoy Interactive Coding PDF


201

const int size = 5;


int arr[size];

cout << "Enter " << size << " integers:" << endl;

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


cin >> arr[i];
}

int* ptr = arr;

cout << "Array elements entered: ";


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

return 0;
}

236. Write a program to copy one array to another using a pointer.


#include <iostream>
using namespace std;

int main() {
const int size = 5;
int source[size] = {1, 2, 3, 4, 5};
int destination[size];

int* srcPtr = source;


int* destPtr = destination;

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

Code With Redoy Interactive Coding PDF


202

*destPtr = *srcPtr;
srcPtr++;
destPtr++;
}

cout << "Copied array elements: ";


destPtr = destination; // Reset the pointer to the
beginning of the destination array
for (int i = 0; i < size; i++) {
cout << *destPtr << " ";
destPtr++;
}
cout << endl;

return 0;
}

237. Write a program to add and multiply two matrices using pointers.
#include <iostream>
using namespace std;

const int ROWS = 2;


const int COLS = 2;

// Function to add two matrices using pointers


void addMatrices(int mat1[ROWS][COLS], int mat2[ROWS][COLS],
int result[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
*(*(result + i) + j) = *(*(mat1 + i) + j) +
*(*(mat2 + i) + j);
}
}
}

Code With Redoy Interactive Coding PDF


203

// Function to multiply two matrices using pointers


void multiplyMatrices(int mat1[ROWS][COLS], int
mat2[ROWS][COLS], int result[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
*(*(result + i) + j) = 0;
for (int k = 0; k < COLS; k++) {
*(*(result + i) + j) += (*(*(mat1 + i) + k)) *
(*(*(mat2 + k) + j));
}
}
}
}

int main() {
int matrix1[ROWS][COLS] = {{1, 2}, {3, 4}};
int matrix2[ROWS][COLS] = {{5, 6}, {7, 8}};
int sumMatrix[ROWS][COLS];
int productMatrix[ROWS][COLS];

addMatrices(matrix1, matrix2, sumMatrix);


multiplyMatrices(matrix1, matrix2, productMatrix);

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


for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cout << *(*(sumMatrix + i) + j) << " ";
}
cout << endl;
}

cout << "Product of matrices:" << endl;


for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cout << *(*(productMatrix + i) + j) << " ";
}

Code With Redoy Interactive Coding PDF


204

cout << endl;


}

return 0;
}

Code With Redoy Interactive Coding PDF


205

Files (12 Problems)

238. Write a program to create a file and write contents, and save and
close the file.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outputFile("sample.txt"); // Create and open a
file for writing

if (!outputFile) {
cerr << "Failed to open the file for writing." <<
endl;
return 1;
}

outputFile << "Hello, World!" << endl;


outputFile << "This is a sample file." << endl;

outputFile.close(); // Save and close the file

cout << "File created and contents written successfully."


<< endl;

return 0;
}

239. Write a program to read file contents and display them on the
console.
#include <iostream>
#include <fstream>

Code With Redoy Interactive Coding PDF


206

#include <string>
using namespace std;

int main() {
ifstream inputFile("sample.txt"); // Open the file for
reading

if (!inputFile) {
cerr << "Failed to open the file for reading." <<
endl;
return 1;
}

string line;

while (getline(inputFile, line)) {


cout << line << endl;
}

inputFile.close(); // Close the file

return 0;
}

240. Write a program to read numbers from a file and write even, odd
and prime numbers to separate files.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

bool isPrime(int num) {


if (num <= 1) {
return false;

Code With Redoy Interactive Coding PDF


207

}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

int main() {
ifstream inputFile("numbers.txt"); // Open the file for
reading

if (!inputFile) {
cerr << "Failed to open the file for reading." <<
endl;
return 1;
}

ofstream evenFile("even_numbers.txt"); // Create and open


a file for even numbers
ofstream oddFile("odd_numbers.txt"); // Create and open
a file for odd numbers
ofstream primeFile("prime_numbers.txt"); // Create and
open a file for prime numbers

if (!evenFile || !oddFile || !primeFile) {


cerr << "Failed to create one or more output files."
<< endl;
return 1;
}

int num;
while (inputFile >> num) {
if (num % 2 == 0) {
evenFile << num << " ";
} else {

Code With Redoy Interactive Coding PDF


208

oddFile << num << " ";


}

if (isPrime(num)) {
primeFile << num << " ";
}
}

inputFile.close();
evenFile.close();
oddFile.close();
primeFile.close();

cout << "Numbers categorized and written to separate


files." << endl;

return 0;
}

241. Write a program to copy the contents of one text file to another.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream inputFile("source.txt"); // Open the source file
for reading
ofstream outputFile("destination.txt"); // Open the
destination file for writing

if (!inputFile) {
cerr << "Failed to open the source file." << endl;
return 1;
}

if (!outputFile) {

Code With Redoy Interactive Coding PDF


209

cerr << "Failed to open the destination file." <<


endl;
return 1;
}

char ch;
while (inputFile.get(ch)) {
outputFile.put(ch);
}

inputFile.close();
outputFile.close();

cout << "File copied successfully." << endl;

return 0;
}

242. Write a program to count the number of lines in a text file.


#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream inputFile("file.txt"); // Open the file for
reading

if (!inputFile) {
cerr << "Failed to open the file." << endl;
return 1;
}

int lineCount = 0;
string line;

Code With Redoy Interactive Coding PDF


210

while (getline(inputFile, line)) {


lineCount++;
}

inputFile.close();

cout << "Number of lines in the file: " << lineCount <<
endl;

return 0;
}

243. Write a program to search for a specific word in a text file and
display the line numbers where it occurs.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream inputFile("file.txt"); // Open the file for
reading

if (!inputFile) {
cerr << "Failed to open the file." << endl;
return 1;
}

string wordToSearch;
cout << "Enter the word to search: ";
cin >> wordToSearch;

string line;

Code With Redoy Interactive Coding PDF


211

int lineNumber = 0;

while (getline(inputFile, line)) {


lineNumber++;
if (line.find(wordToSearch) != string::npos) {
cout << "Found in line " << lineNumber << ": " <<
line << endl;
}
}

inputFile.close();

return 0;
}

244. Write a program to read and display the contents of a binary file.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream inputFile("binaryfile.bin", ios::binary); // Open
the binary file for reading in binary mode

if (!inputFile) {
cerr << "Failed to open the binary file." << endl;
return 1;
}

char ch;
while (inputFile.get(ch)) {
cout << ch;
}

Code With Redoy Interactive Coding PDF


212

inputFile.close();

return 0;
}

245. Write a program to merge two text files into a single text file.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream inputFile1("file1.txt"); // Open the first file
for reading
ifstream inputFile2("file2.txt"); // Open the second file
for reading
ofstream outputFile("mergedfile.txt"); // Open the merged
file for writing

if (!inputFile1 || !inputFile2) {
cerr << "Failed to open one or both input files." <<
endl;
return 1;
}

if (!outputFile) {
cerr << "Failed to open the output file." << endl;
return 1;
}

char ch;
while (inputFile1.get(ch)) {
outputFile.put(ch);
}

Code With Redoy Interactive Coding PDF


213

while (inputFile2.get(ch)) {
outputFile.put(ch);
}

inputFile1.close();
inputFile2.close();
outputFile.close();

cout << "Files merged successfully." << endl;

return 0;
}

246. Write a program to read a CSV (Comma-Separated Values) file


and display its contents in tabular form.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;

int main() {
ifstream inputFile("data.csv"); // Open the CSV file for
reading

if (!inputFile) {
cerr << "Failed to open the CSV file." << endl;
return 1;
}

string line;
vector<vector<string>> data;

Code With Redoy Interactive Coding PDF


214

while (getline(inputFile, line)) {


vector<string> row;
stringstream ss(line);
string cell;

while (getline(ss, cell, ',')) {


row.push_back(cell);
}

data.push_back(row);
}

inputFile.close();

// Display data in tabular form


for (const vector<string>& row : data) {
for (const string& cell : row) {
cout << cell << "\t";
}
cout << endl;
}

return 0;
}

247. Write a program to read a binary file containing student records


and display the records in a structured format.
#include <iostream>
#include <fstream>
using namespace std;

struct Student {
int rollNumber;
string name;

Code With Redoy Interactive Coding PDF


215

double marks;
};

int main() {
ifstream inputFile("student_records.bin", ios::binary); //
Open the binary file for reading in binary mode

if (!inputFile) {
cerr << "Failed to open the binary file." << endl;
return 1;
}

Student student;

while (inputFile.read(reinterpret_cast<char*>(&student),
sizeof(Student))) {
cout << "Roll Number: " << student.rollNumber << endl;
cout << "Name: " << student.name << endl;
cout << "Marks: " << student.marks << endl;
cout << "-------------------" << endl;
}

inputFile.close();

return 0;
}

248. Write a program to read a text file and count the occurrences of a
specific word.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

Code With Redoy Interactive Coding PDF


216

int main() {
ifstream inputFile("textfile.txt"); // Open the text file
for reading

if (!inputFile) {
cerr << "Failed to open the file." << endl;
return 1;
}

string wordToCount;
cout << "Enter the word to count: ";
cin >> wordToCount;

string word;
int count = 0;

while (inputFile >> word) {


if (word == wordToCount) {
count++;
}
}

inputFile.close();

cout << "The word '" << wordToCount << "' appears " <<
count << " times in the file." << endl;

return 0;
}

249. Write a program to read data from a CSV file containing product
information, calculate the total price of all products, and display it.
#include <iostream>
#include <fstream>

Code With Redoy Interactive Coding PDF


217

#include <string>
#include <sstream>
using namespace std;

struct Product {
string name;
double price;
int quantity;
};

int main() {
ifstream inputFile("products.csv"); // Open the CSV file
for reading

if (!inputFile) {
cerr << "Failed to open the CSV file." << endl;
return 1;
}

string line;
double totalPrice = 0.0;

while (getline(inputFile, line)) {


stringstream ss(line);
string name, quantityStr, priceStr;

getline(ss, name, ',');


getline(ss, quantityStr, ',');
getline(ss, priceStr, ',');

int quantity = stoi(quantityStr);


double price = stod(priceStr);

totalPrice += quantity * price;


}

inputFile.close();

Code With Redoy Interactive Coding PDF


218

cout << "Total price of all products: $" << totalPrice <<
endl;

return 0;
}

250. Write a program that reads a text file containing names and their
corresponding ages, and then calculates and displays the average age
of all individuals in the file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream inputFile("names_and_ages.txt"); // Open the text file for reading

if (!inputFile) {
cerr << "Failed to open the file." << endl;
return 1;
}

string name;
int age;
int totalAge = 0;
int personCount = 0;

while (inputFile >> name >> age) {


totalAge += age;
personCount++;
}

inputFile.close();

if (personCount > 0) {
double averageAge = static_cast<double>(totalAge) / personCount;
cout << "Average age of all individuals: " << averageAge << " years" << endl;
} else {
cout << "No data found in the file." << endl;
}

return 0;
}

Code With Redoy Interactive Coding PDF

You might also like