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

C Programming Examples From Basics to Advanced

The document is a comprehensive guide titled 'C++ Programming Examples: From Basics to Advanced' by Abdul Wahab Junaid, featuring over 200 programming examples that cover a wide range of C++ concepts. It is licensed under a Creative Commons Attribution License, allowing readers to share and adapt the content with proper attribution. The author, a skilled programmer and tech writer, also provides links to his blog and social media for further engagement.

Uploaded by

BÙI ĐĂNG
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C Programming Examples From Basics to Advanced

The document is a comprehensive guide titled 'C++ Programming Examples: From Basics to Advanced' by Abdul Wahab Junaid, featuring over 200 programming examples that cover a wide range of C++ concepts. It is licensed under a Creative Commons Attribution License, allowing readers to share and adapt the content with proper attribution. The author, a skilled programmer and tech writer, also provides links to his blog and social media for further engagement.

Uploaded by

BÙI ĐĂNG
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 209

Written By

Abdul Wahab Junaid

C++ PROGRAMMING EXAMPLES


FROM
BASICS TO ADVANCED
C++ Programming
Examples: From Basics to
Advanced

100+ Examples of C++


programming, covering basic to
advanced concepts, to aid in
understanding the language's
functionalities.

github.com/aw-junaid 1
C++ Programming Examples: From Basics to Advanced

Abdul Wahab Junaid


Lahore, Pakistan

Copyright © 2023 by Abdul Wahab Junaid


This book is licensed under a Creative Commons Attribution [CC BY] International
License.

The Creative Commons Attribution License allows others to share, copy, distribute,
and transmit the work as long as they give appropriate credit to the original author
and indicate if any changes were made to the work. The license also allows for
commercial use of the work.

By choosing to release this book under a Creative Commons license, the author is
allowing readers to share and distribute the book while still retaining some control
over how it is used. This is because the license requires attribution and may
include other restrictions, depending on the type of license chosen.

Readers are free to use the book in various ways, including adapting it, translating
it, or even creating a new work based on it. However, they must still give credit to
the original author and comply with any other restrictions set forth in the license.

It's important to note that while Creative Commons licenses are a useful tool for
sharing and disseminating creative works, they are not a substitute for copyright
law. Copyright law still applies to works licensed under a Creative Commons
license, and authors should seek legal advice to ensure that their rights are
protected.

In addition, the author of this book retains all other rights not specifically granted by
the Creative Commons license, such as the right to create derivative works or to
license the work to others under different terms.

Any source code or other supplementary material referenced by the author in this
book is available to readers on GitHub, located at https://github.com/aw-junaid/C---
Programming.

github.com/aw-junaid 2
Hi, I'm
Abdul Wahab
Junaid
I am highly skilled Social Engineer and Cyber Researcher with
expertise in several programming languages, including C, C++, Python,
Dart, Ruby, and Rust. I am passionate about exploring the depths of
cyber-security and finding ways to protect individuals and businesses
from digital threats.

I am also a tech writer and always passionate for sharing their


knowledge and expertise with others. I am writing on a variety of
topics, including cyber-security best practices, programming tips and
tricks, and the latest trends in technology.

Visit My Blog: https://medium.com/@aw-junaid

where to find me:

Linkedin: https://www.linkedin.com/in/aw-junaid/
Github: https://github.com/aw-junaid/
Facebook: https://www.facebook.com/abdulwahabjunaid0/
Instagram: https://www.instagram.com/aw.junaid/
VK: https://vk.com/aw.junaid
Contact Me: https://www.awjunaid.live/p/blog-page.html
Merchandise: https://awj-store.creator-spring.com/
Linktree: https://linktr.ee/awjunaid

github.com/aw-junaid 3
Table of Content
1: Program prints Hello World! to the standard output stream
2: Program to calculate sum of two numbers.
3: Program to calculate the product of three integers.
4: Program to printing a line of text with multiple statements.
5: Program to printing multiple lines of text with a single statement.
6: Addition program that displays the sum of two numbers.
7: Program to swap two numbers using macros.
8: Program to print your name 50 times.
9: Program to subtract two numbers without using the subtraction operator.
10: Program to print complex number.
11: Comparing integers using if statements, relational and equality operators.
12: Program to calculate the sum of the integers from 1 to 5.
13: Program to check whether input alphabet is a vowel or not.
14 Program to print numeric pyramid.
15: Program to calculate the value of product and quotient.
16: Program to accept Student roll no, marks in 7 subjects and calculate total...
17: Program to check if given integer is positive or negative.
18: Program to calculate raise x to the y power.
19: Program to print a new number by adding one to each of its digits...
20: Program to convert binary number to decimal number.
21: Program to find the area of a trapezium.
22: Program to find the area of a square.
23: Program to find the area of a triangle.
24: Program to find greatest number between 5 numbers.
25: Program to convert a decimal number to binary number.
26: Program to preincrementing and postincrementing.
27 Program to display number in hexadecimal form.
28: Program to print odd numbers from 1 to 7
29: Program to find greatest number among four numbers by ternary operator.
30: Program to find smallest number among four numbers by using ternary operator.
31: Write a program to calculate the area & perimeter of the rectangle...
32: Program to accept a string in any case and print it by another case.
33: Program to check whether a given number is perfect or not.
34: Program to shifted and scaled random integers.
35: Program to print table of any number.
36: Program to find largest element using dynamic memory allocation.
37: Program to reverse a given number.
38: Program to print natural numbers from 1 to 10 in reverse.
39: Program to read ‘n’ number and print them in matrix terms in all orders.
40: Program to accept two numbers and print the sum of given two numbers...

github.com/aw-junaid 4
41: Program to find generic root of number or sum of digits of a number unit we...
42: Program to find the sum of first n natural numbers using for loop.
43: Program to calculate the sum of odd & even numbers up to n numbers.
44: Program to check whether a number is strong or not.
45: Program to find whether a number is divisible by ‘13’ or not without actual...
46: Program for craps simulation.
47: Program to print following series using function: x + x^3/3! + x^5/5! +.......+ x^n/n!
48: Program to check whether a number is prime number or not.
49: Program to find sum of series 1 + 2 + 3 +......+ n
50: Program to Print following series: 1 -4 7 -10..........-40
51: Program to swap values of two variables using pass by reference method.
52: Program of simple bubble sort implementation using array ascending order.
53: Program to find HCF and LCM of numbers.
54: Program to print prime numbers between 1-200 using break and continue.
55: Program to find prime factor of number.
56: Program to find factorial of a number.
57: Program to print Fibonacci series.
58: Program to print Armstrong numbers from 1 to 500.
59: Program to check whether a number is Armstrong number or not.
60: Program to print truth table of XY+Z.
61: Program to find first three pythagorian triplet.
62: Program to check whether a number is unique number or not.
63: Program to swap to numbers without using a third variable.
64: Program to perform all arithmetic calculation using switch case.
65: Program to do arithmetic operations according to user choice using switch case.
66: Program to check given number is multiple of number entered by user.
67: Program to check given year is leap or not.
68: Program to convert gallons to liters.
69: Program to check whether a number is palindrome or not.
70: Program to reverse a number and check if it is a palindrome.
71: Program to find out the sum of in A.P. series.
72: Program to find out the sum of G.P series.
73: Program to find out the sum of H.M series.
74: Program to find out the sum of infinite G.P. series.
75: Program to find the sum of individual digits of a positive integer.
76: Program to the number count of letters in a given text.
77: Program to sort a list of numbers in ascending order.
78: Program to generate square root of 1 to 10.
79: Program to find out entered number.
80: Program to calculate GCD of two numbers.
81: Program to calculate factorial of a number.
82: Program to find absolute value of the integer.

github.com/aw-junaid 5
83: Program for addition of 2 matrices.
84: Program to find roots of a quadratic equation.
85: Program to print numerical as Pascal’s triangle pattern.
86: Program to print “*” as inverted Pascal’s triangle pattern.
87: Program to print numerical as Floyd’s triangle pattern.
88: Program to print “*” as inverted Floyd’s triangle pattern.
89: Program to print diamond pattern.
90: Program to print ASCII value of digits, uppercase and lowercase alphabates.
91: Program to raise any number x to a positive power n.
92: Program to convert given inches into equivalent yard, feet and inches.
93: Program to find ASCII value of a character.
94: Program to reverse all the strings stored in an array
95: Program to search an element in an array using binary search.
96: Program for decimal to octal converter.
97: Convert large binary number to hexadecimal.
98: Program for hexadecimal to binary conversion.
99: Program to convert octal number to decimal number.
100: Program to covert each digits of a number in English word.
101: Program for multiplication of two binary numbers.
102: Program which prints initial of any name.
103: Program to concatenate two strings.
104: Program to find length of a string.
105: Program to find substring in String (Pattern Matching).
106: Program to remove spaces from string
107: Program to find compound interest.
108: Program to convert given no. of days into years, weeks and days.
109: Program to find cube of a number using macros.
110: Program to insert an element in an array.
111: Program to find sum of diagonal elements of a matrix.
112: Program to check whether two matrices are equal or not.
113: Program to check whether a given matrix is identity matrix or not.
114: Program to check whether a given matrix is a sparse matrix or dense matrix.
115: Program to calculate sum of the elements of each row and column.
116: Program to find the frequency of odd and even numbers in the given matrix.
117: Program for swapping of two arrays.
118: Program to print upper triangular matrix.
119: Program for multiplication of two matrices.
120: Program to find inverse of a matrix.
121: Program to find transpose of matrix.
122: Program to find determinant of a matrix.
123: Program to find the second largest element in an array .
124: Program to find the second smallest element in an array.

github.com/aw-junaid 6
125: Program to insert an element in an array at desired position.
126: Program to remove duplicate elements in an array.
127: Program to compare two strings using “strcmp” functions.
128: Program to compare two strings without using string functions.
129: Program to find length of string using “strlen” function.
130: Program to copy string using “strcpy” library function.
131: Program to copy string without using strcpy library function.
132: Program to reverse a string using “strrev” library function.
133: Program for Swapping of strings.
134: Program to delete vowels from string.
135: Program to find number of vowels, consonants, digits and white space.
136: Program to check whether two strings are anagrams or not.
137: Program to reverse a string using both recursion and iteration.
138: Program to find size of structure data type without using size of operator.
139: Program to store and display information of single student using structure.
140: Program to read and print details of 50 students using structure.
141: Program to print sum of two complex numbers by passing structure to a function.
142: Program to see difference between union and structure.
143: Program to find largest and second largest no from a 2D array.
144: Program to do linear search in Array.
145: Program and algorithm for selection Sort.
146: Program and algorithm for insertion Sort.
147: Program to find whether a square matrix is a) symmetric b) skew symmetric...
148: Program for linked list representation of linear queue.
149: Program to perform a PUSH operation on a dynamically allocated stack.
150: Program to swap two numbers using class.
151: Program to count occurrence of a word in a text file.
152: Program to copy files.
153: Program to merge two files.
154: Program to delete a file.
155: program to write all the members of an array of structure to a file using fwrite().
156: Program to write on data file and read from data file.
157: Program to concatenate many files and store them in a file.
158: Program to replace specified line in a text file.
159: Program to delete specific line from a text file.
160: Program to find GCD of numbers using recursion.
161: Program to display atm transaction using class.
162: Program for a matchstick game being played between the computer and a user.
163: Write a function power ( a, b ), to calculate the value of a raised to b.
164: Write a general-purpose function to convert any given year into its roman...
165: Program that compares two given dates using structure.
166: Program two functions xgets( ) and xputs( ) which work similar to the standard...
167: Program to add the contents of one file at the end of another.
168: Program to encrypt/decrypt a file.

github.com/aw-junaid 7
169: Program that can be used at command prompt as a calculating utility.
170: Program that prints the value of hInstance in a message box.
171: Program that displays three buttons ‘Yes’, ‘No’ ‘Cancel’ in the message box.
172: Program that displays command line arguments including file name in a mes...
173: Write a program to gradient fill the entire client area with shades of blue color.
174: Write a program that displays only the upper half of a bitmap of size 40 x 40.
175: Write a program that displays different text in different colors and fonts at diff...
176: Write a program to read the contents of Boot Sector of a 32-bit FAT file sys...
177: Write a program that blocks the SIGTERM signal during execution of the SIGINT.
178: Write a program to verify that SIGSTOP and SIGKILL signals are un-catc...
179: Program to create GradeBook object and call its displayMessage function.
180: Create a BMI calculator application that reads the user’s weight in pounds...
181: Write a program that displays the checkerboard pattern using *
182: Program for counting letter grades with switch.
183: Program using the break statement in a for statement.
184: Program using the continue statement in a for statement.
185: Program to Calculate Weekly Pay.
186: Program using the De Morgan’s Laws.
187: Write a program for Roman-Numeral Equivalent of Decimal Values.
188: Program to demonstrating the function call stack and stack frames using a...
189: Write a program to randomizing the die-rolling program.
190: Program a recursive factorial function.
191: Write a program Hypotenuse Calculations using function.
192: Program to convert Time in Seconds.
193: Write a program for Currency Conversion.
194: Write a program that simulates coin tossing.
195: Write a recursive function isPrime that determines whether the given input is...
196: Write a program to displaying a histogram using array.
197: Write a program to treating character arrays as strings.
198: Write a Program for array name is the same as the address of the array’s ...
199: Write a Program for passing arrays and individual array elements to functions.
200: Write a Program for Survey data analysis with arrays:computing the mean,...
201: Program to Print a string one character at a time using a non-constant pointer...
202: Write a Program using operator sizeof to determine standard data type sizes.
203: Write a program for card shuffling and dealing.
204: Write a Program for counting the occurrences of a substring.
205: Write a program that reads a series of strings and prints only those beginning...
206: Write a program that reads a series of strings and prints only those that end...
207: Write your own versions of the functions for converting strings to numbers.
208: Function to convert string to double.
209: Write a program that will assist the user with metric conversions.
210: Write a program that reverses the order of the bits in an unsigned int value.
211: Program for reading and printing a sequential file.

github.com/aw-junaid 8
212: Credit inquiry program.
213: Program for writing data randomly to a random-access file.
214: Program for inserting and deleting nodes in a list.
215: Simple stack program.
216: Program for creating and traversing a binary tree preorder, inorder, and...
217: Write a program that concatenates two linked lists of characters.
218: Write a program that merges two ordered lists of integers into a single ord...
219: Write a program that inserts 25 random integers from 0 to 100 in order in a ...
220: Write a program that creates a linked list of 10 characters, then creates a...
221: Write a program that inputs a line of text and uses a stack to print the line...
222: Write a function searchList that recursively searches a linked list for a speci...
223: Write a program that prints the command-line arguments of the program.
224: Overloaded square functions.
225: Inline function that calculates the volume of a sphere.
226: Create a class called Date that includes three pieces of information as data
members—a month (type int), a day (type int) and a year (type int). Y
227: Write a program that demonstrates several exception types being caught with the
catch(...) exception handler
228: Write a program that shows a constructor passing information about constructor
failure to an exception handler after a try block.
229: Write a program that illustrates rethrowing an exception.

github.com/aw-junaid 9
1: Program prints Hello World! to the standard output stream.

#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}

Output:
https://github.com/aw-junaid/C---Programming

2: Program to calculate sum of two numbers.

#include <iostream>
// Include input/output stream library

int main() {
// Main function
int num1, num2, sum;
// Declare integer variables to store input numbers and sum
std::cout << "Enter first number: ";
// Prompt user to enter first number
std::cin >> num1;
// Read first input number from console and store in num1
std::cout << "Enter second number: ";
// Prompt user to enter second number
std::cin >> num2;
// Read second input number from console and store in num2
sum = num1 + num2;
// Calculate sum of num1 and num2 and store in sum
std::cout << "Sum of " << num1 << " and " << num2 << " is " << sum << std::endl;
// Print sum of input numbers to console
return 0;
// End main function and return 0 to indicate successful execution
}

3: Program to calculate the product of three integers.

#include <iostream>
using namespace std;

github.com/aw-junaid 10
int main() {
int num1, num2, num3;
int product;

// Prompt user to input three integers


cout << "Enter three integers: ";

// Read in the three integers from user input


cin >> num1 >> num2 >> num3;

// Calculate the product of the three integers


product = num1 * num2 * num3;

// Display the product of the three integers to the user


cout << "The product of the three integers is: " << product << endl;

return 0;

4: Program to printing a line of text with multiple statements.

#include <iostream>
using namespace std;

int main() {
cout << "Hello, ";
cout << "world!";
cout << endl;

return 0;
}

5: Program to printing multiple lines of text with a single statement.

#include <iostream>
using namespace std;

int main() {
cout << "Hello,\nworld!\n";

return 0;
}

6: Addition program that displays the sum of two numbers.

github.com/aw-junaid 11
#include <iostream>
using namespace std;

int main() {
int num1, num2, sum;

// Prompt user to input two numbers


cout << "Enter two numbers: ";

// Read in the two numbers from user input


cin >> num1 >> num2;

// Add the two numbers together


sum = num1 + num2;

// Display the sum of the two numbers to the user


cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl;

return 0;
}

7: Program to swap two numbers using macros.

#include <iostream>
using namespace std;

// Define a macro to swap two numbers


#define SWAP(a, b) {a ^= b; b ^= a; a ^= b;}

int main() {
int num1 = 5, num2 = 10;

// Display the original values of the two numbers


cout << "Before swapping, num1 = " << num1 << " and num2 = " << num2 << endl;

// Use the SWAP macro to swap the values of the two numbers
SWAP(num1, num2);

// Display the swapped values of the two numbers


cout << "After swapping, num1 = " << num1 << " and num2 = " << num2 << endl;

return 0;
}

github.com/aw-junaid 12
8: Program to print your name 50 times.

#include <iostream>
using namespace std;

int main() {
// Loop 50 times and print your name each time
for (int i = 1; i <= 50; i++) {
cout << i << ". Your Name Here" << endl;
}

return 0;
}

9: Program to subtract two numbers without using the subtraction


operator.

#include <iostream>
using namespace std;

int main() {
int num1 = 10, num2 = 5, result;

// Subtract num2 from num1 using bitwise NOT and AND operators
result = num1 + (~num2 + 1);

// Display the result to the console


cout << "The result of subtracting " << num2 << " from " << num1 << " is " << result
<< endl;

return 0;
}

10: Program to print complex number.

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

int main() {
// Create a complex number object
complex<double> num(3.0, 4.0);

github.com/aw-junaid 13
// Display the real and imaginary parts of the complex number
cout << "The real part is: " << num.real() << endl;
cout << "The imaginary part is: " << num.imag() << endl;

// Display the complex number in rectangular and polar forms


cout << "The complex number in rectangular form is: " << num << endl;
cout << "The complex number in polar form is: " << abs(num) << " * exp(" <<
arg(num) << "i)" << endl;

return 0;
}

11: Comparing integers using if statements, relational operators and


equality operators.

#include <iostream>
using namespace std;

int main() {
int num1, num2;

cout << "Enter the first number: ";


cin >> num1;

cout << "Enter the second number: ";


cin >> num2;

if (num1 == num2) {
cout << num1 << " is equal to " << num2 << endl;
} else if (num1 < num2) {
cout << num1 << " is less than " << num2 << endl;
} else {
cout << num1 << " is greater than " << num2 << endl;
}

return 0;
}

12: Program to calculate the sum of the integers from 1 to 5.

#include <iostream>

github.com/aw-junaid 14
using namespace std;

int main() {
int sum = 0;

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


sum += i;
}

cout << "The sum of integers from 1 to 5 is " << sum << endl;

return 0;
}

13: Program to check whether input alphabet is a vowel or not.

#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' ||


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

return 0;
}

14: Program to print numeric pyramid.

#include <iostream>
using namespace std;

int main() {
int rows;

github.com/aw-junaid 15
cout << "Enter the number of rows: ";
cin >> rows;

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


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

return 0;
}

15: Program to calculate the value of product and quotient.

#include <iostream>
using namespace std;

int main() {
double num1, num2, product, quotient;

cout << "Enter the first number: ";


cin >> num1;

cout << "Enter the second number: ";


cin >> num2;

product = num1 * num2;


quotient = num1 / num2;

cout << "The product of the two numbers is: " << product << endl;
cout << "The quotient of the two numbers is: " << quotient << endl;

return 0;
}

16: Program to accept Student roll no, marks in 7 subjects and


calculate total, average and print it.

#include <iostream>
using namespace std;

github.com/aw-junaid 16
int main() {
int rollNo;
float marks[7], total = 0, average;

cout << "Enter the student's roll number: ";


cin >> rollNo;

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


cout << "Enter the marks in subject " << i+1 << ": ";
cin >> marks[i];
total += marks[i];
}

average = total / 7;

cout << "Roll No: " << rollNo << endl;


cout << "Total Marks: " << total << endl;
cout << "Average Marks: " << average << endl;

return 0;
}

17: Program to check if given integer is positive or negative.

#include <iostream>

using namespace std;

int main() {
int num;

cout << "Enter an integer: ";


cin >> num;

if (num > 0) {
cout << num << " is a positive integer." << endl;
}
else if (num < 0) {
cout << num << " is a negative integer." << endl;
}
else {
cout << "The integer is zero." << endl;
}

github.com/aw-junaid 17
return 0;
}

18: Program to calculate raise x to the y power.

#include <iostream>

using namespace std;

int main() {
int x, y, result = 1;

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


cin >> x;

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


cin >> y;

// loop to calculate x raised to the power of y


for(int i = 1; i <= y; i++) {
result *= x; // multiply result by x for y times
}

cout << x << " raised to the power of " << y << " is " << result << endl;

return 0;
}

19: Program to print a new number by adding one to each of its digits.
Take 5 digit input from user.

#include <iostream>

using namespace std;

int main() {
int num, newNum = 0, digit;

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


cin >> num;

// loop to add 1 to each digit

github.com/aw-junaid 18
for(int i = 1; i <= 5; i++) {
digit = (num % 10) + 1; // add 1 to the rightmost digit
newNum = digit * i + newNum; // add digit to the new number
num /= 10; // remove the rightmost digit
}

cout << "The new number is " << newNum << endl;

return 0;
}

20: Program to convert binary number to decimal number.

#include <iostream>
#include <cmath>

using namespace std;

int main() {
long long binaryNum, decimalNum = 0;
int power = 0;

cout << "Enter a binary number: ";


cin >> binaryNum;

// loop to convert binary to decimal


while(binaryNum != 0) {
int digit = binaryNum % 10; // get rightmost digit of binary number
decimalNum += digit * pow(2, power); // add decimal equivalent of digit
binaryNum /= 10; // remove rightmost digit of binary number
power++; // increment power by 1
}

cout << "The decimal equivalent of the binary number is " << decimalNum << endl;

return 0;
}

21: Program to find the area of a trapezium.

#include <iostream>
using namespace std;

github.com/aw-junaid 19
nt main() {
float base1, base2, height, area;

cout << "Enter the length of the first base: ";


cin >> base1;

cout << "Enter the length of the second base: ";


cin >> base2;

cout << "Enter the height: ";


cin >> height;

area = (base1 + base2) * height / 2;

cout << "The area of the trapezium is " << area << endl;

return 0;
}

22: Program to find the area of a square.

#include <iostream>

using namespace std;

int main() {
float side, area;

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


cin >> side;

area = side * side;

cout << "The area of the square is " << area << endl;

return 0;
}

23: Program to find the area of a triangle.

#include <iostream>

github.com/aw-junaid 20
#include <iostream>

using namespace std;

int main() {
float base, height, area;

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

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


cin >> height;

area = 0.5 * base * height;

cout << "The area of the triangle is " << area << endl;

return 0;
}

24: Program to find greatest number between 5 numbers.

#include <iostream>

using namespace std;

int main() {
float num1, num2, num3, num4, num5, max;

cout << "Enter five numbers: ";


cin >> num1 >> num2 >> num3 >> num4 >> num5;

max = num1;

if (num2 > max) {


max = num2;
}

if (num3 > max) {


max = num3;
}

github.com/aw-junaid 21
if (num4 > max) {
max = num4;
}

if (num5 > max) {


max = num5;
}

cout << "The greatest number among " << num1 << ", " << num2 << ", " << num3
<< ", " << num4 << ", and " << num5 << " is " << max << endl;

return 0;
}

25: Program to convert a decimal number to binary number.

#include <iostream>

using namespace std;

int main() {
int decimalNum, binaryNum = 0, i = 1, rem;

cout << "Enter a decimal number: ";


cin >> decimalNum;

while (decimalNum != 0) {
rem = decimalNum % 2;
decimalNum /= 2;
binaryNum += rem * i;
i *= 10;
}

cout << "The binary equivalent of the decimal number is " << binaryNum << endl;

return 0;
}

26: Program to preincrementing and postincrementing.

#include <iostream>
using namespace std;

github.com/aw-junaid 22
#include <iostream>

using namespace std;

int main() {
int num = 5, pre, post;

// pre-increment
pre = ++num;
cout << "The value of num after pre-incrementing: " << num << endl;
cout << "The value of pre after pre-incrementing: " << pre << endl;

num = 5; // resetting num to its initial value

// post-increment
post = num++;
cout << "The value of num after post-incrementing: " << num << endl;
cout << "The value of post after post-incrementing: " << post << endl;

return 0;
}

27: Program to display number in hexadecimal form.

#include <iostream>
#include <iomanip>

using namespace std;

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

cout << "The hexadecimal equivalent of the decimal number is: ";
cout << hex << decimalNum << endl;

return 0;
}

28: Program to print odd numbers from 1 to 7.

#include <iostream>

github.com/aw-junaid 23
using namespace std;

int main() {
cout << "The odd numbers from 1 to 7 are:" << endl;

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


cout << i << endl;
}

return 0;
}

29: Program to find greatest number among four numbers by ternary


operator.

#include <iostream>

using namespace std;

int main() {
int num1, num2, num3, num4, maxNum;

cout << "Enter four numbers: ";


cin >> num1 >> num2 >> num3 >> num4;

maxNum = (num1 > num2) ? ((num1 > num3) ? ((num1 > num4) ? num1 : num4) :
((num3 > num4) ? num3 : num4)) : ((num2 > num3) ? ((num2 > num4) ? num2 :
num4) : ((num3 > num4) ? num3 : num4));

cout << "The greatest number among " << num1 << ", " << num2 << ", " << num3
<< ", " << num4 << " is: " << maxNum << endl;

return 0;
}

30: Program to find smallest number among four numbers by using


ternary operator.

#include <iostream>
using namespace std;

int main() {
int num1, num2, num3, num4, minNum;

github.com/aw-junaid 24
minNum = (num1 < num2) ? ((num1 < num3) ? ((num1 < num4) ? num1 : num4) :
((num3 < num4) ? num3 : num4)) : ((num2 < num3) ? ((num2 < num4) ? num2 :
num4) : ((num3 < num4) ? num3 : num4));

cout << "The smallest number among " << num1 << ", " << num2 << ", " << num3
<< ", " << num4 << " is: " << minNum << endl;

return 0;
}

31: Write a program to calculate the area & perimeter of the rectangle,
and the area & circumference of the circle.

#include <iostream>
#include <cmath>

using namespace std;

int main() {
double length, width, radius;
double rectArea, rectPerimeter, circleArea, circleCircumference;
const double PI = 3.14159265358979323846;

//Rectangle calculations
cout << "Enter the length and width of the rectangle: ";
cin >> length >> width;

rectArea = length * width;


rectPerimeter = 2 * (length + width);

cout << "The area of the rectangle is: " << rectArea << endl;
cout << "The perimeter of the rectangle is: " << rectPerimeter << endl;

//Circle calculations
cout << "Enter the radius of the circle: ";
cin >> radius;

circleArea = PI * pow(radius, 2);


circleCircumference = 2 * PI * radius;

cout << "The area of the circle is: " << circleArea << endl;
cout << "The circumference of the circle is: " << circleCircumference << endl;

github.com/aw-junaid 25
return 0;
}

32: Program to accept a string in any case and print it by another case.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

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

// Convert string to lowercase


transform(str.begin(), str.end(), str.begin(), ::tolower);
cout << "Lowercase: " << str << endl;

// Convert string to uppercase


transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << "Uppercase: " << str << endl;

return 0;
}

33: Program to check whether a given number is perfect or not.

#include <iostream>

using namespace std;

bool isPerfect(int num) {


int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return (sum == num);
}

github.com/aw-junaid 26
int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (isPerfect(num)) {
cout << num << " is a perfect number." << endl;
} else {
cout << num << " is not a perfect number." << endl;
}

return 0;
}

34: Program to shifted and scaled random integers.

#include <iostream>
#include <random>

using namespace std;

int main() {
// Define the range of the random integer (0 to 99)
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0, 99);

// Generate and print a random integer


int num = dis(gen);
cout << "Random integer: " << num << endl;

// Prompt the user for the shift and scale values


int shift, scale;
cout << "Enter the shift value: ";
cin >> shift;
cout << "Enter the scale value: ";
cin >> scale;

// Shift and scale the random integer


int shifted_num = num + shift;
int scaled_num = shifted_num * scale;

// Print the shifted and scaled integer

github.com/aw-junaid 27
cout << "Shifted and scaled integer: " << scaled_num << endl;

return 0;
}

35: Program to print table of any number.

#include <iostream>

using namespace std;

int main() {
int num;
cout << "Enter a number to print its multiplication table: ";
cin >> num;

cout << "Multiplication table of " << num << ":" << endl;

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


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

return 0;
}

36: Program to find largest element using dynamic memory allocation.

#include <iostream>
using namespace std;

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

// dynamically allocate memory for the array


int *arr = new int[size];

// read input elements from the user


cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

github.com/aw-junaid 28
// find the largest element in the array
int largest = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

cout << "The largest element in the array is: " << largest << endl;

// deallocate the dynamically allocated memory


delete[] arr;

return 0;
}

37: Program to reverse a given number.

#include <iostream>

using namespace std;

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

// reverse the digits of the number


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

cout << "The reversed number is: " << reversed << endl;

return 0;
}

38: Program to print natural numbers from 1 to 10 in reverse.

#include <iostream>

github.com/aw-junaid 29
using namespace std;

int main() {
int num = 10;
while (num >= 1) {
cout << num << " ";
num--;
}
return 0;
}

39: Program to read ‘n’ number and print them in matrix terms in all
orders.

#include <iostream>
using namespace std;

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

// calculate the number of rows and columns in the matrix


rows = cols = sqrt(n);
if (rows * cols < n) {
cols++;
}

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

// print the elements in row-major order


cout << "Row-major order:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int index = i * cols + j;
if (index < n) {
cout << arr[index] << " ";
}
}

github.com/aw-junaid 30
}
cout << endl;
}

return 0;
}

40: Program to accept two numbers and print the sum of given two
numbers by using pointers.

#include <iostream>
using namespace std;

int main() {
int num1, num2, *ptr1, *ptr2, sum;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

ptr1 = &num1;
ptr2 = &num2;

sum = *ptr1 + *ptr2;

cout << "Sum of " << *ptr1 << " and " << *ptr2 << " is " << sum << endl;

return 0;
}

41: Program to find generic root of number or sum of digits of a


number unit we don't get a single digit.

#include <iostream>
using namespace std;

int digitalRoot(int num) {


if (num == 0) {

github.com/aw-junaid 31
return 0;
} else if (num % 9 == 0) {
return 9;
} else {
return num % 9;
}
}

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
int root = digitalRoot(num);
cout << "The digital root of " << num << " is " << root << endl;
return 0;
}

42: Program to find the sum of first n natural numbers using for loop.

#include <iostream>
using namespace std;

int main() {
int n, sum = 0;
cout << "Enter a positive integer n: ";
cin >> n;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "The sum of the first " << n << " natural numbers is " << sum << endl;
return 0;
}

43: Program to calculate the sum of odd & even numbers up to n


numbers.

#include <iostream>
using namespace std;

int main() {
int n, sum_odd = 0, sum_even = 0;
cout << "Enter a positive integer n: ";

github.com/aw-junaid 32
cin >> n;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum_even += i;
} else {
sum_odd += i;
}
}
cout << "The sum of even numbers up to " << n << " is " << sum_even << endl;
cout << "The sum of odd numbers up to " << n << " is " << sum_odd << endl;
return 0;
}

44: Program to check whether a number is strong or not.

#include <iostream>
using namespace std;

// Function to calculate the factorial of a number


int factorial(int num) {
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}

int main() {
int num, sum = 0, temp;
cout << "Enter a positive integer: ";
cin >> num;
temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += factorial(digit);
temp /= 10;
}
if (sum == num) {
cout << num << " is a strong number." << endl;
} else {
cout << num << " is not a strong number." << endl;
}

github.com/aw-junaid 33
return 0;
}

45: Program to find whether a number is divisible by ‘13’ or not without


actual division.

#include <iostream>
using namespace std;

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

int factor[] = {1, 10, 9, 12, 3, 4}; // the factors to use for each digit
int sum = 0;
int i = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * factor[i % 6]; // use the appropriate factor for this digit
n /= 10;
i++;
}

if (sum % 13 == 0) {
cout << "The number is divisible by 13.\n";
} else {
cout << "The number is not divisible by 13.\n";
}

return 0;
}

46: Program for craps simulation.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
srand(time(0)); // initialize the random number generator

github.com/aw-junaid 34
int balance = 1000; // initial balance
int bet;

while (balance > 0) {


cout << "Balance: $" << balance << endl;
cout << "Enter bet (0 to quit): ";
cin >> bet;
if (bet == 0) break;

int roll1 = rand() % 6 + 1; // roll the dice


int roll2 = rand() % 6 + 1;
int sum = roll1 + roll2;

cout << "Roll: " << roll1 << " + " << roll2 << " = " << sum << endl;

if (sum == 7 || sum == 11) {


cout << "You win!" << endl;
balance += bet;
} else if (sum == 2 || sum == 3 || sum == 12) {
cout << "You lose!" << endl;
balance -= bet;
} else {
int point = sum;
cout << "Point is " << point << endl;
while (true) {
roll1 = rand() % 6 + 1; // roll the dice again
roll2 = rand() % 6 + 1;
sum = roll1 + roll2;
cout << "Roll: " << roll1 << " + " << roll2 << " = " << sum << endl;
if (sum == point) {
cout << "You win!" << endl;
balance += bet;
break;
} else if (sum == 7) {
cout << "You lose!" << endl;
balance -= bet;
break;
}
}
}
}

cout << "Game over." << endl;

github.com/aw-junaid 35
return 0;
}

47: Program to print following series using function: x + x^3/3! + x^5/5!


+.......+ x^n/n!

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

double factorial(int n) {
double fact = 1.0;
for (int i = 2; i <= n; i++) {
fact *= i;
}
return fact;
}

double computeSeries(double x, int n) {


double sum = x, term;
for (int i = 1; i <= n; i += 2) {
term = pow(x, i) / factorial(i);
sum += term;
}
return sum;
}

int main() {
double x;
int n;

cout << "Enter value of x: ";


cin >> x;
cout << "Enter value of n: ";
cin >> n;

double result = computeSeries(x, n);


cout << "Result: " << result << endl;

return 0;
}

48: Program to check whether a number is prime number or not.

github.com/aw-junaid 36
#include <iostream>
using namespace std;

int main() {
int num;
bool isPrime = true;

cout << "Enter a positive integer: ";


cin >> num;

// check if num is divisible by any number other than 1 and itself


for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}

if(isPrime)
cout << num << " is a prime number";
else
cout << num << " is not a prime number";

return 0;
}

49: Program to find sum of series 1 + 2 + 3 +......+ n

#include <iostream>
using namespace std;

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

cout << "Enter a positive integer n: ";


cin >> n;

// Loop through numbers 1 to n and add them up


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

github.com/aw-junaid 37
}

cout << "The sum of the series 1 + 2 + 3 + ... + " << n << " is " << sum << endl;

return 0;
}

50: Program to Print following series: 1 -4 7 -10..........-40

#include <iostream>
using namespace std;

int main()
{
int n = 10; // number of terms in the series
int sign = 1; // starting sign of the series
int term = 1; // starting term of the series

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


{
cout << term << " "; // output the current term
sign *= -1; // change the sign for the next term
term += 3 * sign; // calculate the next term
}

return 0;
}

51: Program to swap values of two variables using pass by reference


method.

#include <iostream>
using namespace std;

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}
int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

github.com/aw-junaid 38
cin >> num1 >> num2;

cout << "Before swapping - Num1: " << num1 << ", Num2: " << num2 << endl;
swap(num1, num2);

cout << "After swapping - Num1: " << num1 << ", Num2: " << num2 << endl;

return 0;
}

52: Program of simple bubble sort implementation using array


ascending order.

#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {


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

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}

53: Program to find HCF and LCM of numbers.

#include <iostream>

github.com/aw-junaid 39
using namespace std;

// function to calculate HCF of two numbers using recursion


int hcf(int a, int b) {
if (b == 0) {
return a;
}
else {
return hcf(b, a % b);
}
}

// function to calculate LCM of two numbers


int lcm(int a, int b) {
return (a * b) / hcf(a, b);
}
int main() {
int num1, num2, h, l;

cout << "Enter two numbers: ";


cin >> num1 >> num2;

// calculate HCF and LCM


h = hcf(num1, num2);
l = lcm(num1, num2);

// print the results


cout << "HCF of " << num1 << " and " << num2 << " is " << h << endl;
cout << "LCM of " << num1 << " and " << num2 << " is " << l << endl;

return 0;
}

54: Program to print prime numbers between 1-200 using break and
continue.

#include <iostream>
using namespace std;

int main() {
int i, j;
bool isPrime;

github.com/aw-junaid 40
// Print all prime numbers between 1 and 200
for (i = 1; i <= 200; i++) {
// Skip the number 1
if (i == 1) {
continue;
}

// Check if current number is prime or not


isPrime = true;
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}

// If the number is prime, print it


if (isPrime) {
cout << i << " ";
}
}

return 0;
}

55: Program to find prime factor of number.

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

// function to check if a number is prime or not


bool isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

github.com/aw-junaid 41
// function to find prime factors of a number
vector<int> primeFactors(int num) {
vector<int> factors;
for (int i = 2; i <= num; i++) {
if (isPrime(i)) {
while (num % i == 0) {
factors.push_back(i);
num /= i;
}
}
}
return factors;
}

// main function to test the primeFactors function


int main() {
int num;
cout << "Enter a number: ";
cin >> num;
vector<int> factors = primeFactors(num);
cout << "Prime factors of " << num << " are: ";
for (int i = 0; i < factors.size(); i++) {
cout << factors[i] << " ";
}
cout << endl;
return 0;
}

56: Program to find factorial of a number.

#include <iostream>
using namespace std;

int main()
{
int num;
long long factorial = 1;

cout << "Enter a positive integer: ";


cin >> num;

// if user enters negative number

github.com/aw-junaid 42
// if user enters negative number
if (num < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else
{
for (int i = 1; i <= num; ++i)
{
factorial *= i;
}
cout << "Factorial of " << num << " = " << factorial;
}

return 0;
}

57: Program to print Fibonacci series.

#include <iostream>
using namespace std;

int main()
{
int n, i, a = 0, b = 1, c;

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


cin >> n;

cout << "Fibonacci Series: ";

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


{
cout << a << " ";
c = a + b;
a = b;
b = c;
}

return 0;
}

58: Program to print Armstrong numbers from 1 to 500.

#include <iostream>

github.com/aw-junaid 43
using namespace std;

int main() {
int num, sum, rem, i;
cout << "Armstrong numbers between 1 to 500:" << endl;
for (i = 1; i <= 500; i++) {
sum = 0;
num = i;
while (num > 0) {
rem = num % 10;
sum += (rem * rem * rem);
num = num / 10;
}
if (sum == i) {
cout << i << " ";
}
}
return 0;
}

59: Program to check whether a number is Armstrong number or not.

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

int main() {
int number, originalNumber, remainder, result = 0, n = 0;

cout << "Enter an integer: ";


cin >> number;

originalNumber = number;

while (originalNumber != 0) {
originalNumber /= 10;
++n;
}

originalNumber = number;

while (originalNumber != 0) {

github.com/aw-junaid 44
while (originalNumber != 0) {
originalNumber /= 10;
++n;
}

originalNumber = number;

while (originalNumber != 0) {
remainder = originalNumber % 10;
result += pow(remainder, n);
originalNumber /= 10;
}

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

return 0;
}

60: Program to print truth table of XY+Z.

#include <iostream>

using namespace std;

int main()
{
bool x, y, z;

cout << "X\tY\tZ\tResult\n";

for(x = 0; x <= 1; x++)


{
for(y = 0; y <= 1; y++)
{
for(z = 0; z <= 1; z++)
{
bool result = x * y + z;
cout << x << "\t" << y << "\t" << z << "\t" << result << endl;
}
}

github.com/aw-junaid 45
}

return 0;
}

61: Program to find first three Pythagorean triplet.

#include <iostream>
using namespace std;

int main() {
int a, b, c, m, n;

// First triplet
m = 2;
n = 1;
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
cout << "First triplet: " << a << ", " << b << ", " << c << endl;

// Second triplet
m = 3;
n = 2;
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
cout << "Second triplet: " << a << ", " << b << ", " << c << endl;

// Third triplet
m = 4;
n = 1;
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
cout << "Third triplet: " << a << ", " << b << ", " << c << endl;

return 0;
}

62: Program to check whether a number is unique number or not.

github.com/aw-junaid 46
#include <iostream>
#include <unordered_set>

using namespace std;

bool isUniqueNumber(int num) {


unordered_set<int> seen;
while (num > 0) {
int digit = num % 10;
if (seen.count(digit)) {
return false;
}
seen.insert(digit);
num /= 10;
}
return true;
}

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isUniqueNumber(num)) {
cout << num << " is a unique number." << endl;
} else {
cout << num << " is not a unique number." << endl;
}
return 0;
}

63: Program to swap to numbers without using a third variable.

#include <iostream>
using namespace std;

int main() {
int num1, num2;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

github.com/aw-junaid 47
cout << "Before swapping, num1 = " << num1 << " and num2 = " << num2 << endl;

num1 = num1 + num2;


num2 = num1 - num2;
num1 = num1 - num2;

cout << "After swapping, num1 = " << num1 << " and num2 = " << num2 << endl;

return 0;
}

64: Program to perform all arithmetic calculation using switch case.

#include <iostream>
using namespace std;

int main() {
char op;
float num1, num2, result;

cout << "Enter two numbers: ";


cin >> num1 >> num2;

cout << "Enter the operator (+, -, *, /): ";


cin >> op;

switch(op) {
case '+':
result = num1 + num2;
cout << num1 << " + " << num2 << " = " << result;
break;

case '-':
result = num1 - num2;
cout << num1 << " - " << num2 << " = " << result;
break;

case '*':
result = num1 * num2;
cout << num1 << " * " << num2 << " = " << result;
break;

github.com/aw-junaid 48
case '/':
result = num1 / num2;
cout << num1 << " / " << num2 << " = " << result;
break;

default:
cout << "Invalid operator!";
break;
}

return 0;
}

65: Program to do arithmetic operations according to user choice


using switch case.

#include <iostream>
using namespace std;

int main() {
float num1, num2, result;
int choice;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

cout << "Enter operation to be performed: \n";


cout << "1. Addition (+)\n";
cout << "2. Subtraction (-)\n";
cout << "3. Multiplication (*)\n";
cout << "4. Division (/)\n";
cout << "5. Modulus (%)\n";
cin >> choice;

switch(choice) {
case 1:
result = num1 + num2;
cout << "Addition of " << num1 << " and " << num2 << " is: " << result <<
endl;
break;

github.com/aw-junaid 49
case 2:
result = num1 - num2;
cout << "Subtraction of " << num1 << " and " << num2 << " is: " << result <<
endl;
break;
case 3:
result = num1 * num2;
cout << "Multiplication of " << num1 << " and " << num2 << " is: " << result <<
endl;
break;
case 4:
if(num2 == 0) {
cout << "Division by zero not possible!" << endl;
}
else {
result = num1 / num2;
cout << "Division of " << num1 << " and " << num2 << " is: " << result <<
endl;
}
break;
case 5:
result = (int)num1 % (int)num2; // casting to integer to perform modulus
operation
cout << "Modulus of " << num1 << " and " << num2 << " is: " << result <<
endl;
break;
default:
cout << "Invalid operation choice!" << endl;
}
return 0;
}

66: Program to check given number is multiple of number entered by


user.

#include <iostream>
using namespace std;

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

github.com/aw-junaid 50
cout << "Enter a factor: ";
cin >> factor;
if (num % factor == 0) {
cout << num << " is a multiple of " << factor << endl;
}
else {
cout << num << " is not a multiple of " << factor << endl;
}
return 0;
}
67: Program to check given year is leap or not.

#include <iostream>

using namespace std;

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.";
} else {
cout << year << " is not a leap year.";
}

return 0;
}

68: Program to convert gallons to liters.

#include <iostream>
using namespace std;

int main() {
double gallons, liters;

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


cin >> gallons;

liters = gallons * 3.78541;

github.com/aw-junaid 51
cout << gallons << " gallons = " << liters << " liters." << endl;

return 0;
}
69: Program to check whether a number is palindrome or not.

#include <iostream>
using namespace std;

int main() {
int num, rev = 0, rem, temp;
cout << "Enter a number: ";
cin >> num;
temp = num;
while (temp != 0) {
rem = temp % 10;
rev = rev * 10 + rem;
temp /= 10;
}
if (num == rev)
cout << num << " is a palindrome number.";
else
cout << num << " is not a palindrome number.";
return 0;
}

70: Program to reverse a number and check if it is a palindrome.

#include <iostream>
using namespace std;

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

// Reverse the number


while(num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;

github.com/aw-junaid 52
}

// Check if the reversed number is the same as the original number


if(reversed == original) {
cout << original << " is a palindrome" << endl;
} else {
cout << original << " is not a palindrome" << endl;
}

return 0;
}

71: Program to find out the sum of in A.P. series.

#include <iostream>

using namespace std;

int main()
{
int first_term, common_diff, num_terms, sum;

cout << "Enter the first term of the AP: ";


cin >> first_term;

cout << "Enter the common difference of the AP: ";


cin >> common_diff;

cout << "Enter the number of terms in the AP: ";


cin >> num_terms;

// Using the formula for the sum of an AP series: S = n/2[2a + (n-1)d]


sum = num_terms/2 * (2 * first_term + (num_terms - 1) * common_diff);

cout << "The sum of the AP series is: " << sum << endl;

return 0;
}

72: Program to find out the sum of G.P series.

github.com/aw-junaid 53
#include <iostream>
#include <cmath>

using namespace std;

int main() {
double a, r, n, sum;

cout << "Enter the first term (a): ";


cin >> a;
cout << "Enter the common ratio (r): ";
cin >> r;
cout << "Enter the number of terms (n): ";
cin >> n;

// calculating sum of the G.P series using formula


sum = (a * (1 - pow(r, n))) / (1 - r);

cout << "The sum of the G.P series is: " << sum << endl;

return 0;
}

73: Program to find out the sum of H.M series.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;
double a[n], sum = 0;
cout << "Enter the terms of the series: ";
for(int i = 0; i < n; i++) {
cin >> a[i];
sum += 1 / a[i];
}
cout << "The sum of the series is " << n / sum << endl;

return 0;
}

github.com/aw-junaid 54
74: Program to find out the sum of infinite G.P. series.

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

int main()
{
double a, r;

cout << "Enter the first term (a): ";


cin >> a;

cout << "Enter the common ratio (r): ";


cin >> r;

if (abs(r) < 1) { // check if series is convergent


double sum = a / (1 - r);
cout << "The sum of the infinite G.P. series is: " << sum << endl;
}
else {
cout << "The series is not convergent." << endl;
}

return 0;
}

75: Program to find the sum of individual digits of a positive integer.

#include <iostream>
using namespace std;

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

while (num > 0)


{
digit = num % 10;
sum += digit;

github.com/aw-junaid 55
num /= 10;
}

cout << "The sum of the digits is: " << sum << endl;
return 0;
}

76: Program to the number count of letters in a given text.

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main() {
string text;
int count = 0;

cout << "Enter a text: ";


getline(cin, text);

for(int i = 0; i < text.length(); i++) {


if(isalpha(text[i])) { // check if the character is an alphabet
count++;
}
}

cout << "The number of letters in the text is: " << count << endl;

return 0;
}

77: Program to sort a list of numbers in ascending order.

#include <iostream>
using namespace std;

int main() {
int arr[100], n;
cout << "Enter the number of elements in the array: ";
cin >> n;
cout << "Enter the elements of the array:\n";

github.com/aw-junaid 56
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// bubble sort algorithm


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

cout << "The sorted array in ascending order is:\n";


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

return 0;
}

78: Program to generate square root of 1 to 10.

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

int main() {
for(int i=1; i<=10; i++) {
cout << "Square root of " << i << " is " << sqrt(i) << endl;
}
return 0;
}

79: Program to find out entered number

#include <iostream>
using namespace std;

github.com/aw-junaid 57
int main() {
int num;

cout << "Enter a number: ";


cin >> num;

cout << "The entered number is: " << num << endl;

return 0;
}

80: Program to calculate GCD of two numbers.

#include <iostream>
using namespace std;

int gcd(int a, int b)


{
if (a == 0)
return b;
return gcd(b % a, a);
}

int main()
{
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "GCD of " << num1 << " and " << num2 << " is: " << gcd(num1, num2);
return 0;
}

81: Program to calculate factorial of a number.

#include <iostream>
using namespace std;

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

cout << "Enter a number: ";


cin >> num;

github.com/aw-junaid 58
// Calculating factorial of the number
for (int i = 1; i <= num; i++) {
fact *= i;
}

cout << "Factorial of " << num << " is " << fact << endl;

return 0;
}

82: Program to find absolute value of the integer.

#include <iostream>
using namespace std;

int main() {
int num, absValue;

// Input the number


cout << "Enter an integer: ";
cin >> num;

// Calculate the absolute value


if (num < 0) {
absValue = -num;
} else {
absValue = num;
}

// Output the absolute value


cout << "The absolute value of " << num << " is " << absValue << endl;

return 0;
}

83: Program for addition of 2 matrices.

#include <iostream>
using namespace std;

int main() {
int rows, cols, i, j;

github.com/aw-junaid 59
cout << "Enter the number of rows and columns of matrix: ";
cin >> rows >> cols;

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

cout << "Enter the elements of first matrix:\n";

// input matrix1
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
cin >> matrix1[i][j];
}
}

cout << "Enter the elements of second matrix:\n";

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

// add the two matrices


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

cout << "The sum of the two matrices is:\n";

// print the result matrix


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

return 0;
}

github.com/aw-junaid 60
84: Program to find roots of a quadratic equation.

#include <iostream>
#include <cmath>

using namespace std;

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

cout << "Enter coefficients a, b, and c: ";


cin >> a >> b >> c;

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

// Check if discriminant is positive, negative, or zero


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "Roots are real and distinct." << endl;
cout << "Root 1 = " << root1 << endl;
cout << "Root 2 = " << root2 << endl;
} else if (discriminant == 0) {
root1 = -b / (2 * a);
cout << "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 << "Roots are complex and different." << endl;
cout << "Root 1 = " << realPart << "+" << imaginaryPart << "i" << endl;
cout << "Root 2 = " << realPart << "-" << imaginaryPart << "i" << endl;
}

return 0;
}

85: Program to print numerical as Pascal’s triangle pattern.

#include <iostream>
using namespace std;

github.com/aw-junaid 61
int main() {
int rows, coef = 1;

cout << "Enter number of rows: ";


cin >> rows;

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

86: Program to print “*” as inverted Pascal’s triangle pattern.

#include <iostream>
using namespace std;

int main() {
int rows, num=1;
cout << "Enter the number of rows: ";
cin >> rows;

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


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

github.com/aw-junaid 62
num++;
cout << endl;
}
return 0;
}

87: Program to print numerical as Floyd’s triangle pattern.

#include <iostream>
using namespace std;

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

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


cin >> n;

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


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

return 0;
}

88: Program to print “*” as inverted Floyd’s triangle pattern.

#include <iostream>
using namespace std;

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

cout << "Enter number of rows: ";


cin >> rows;

github.com/aw-junaid 63
for(int i = rows; i >= 1; i--)
{
for(int j = 1; j <= i; j++)
{
cout << "* ";
}
cout << endl;
}

return 0;
}

89: Program to print diamond pattern.

#include <iostream>
using namespace std;

int main() {
int n, i, j, space;

cout << "Enter the number of rows (odd number): ";


cin >> n;

// Upper half of the diamond


for (i = 1; i <= n; i += 2) {
for (space = 1; space <= (n - i) / 2; space++) {
cout << " ";
}
for (j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}

// Lower half of the diamond


for (i = n - 2; i >= 1; i -= 2) {
for (space = 1; space <= (n - i) / 2; space++) {
cout << " ";
}
for (j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}

github.com/aw-junaid 64
return 0;
}

90: Program to print ASCII value of digits, uppercase and lowercase


alphabates.

#include <iostream>
using namespace std;

int main() {
// Printing ASCII values of digits
cout << "ASCII values of digits: " << endl;
for (char c = '0'; c <= '9'; ++c) {
cout << c << " = " << int(c) << endl;
}

// Printing ASCII values of uppercase alphabets


cout << "ASCII values of uppercase alphabets: " << endl;
for (char c = 'A'; c <= 'Z'; ++c) {
cout << c << " = " << int(c) << endl;
}
// Printing ASCII values of lowercase alphabets
cout << "ASCII values of lowercase alphabets: " << endl;
for (char c = 'a'; c <= 'z'; ++c) {
cout << c << " = " << int(c) << endl;
}

return 0;
}

91: Program to raise any number x to a positive power n.

#include<iostream>
using namespace std;

int main()
{
int x, n, result=1;
cout<<"Enter the value of x: ";
cin>>x;
cout<<"Enter the value of n: ";
cin>>n;

github.com/aw-junaid 65
for(int i=1; i<=n; i++)
{
result *= x;
}

cout<<x<<" raised to the power "<<n<<" is: "<<result<<endl;


return 0;
}

92: Program to convert given inches into equivalent yard, feet and
inches.

#include <iostream>
using namespace std;

int main() {
int inches;
cout << "Enter the length in inches: ";
cin >> inches;

// Calculate yards, feet and remaining inches


int yards = inches / 36;
int feet = (inches - yards * 36) / 12;
int remaining_inches = inches % 12;

// Display the result


cout << "Equivalent length: " << yards << " yards, " << feet << " feet, " <<
remaining_inches << " inches" << endl;

return 0;
}

93: Program to find ASCII value of a character.

#include <iostream>
using namespace std;

int main() {
char ch;
cout << "Enter a character: ";
cin >> ch;
cout << "The ASCII value of " << ch << " is " << int(ch) << endl;
return 0;
}
github.com/aw-junaid 66
94: Program to reverse all the strings stored in an array.

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

int main() {
const int SIZE = 5;
string arr[SIZE] = {"apple", "banana", "cherry", "date", "elderberry"};

// Print original array


cout << "Original array: " << endl;
for (int i = 0; i < SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;

// Reverse each string in the array


for (int i = 0; i < SIZE; i++) {
int j = arr[i].length() - 1;
for (int k = 0; k < j; k++, j--) {
char temp = arr[i][k];
arr[i][k] = arr[i][j];
arr[i][j] = temp;
}
}

// Print reversed array


cout << "Reversed array: " << endl;
for (int i = 0; i < SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

95: Program to search an element in an array using binary search.

#include <iostream>
using namespace std;

// Binary search function

github.com/aw-junaid 67
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;

if (arr[mid] == x) {
return mid;
}

if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}

return binarySearch(arr, mid + 1, r, x);


}

return -1;
}

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

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

cout << "Enter element to search: ";


cin >> x;

int result = binarySearch(arr, 0, n - 1, x);


if (result == -1) {
cout << "Element not found\n";
} else {
cout << "Element found at index " << result << "\n";
}

return 0;
}

github.com/aw-junaid 68
96: Program for decimal to octal converter.

#include <iostream>
using namespace std;

int main() {
int decimalNumber, quotient, remainder;
int octalNumber[100], i = 1;

cout << "Enter a decimal number: ";


cin >> decimalNumber;

quotient = decimalNumber;

while (quotient != 0) {
octalNumber[i++] = quotient % 8;
quotient /= 8;
}

cout << "Octal number is: ";


for (int j = i - 1; j > 0; j--) {
cout << octalNumber[j];
}

return 0;
}

97: Convert large binary number to hexadecimal.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string binaryToHex(string binary) {


// Pad the binary number with zeros if necessary
while (binary.length() % 4 != 0) {
binary = "0" + binary;
}

string hex = "";


for (int i = 0; i < binary.length(); i += 4) {

github.com/aw-junaid 69
string group = binary.substr(i, 4);
if (group == "0000") hex += "0";
else if (group == "0001") hex += "1";
else if (group == "0010") hex += "2";
else if (group == "0011") hex += "3";
else if (group == "0100") hex += "4";
else if (group == "0101") hex += "5";
else if (group == "0110") hex += "6";
else if (group == "0111") hex += "7";
else if (group == "1000") hex += "8";
else if (group == "1001") hex += "9";
else if (group == "1010") hex += "A";
else if (group == "1011") hex += "B";
else if (group == "1100") hex += "C";
else if (group == "1101") hex += "D";
else if (group == "1110") hex += "E";
else if (group == "1111") hex += "F";
}

return hex;
}

int main() {
string binary =
"1010101010101010101010101010101010101010101010101010101010101010";
string hex = binaryToHex(binary);
cout << hex << endl; // Output: "AAAAAAAA"
return 0;
}

98: Program for hexadecimal to binary conversion.

#include <iostream>
#include <string>

using namespace std;

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

string binNum = "";

github.com/aw-junaid 70
int len = hexNum.length();

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


char hexDigit = hexNum[i];
int decDigit;

if(hexDigit >= '0' && hexDigit <= '9') {


decDigit = hexDigit - '0';
} else if(hexDigit >= 'A' && hexDigit <= 'F') {
decDigit = hexDigit - 'A' + 10;
} else if(hexDigit >= 'a' && hexDigit <= 'f') {
decDigit = hexDigit - 'a' + 10;
}

for(int j = 3; j >= 0; j--) {


if(decDigit >= (1 << j)) {
binNum += '1';
decDigit -= (1 << j);
} else {
binNum += '0';
}
}
}

cout << "The binary equivalent is " << binNum << endl;

return 0;
}

99: Program to convert octal number to decimal number.

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

int octalToDecimal(int octal);

int main() {
int octalNumber;
cout << "Enter an octal number: ";
cin >> octalNumber;
cout << octalNumber << " in octal = " << octalToDecimal(octalNumber) << " in
decimal";

github.com/aw-junaid 71
return 0;
}

int octalToDecimal(int octal) {


int decimal = 0, i = 0;
while (octal != 0) {
decimal += (octal % 10) * pow(8, i);
++i;
octal /= 10;
}
return decimal;
}

100: Program to covert each digits of a number in English word.

#include <iostream>
using namespace std;

// function to convert a digit to its English word equivalent


string convertDigit(int digit) {
switch(digit) {
case 0: return "Zero";
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
default: return "Invalid digit";
}
}

// function to convert the number to its English word equivalent


string convertNumber(int number) {
if (number == 0) {
return convertDigit(0);
}
string word = "";
while (number != 0) {
int digit = number % 10;

github.com/aw-junaid 72
word = convertDigit(digit) + " " + word;
number /= 10;
}
return word;
}

int main() {
int number;
cout << "Enter a number: ";
cin >> number;
string word = convertNumber(number);
cout << "The number in words is: " << word << endl;
return 0;
}

101: Program for multiplication of two binary numbers.

#include <iostream>
using namespace std;

int binaryToDecimal(int n) {
int ans = 0, base = 1;
while(n > 0) {
int rem = n % 10;
ans += rem * base;
base *= 2;
n /= 10;
}
return ans;
}

int decimalToBinary(int n) {
int ans = 0, base = 1;
while(n > 0) {
int rem = n % 2;
ans += rem * base;
base *= 10;
n /= 2;
}
return ans;
}

int multiplyBinary(int n1, int n2) {

github.com/aw-junaid 73
int ans = 0, base = 1;
while(n2 > 0) {
int bit = n2 % 10;
if(bit == 1) {
ans += n1 * base;
}
base *= 10;
n2 /= 10;
}
return ans;
}

int main() {
int n1, n2;
cout << "Enter two binary numbers: ";
cin >> n1 >> n2;
int decimal1 = binaryToDecimal(n1);
int decimal2 = binaryToDecimal(n2);
int product = decimal1 * decimal2;
int binaryProduct = decimalToBinary(product);
cout << "Product of " << n1 << " and " << n2 << " is: " << binaryProduct << endl;
return 0;
}

102: Program which prints initial of any name.

#include <iostream>
using namespace std;

int main() {
string name;
cout << "Enter a name: ";
getline(cin, name); // read the full name including spaces

// print the first character of the name and each character after a space
for (int i = 0; i < name.length(); i++) {
if (i == 0 || name[i - 1] == ' ') {
cout << name[i];
}
}

return 0;
}

github.com/aw-junaid 74
103: Program to concatenate two strings.

#include <iostream>
#include <cstring>

using namespace std;

int main() {
char str1[50], str2[50];
cout << "Enter the first string: ";
cin.getline(str1, 50);
cout << "Enter the second string: ";
cin.getline(str2, 50);
strcat(str1, str2);
cout << "Concatenated string is: " << str1 << endl;
return 0;
}

104: Program to find length of a string.

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
char str[100];
int len;

cout << "Enter a string: ";


cin >> str;

len = strlen(str);

cout << "Length of the string is: " << len << endl;

return 0;
}

105: Program to find substring in String (Pattern Matching).

github.com/aw-junaid 74
#include <iostream>
#include <string>

using namespace std;

int main() {
string str, substr;
cout << "Enter the main string: ";
getline(cin, str);
cout << "Enter the substring: ";
getline(cin, substr);

int n = str.length();
int m = substr.length();

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


int j;
for(j = 0; j < m; j++) {
if(str[i + j] != substr[j])
break;
}
if(j == m) {
cout << "Substring found at index " << i << endl;
return 0;
}
}
cout << "Substring not found!" << endl;
return 0;
}

106: Program to remove spaces from string.

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

int main() {
string str;
getline(cin, str); // Taking input string

string newStr = ""; // Empty string to store new string without spaces

// Loop through the string and add characters to new string if it is not a space

github.com/aw-junaid 75
for (int i = 0; i < str.length(); i++) {
if (str[i] != ' ') {
newStr += str[i];
}
}

// Printing the new string without spaces


cout << "New String: " << newStr;

return 0;
}
107: Program to find compound interest.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double principle, rate, time, compound_interest;

// Input principle amount


cout << "Enter principle amount: ";
cin >> principle;

// Input rate of interest


cout << "Enter rate of interest: ";
cin >> rate;

// Input time period


cout << "Enter time period (in years): ";
cin >> time;

// Calculate compound interest


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

// Display the result


cout << "Compound interest = " << compound_interest << endl;

return 0;
}

github.com/aw-junaid 76
108: Program to convert given no. of days into years, weeks and days.
#include <iostream>
using namespace std;

int main() {
int days, years, weeks;

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


cin >> days;

years = days / 365;


days = days % 365;

weeks = days / 7;
days = days % 7;

cout << "Equivalent years: " << years << endl;


cout << "Equivalent weeks: " << weeks << endl;
cout << "Equivalent days: " << days << endl;

return 0;
}

109: Program to find cube of a number using macros.

#include <iostream>
#define CUBE(x) (x * x * x)

using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Cube of " << num << " is: " << CUBE(num) << endl;
return 0;
}

110: Program to insert an element in an array.

#include <iostream>
using namespace std;

github.com/aw-junaid 77
int main() {
int arr[50], size, pos, value;

cout << "Enter the size of the array: ";


cin >> size;

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


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

cout << "Enter the position to insert the element: ";


cin >> pos;

cout << "Enter the value to insert: ";


cin >> value;

// Shift the elements to the right of pos to create space for the new element
for (int i = size - 1; i >= pos; i--) {
arr[i + 1] = arr[i];
}

// Insert the new element at the specified position


arr[pos] = value;

size++; // Increase the size of the array

cout << "Array after insertion: ";


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

return 0;
}

111: Program to find sum of diagonal elements of a matrix.

#include <iostream>
using namespace std;

int main() {
int matrix[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};

github.com/aw-junaid 78
int main() {
int matrix[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int sum = 0;

// Loop through the diagonal elements of the matrix and add them up
for (int i = 0; i < 3; i++) {
sum += matrix[i][i];
}

// Output the sum of the diagonal elements


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

return 0;
}

112: Program to check whether two matrices are equal or not.

#include <iostream>
using namespace std;

int main() {
int matrix1[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int matrix2[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};

bool equal = true;

// Loop through all elements of the matrices and check if they are equal
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix1[i][j] != matrix2[i][j]) {
equal = false;
break;
}
}
if (!equal) {
break;

github.com/aw-junaid 79
}
}

// Output the result


if (equal) {
cout << "Matrices are equal." << endl;
} else {
cout << "Matrices are not equal." << endl;
}

return 0;
}

113: Program to check whether a given matrix is identity matrix or not.

#include <iostream>
using namespace std;

int main() {
int matrix[3][3] = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};

bool is_identity = true;

// Loop through all elements of the matrix and check if they are equal to 1 on the
diagonal and 0 elsewhere
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j && matrix[i][j] != 1) {
is_identity = false;
break;
}
if (i != j && matrix[i][j] != 0) {
is_identity = false;
break;
}
}
if (!is_identity) {
break;
}
}

github.com/aw-junaid 80
// Output the result
if (is_identity) {
cout << "Matrix is an identity matrix." << endl;
} else {
cout << "Matrix is not an identity matrix." << endl;
}

return 0;
}

114: Program to check whether a given matrix is a sparse matrix or


dense matrix.

#include <iostream>
using namespace std;

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

int num_zeros = 0;

// Loop through all elements of the matrix and count the number of zeros
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 0) {
num_zeros++;
}
}
}

// Calculate the ratio of zeros to non-zeros


float ratio = (float) num_zeros / (3 * 3);

// Output the result


if (ratio > 0.5) {
cout << "Matrix is a sparse matrix." << endl;
} else {
cout << "Matrix is a dense matrix." << endl;
}

return 0;
}
github.com/aw-junaid 81
115: Program to calculate sum of the elements of each row and
column.

#include <iostream>
using namespace std;

int main() {
int matrix[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int row_sum[3] = {0}; // Initialize all elements to zero
int col_sum[3] = {0}; // Initialize all elements to zero

// Calculate the sum of each row


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
row_sum[i] += matrix[i][j];
}
}

// Calculate the sum of each column


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
col_sum[j] += matrix[i][j];
}
}

// Output the row sums


cout << "Row sums: ";
for (int i = 0; i < 3; i++) {
cout << row_sum[i] << " ";
}
cout << endl;

// Output the column sums


cout << "Column sums: ";
for (int i = 0; i < 3; i++) {
cout << col_sum[i] << " ";
}
cout << endl;

return 0;
}

github.com/aw-junaid 82
116: Program to find the frequency of odd and even numbers in the
given matrix.

#include <iostream>
using namespace std;

int main() {
int matrix[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int odd_freq = 0;
int even_freq = 0;

// Count the frequency of odd and even numbers


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] % 2 == 0) {
even_freq++;
} else {
odd_freq++;
}
}
}

// Output the results


cout << "Frequency of even numbers: " << even_freq << endl;
cout << "Frequency of odd numbers: " << odd_freq << endl;

return 0;
}

117: Program for swapping of two arrays.

#include <iostream>
using namespace std;

const int ARRAY_SIZE = 5; // change this to adjust the size of the arrays

void swapArrays(int arr1[], int arr2[], int size) {


for (int i = 0; i < size; i++) {
int temp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = temp;

github.com/aw-junaid 83
}
}

int main() {
int array1[ARRAY_SIZE] = {1, 2, 3, 4, 5};
int array2[ARRAY_SIZE] = {6, 7, 8, 9, 10};

// Before swapping
cout << "Array 1: ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array1[i] << " ";
}
cout << endl;
cout << "Array 2: ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array2[i] << " ";
}
cout << endl;

// Swap the arrays


swapArrays(array1, array2, ARRAY_SIZE);

// After swapping
cout << "Array 1: ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array1[i] << " ";
}
cout << endl;
cout << "Array 2: ";
for (int i = 0; i < ARRAY_SIZE; i++) {
cout << array2[i] << " ";
}
cout << endl;

return 0;
}

118: Program to print upper triangular matrix.

#include <iostream>
using namespace std;

const int MATRIX_SIZE = 3; // change this to adjust the size of the matrix

github.com/aw-junaid 84
void printUpperTriangular(int matrix[MATRIX_SIZE][MATRIX_SIZE]) {
cout << "Upper Triangular Matrix: " << endl;
for(int i = 0; i < MATRIX_SIZE; i++) {
for(int j = 0; j < MATRIX_SIZE; j++) {
if(j >= i) {
cout << matrix[i][j] << " ";
} else {
cout << "0 ";
}
}
cout << endl;
}
}

int main() {
int matrix[MATRIX_SIZE][MATRIX_SIZE] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

printUpperTriangular(matrix);

return 0;
}

119: Program for multiplication of two matrices.

#include <iostream>
using namespace std;

const int ROWS_1 = 2; // number of rows in first matrix


const int COLS_1 = 3; // number of columns in first matrix
const int ROWS_2 = 3; // number of rows in second matrix
const int COLS_2 = 2; // number of columns in second matrix

void matrixMultiplication(int matrix1[][COLS_1], int matrix2[][COLS_2], int result[]


[COLS_2]) {
// Initialize result matrix with 0s
for(int i = 0; i < ROWS_1; i++) {
for(int j = 0; j < COLS_2; j++) {
result[i][j] = 0;

github.com/aw-junaid 85
}
}
// Perform matrix multiplication
for(int i = 0; i < ROWS_1; i++) {
for(int j = 0; j < COLS_2; j++) {
for(int k = 0; k < ROWS_2; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}

void printMatrix(int matrix[][COLS_2]) {


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

int main() {
int matrix1[ROWS_1][COLS_1] = {
{1, 2, 3},
{4, 5, 6}
};
int matrix2[ROWS_2][COLS_2] = {
{7, 8},
{9, 10},
{11, 12}
};
int result[ROWS_1][COLS_2];

matrixMultiplication(matrix1, matrix2, result);

cout << "Result of matrix multiplication:" << endl;


printMatrix(result);

return 0;
}

github.com/aw-junaid 86
120: Program to find inverse of a matrix.

#include <iostream>
using namespace std;

const int N = 3; // size of matrix

void getCofactor(float A[N][N], float temp[N][N], int p, int q, int n) {


int i = 0, j = 0;
for(int row = 0; row < n; row++) {
for(int col = 0; col < n; col++) {
if(row != p && col != q) {
temp[i][j++] = A[row][col];
if(j == n-1) {
j = 0;
i++;
}
}
}
}
}

float determinant(float A[N][N], int n) {


float det = 0;
if(n == 1) {
return A[0][0];
}
float temp[N][N];
int sign = 1;
for(int i = 0; i < n; i++) {
getCofactor(A, temp, 0, i, n);
det += sign * A[0][i] * determinant(temp, n-1);
sign = -sign;
}
return det;
}

void adjugate(float A[N][N], float adj[N][N]) {


int sign = 1;
float temp[N][N];
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
getCofactor(A, temp, i, j, N);

github.com/aw-junaid 86
sign = ((i+j) % 2 == 0) ? 1 : -1;
adj[j][i] = sign * determinant(temp, N-1);
}
}
}

bool inverse(float A[N][N], float inverse[N][N]) {


float det = determinant(A, N);
if(det == 0) {
cout << "Matrix is not invertible" << endl;
return false;
}
float adj[N][N];
adjugate(A, adj);
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
inverse[i][j] = adj[i][j] / det;
}
}
return true;
}

void printMatrix(float A[N][N]) {


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

int main() {
float A[N][N] = {
{1, 2, 3},
{0, 1, 4},
{5, 6, 0}
};
float inverseA[N][N];
if(inverse(A, inverseA)) {
cout << "Inverse of matrix A:" << endl;
printMatrix(inverseA);
}
return 0;
}

github.com/aw-junaid 87
121: Program to find transpose of matrix.

#include <iostream>
using namespace std;

const int ROW = 3;


const int COL = 3;

void transpose(int A[][COL], int B[][ROW]) {


for(int i = 0; i < ROW; i++) {
for(int j = 0; j < COL; j++) {
B[j][i] = A[i][j];
}
}
}

void printMatrix(int A[][COL]) {


for(int i = 0; i < ROW; i++) {
for(int j = 0; j < COL; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}

int main() {
int A[ROW][COL] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int B[COL][ROW];
transpose(A, B);
cout << "Matrix A:" << endl;
printMatrix(A);
cout << "Transpose of matrix A:" << endl;
printMatrix(B);
return 0;
}

122: Program to find determinant of a matrix.

github.com/aw-junaid 88
#include <iostream>
using namespace std;

int main() {
int A[2][2] = { // define the input matrix
{1, 2},
{3, 4}
};
int det = A[0][0] * A[1][1] - A[0][1] * A[1][0]; // compute the determinant of the matrix
cout << "Determinant of the matrix:" << endl;
cout << det << endl; // print the determinant value
return 0;
}

123: Program to find the second largest element in an array.

#include <iostream>
using namespace std;

int main() {
int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; // define the input array
int n = 10; // size of the array
int largest = arr[0]; // initialize largest and second largest
int secondLargest = arr[0];

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


if(arr[i] > largest) { // if current element is greater than largest
secondLargest = largest; // set second largest as previous largest
largest = arr[i]; // set largest as current element
} else if(arr[i] > secondLargest && arr[i] != largest) { // if current element is
greater than second largest and not equal to largest
secondLargest = arr[i]; // set second largest as current element
}
}

cout << "The second largest element in the array is: " << secondLargest << endl; //
print second largest element
return 0;
}

124: Program to find the second smallest element in an array.

github.com/aw-junaid 89
#include <iostream>
#include <climits> // for using INT_MAX
using namespace std;

int main() {
int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; // define the input array
int n = 10; // size of the array
int smallest = INT_MAX; // initialize smallest and second smallest
int secondSmallest = INT_MAX;

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


if(arr[i] < smallest) { // if current element is smaller than smallest
secondSmallest = smallest; // set second smallest as previous smallest
smallest = arr[i]; // set smallest as current element
} else if(arr[i] < secondSmallest && arr[i] != smallest) { // if current element is
smaller than second smallest and not equal to smallest
secondSmallest = arr[i]; // set second smallest as current element
}
}

cout << "The second smallest element in the array is: " << secondSmallest <<
endl; // print second smallest element
return 0;
}

125: Program to insert an element in an array at desired position.

#include <iostream>
using namespace std;

int main() {
int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; // define the input array
int n = 10; // size of the array
int position = 3; // position to insert the element
int element = 25; // element to be inserted

// shift the elements to the right from the end of the array until the desired position
for(int i = n - 1; i >= position; i--) {
arr[i + 1] = arr[i];
}

// insert the element at the desired position


arr[position] = element;

github.com/aw-junaid 90
// increment the size of the array
n++;

// print the new array


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

return 0;
}

126: Program to remove duplicate elements in an array.

#include <iostream>
using namespace std;

int main() {
int arr[10] = {1, 2, 2, 3, 4, 4, 5, 5, 6, 6}; // define the input array
int n = 10; // size of the array

// loop over the array elements


for(int i = 0; i < n; i++) {
// loop over the remaining elements after i
for(int j = i + 1; j < n; j++) {
// check if there is a duplicate element
if(arr[i] == arr[j]) {
// shift the elements to the left
for(int k = j; k < n - 1; k++) {
arr[k] = arr[k + 1];
}
// decrement the size of the array
n--;
// decrement j to avoid skipping elements
j--;
}
}
}
// print the new array without duplicates
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}

github.com/aw-junaid 91
127: Program to compare two strings using “strcmp” functions.

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

int main() {
char str1[] = "hello";
char str2[] = "world";

int result = strcmp(str1, str2);

if(result == 0) {
cout << "The two strings are equal" << endl;
} else if(result < 0) {
cout << "The first string is less than the second string" << endl;
} else {
cout << "The first string is greater than the second string" << endl;
}

return 0;
}

128: Program to compare two strings without using string functions.

#include <iostream>
using namespace std;

int main() {
char str1[100], str2[100];
int i, j, flag = 0;

cout << "Enter the first string: ";


cin >> str1;

cout << "Enter the second string: ";


cin >> str2;

for(i = 0; str1[i] != '\0'; i++);


for(j = 0; str2[j] != '\0'; j++);

if(i != j) {
cout << "The two strings are not equal" << endl;

github.com/aw-junaid 92
return 0;
}

for(i = 0; str1[i] != '\0'; i++) {


if(str1[i] != str2[i]) {
flag = 1;
break;
}
}

if(flag == 0) {
cout << "The two strings are equal" << endl;
} else {
cout << "The two strings are not equal" << endl;
}

return 0;
}

129: Program to find length of string using “strlen” function.

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

int main() {
char str[100];

cout << "Enter a string: ";


cin >> str;

int length = strlen(str);

cout << "The length of the string is: " << length << endl;

return 0;
}

130: Program to copy string using “strcpy” library function.

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

github.com/aw-junaid 93
int main() {
char sourceStr[100], destStr[100];

cout << "Enter a string to copy: ";


cin >> sourceStr;

strcpy(destStr, sourceStr);

cout << "The copied string is: " << destStr << endl;

return 0;
}

131: Program to copy string without using strcpy library function.

#include <iostream>
using namespace std;

int main() {
char sourceStr[100], destStr[100];
int i = 0;

cout << "Enter a string to copy: ";


cin >> sourceStr;

while (sourceStr[i] != '\0') {


destStr[i] = sourceStr[i];
i++;
}
destStr[i] = '\0';

cout << "The copied string is: " << destStr << endl;

return 0;
}

132: Program to reverse a string using “strrev” library function.

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

void reverseString(char *str);

github.com/aw-junaid 94
int main() {
char str[100];

cout << "Enter a string: ";


cin.getline(str, 100);

reverseString(str);

cout << "The reversed string is: " << str << endl;

return 0;
}

void reverseString(char *str) {


int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}

133: Program for Swapping of strings.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
string str1, str2;

cout << "Enter the first string: ";


getline(cin, str1);

cout << "Enter the second string: ";


getline(cin, str2);

cout << "Before swapping:" << endl;


cout << "String 1 = " << str1 << endl;
cout << "String 2 = " << str2 << endl;

github.com/aw-junaid 95
cout << "String 2 = " << str2 << endl;

swap(str1, str2);

cout << "After swapping:" << endl;


cout << "String 1 = " << str1 << endl;
cout << "String 2 = " << str2 << endl;

return 0;
}

134: Program to delete vowels from string.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string removeVowels(string str) {


string vowels = "aeiouAEIOU";
for (int i = 0; i < str.length(); i++) {
if (vowels.find(str[i]) != string::npos) {
str.erase(i, 1);
i--;
}
}
return str;
}

int main() {
string str;

cout << "Enter a string: ";


getline(cin, str);

cout << "Before removing vowels: " << str << endl;

str = removeVowels(str);

cout << "After removing vowels: " << str << endl;

return 0;
}

github.com/aw-junaid 96
135: Program to find number of vowels, consonants, digits and white
space.

#include <iostream>
#include <string>
#include <cctype>

using namespace std;


int main() {
string str;
int vowels = 0, consonants = 0, digits = 0, whitespace = 0;

cout << "Enter a string: ";


getline(cin, str);

for (int i = 0; i < str.length(); i++) {


if (isalpha(str[i])) { // If it's an alphabetic character
if (tolower(str[i]) == 'a' || tolower(str[i]) == 'e' || tolower(str[i]) == 'i' ||
tolower(str[i]) == 'o' || tolower(str[i]) == 'u') {
vowels++;
} else {
consonants++;
}
} else if (isdigit(str[i])) { // If it's a digit
digits++;
} else if (isspace(str[i])) { // If it's a whitespace character
whitespace++;
}
}

cout << "Number of vowels: " << vowels << endl;


cout << "Number of consonants: " << consonants << endl;
cout << "Number of digits: " << digits << endl;
cout << "Number of whitespace characters: " << whitespace << endl;

return 0;
}

136: Program to check whether two strings are anagrams or not.

#include <iostream>
#include <algorithm>
#include <cstring>

github.com/aw-junaid 97
using namespace std;

int main()
{
char str1[100], str2[100];

cout << "Enter first string: ";


cin.getline(str1, 100);

cout << "Enter second string: ";


cin.getline(str2, 100);

int len1 = strlen(str1);


int len2 = strlen(str2);

if (len1 != len2) {
cout << "Strings are not anagrams of each other." << endl;
return 0;
}

sort(str1, str1 + len1);


sort(str2, str2 + len2);

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


if (str1[i] != str2[i]) {
cout << "Strings are not anagrams of each other." << endl;
return 0;
}
}

cout << "Strings are anagrams of each other." << endl;

return 0;
}

137: Program to reverse a string using both recursion and iteration.

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

// Function to reverse a string using iteration


void reverseStringIteration(char str[]) {

github.com/aw-junaid 98
138: Program to find size of structure data type without using size of
operator.

#include <iostream>
using namespace std;

struct MyStruct {
int x;
char c;
float f;
};

int main() {
MyStruct* ptr1 = nullptr;
MyStruct* ptr2 = nullptr;

ptr1 = new MyStruct;


ptr2 = ptr1 + 1;

cout << "Size of MyStruct = " << (char*)ptr2 - (char*)ptr1 << " bytes" << endl;

delete ptr1;
ptr1 = nullptr;
ptr2 = nullptr;

return 0;
}

github.com/aw-junaid 99
139: Program to store and display information of single student using
structure.

#include <iostream>
using namespace std;

struct Student {
string name;
int rollNo;
float marks;
};

int main() {
// declare a Student variable
Student s;

// read information from user


cout << "Enter name of student: ";
getline(cin, s.name);
cout << "Enter roll number of student: ";
cin >> s.rollNo;
cout << "Enter marks of student: ";
cin >> s.marks;

// display information of student


cout << "\nStudent Information" << endl;
cout << "Name: " << s.name << endl;
cout << "Roll Number: " << s.rollNo << endl;
cout << "Marks: " << s.marks << endl;

return 0;
}

github.com/aw-junaid 100
140: Program to read and print details of 50 students using structure.

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

struct Student {
string name;
int rollNo;
float marks;
};

int main() {
// declare an array of 50 students
Student students[50];

// read details of 50 students from user


for (int i = 0; i < 50; i++) {
cout << "\nEnter details of student " << i+1 << endl;
cout << "Name: ";
getline(cin, students[i].name);
cout << "Roll Number: ";
cin >> students[i].rollNo;
cout << "Marks: ";
cin >> students[i].marks;
cin.ignore(); // to clear input buffer
}

// display details of all 50 students


cout << "\nDetails of all 50 students:" << endl;
for (int i = 0; i < 50; i++) {
cout << "\nStudent " << i+1 << " Details" << endl;
cout << "Name: " << students[i].name << endl;
cout << "Roll Number: " << students[i].rollNo << endl;
cout << "Marks: " << students[i].marks << endl;
}

return 0;
}

141: Program to print sum of two complex numbers by passing


structure to a function.

github.com/aw-junaid 101
#include <iostream>
using namespace std;

// define a structure for complex numbers


struct ComplexNumber {
double realPart;
double imaginaryPart;
};

// function to add two complex numbers


ComplexNumber addComplexNumbers(ComplexNumber num1, ComplexNumber
num2) {
ComplexNumber sum;
sum.realPart = num1.realPart + num2.realPart;
sum.imaginaryPart = num1.imaginaryPart + num2.imaginaryPart;
return sum;
}

int main() {
// create two complex numbers
ComplexNumber num1, num2;

// read the values of the first complex number


cout << "Enter the real part of the first complex number: ";
cin >> num1.realPart;
cout << "Enter the imaginary part of the first complex number: ";
cin >> num1.imaginaryPart;

// read the values of the second complex number


cout << "Enter the real part of the second complex number: ";
cin >> num2.realPart;
cout << "Enter the imaginary part of the second complex number: ";
cin >> num2.imaginaryPart;

// add the two complex numbers


ComplexNumber sum = addComplexNumbers(num1, num2);

// print the sum of the two complex numbers


cout << "The sum of the two complex numbers is: " << sum.realPart << " + " <<
sum.imaginaryPart << "i" << endl;

return 0;
}

github.com/aw-junaid 102
142: Program to see difference between union and structure.

#include<iostream>
using namespace std;

struct ExampleStruct {
int a;
char b;
float c;
};

union ExampleUnion {
int a;
char b;
float c;
};

int main() {
ExampleStruct s;
ExampleUnion u;

cout << "Size of Structure: " << sizeof(s) << endl; // Output: 12
cout << "Size of Union: " << sizeof(u) << endl; // Output: 4

s.a = 10;
s.b = 'A';
s.c = 1.5;

u.a = 10;
cout << "a: " << u.a << endl; // Output: 10
cout << "b: " << u.b << endl; // Output: (Empty)
cout << "c: " << u.c << endl; // Output: 2.8026e-45

u.b = 'A';
cout << "a: " << u.a << endl; // Output: 167772160 (Garbage Value)
cout << "b: " << u.b << endl; // Output: A
cout << "c: " << u.c << endl; // Output: 2.8026e-45

return 0;
}

github.com/aw-junaid 103
143: Program to find largest and second largest no from a 2D array.

#include <iostream>
using namespace std;

const int ROWS = 3; // Number of rows in the 2D array


const int COLS = 4; // Number of columns in the 2D array

int main() {
int arr[ROWS][COLS] = {{10, 20, 30, 40}, {50, 60, 70, 80}, {90, 100, 110, 120}}; //
The 2D array to be checked
int largest = arr[0][0]; // Initializing the largest variable to the first element in the
array
int secondLargest = arr[0][0]; // Initializing the second largest variable to the first
element in the array

// Looping through the entire 2D array


for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (arr[i][j] > largest) {
secondLargest = largest; // The current largest number becomes the
second largest
largest = arr[i][j]; // Updating the largest variable with the new largest
number
}
else if (arr[i][j] > secondLargest && arr[i][j] != largest) {
secondLargest = arr[i][j]; // Updating the second largest variable with the
new second largest number
}
}
}

cout << "The largest number in the 2D array is: " << largest << endl;
cout << "The second largest number in the 2D array is: " << secondLargest <<
endl;

return 0;
}

github.com/aw-junaid 104
144: Program to do linear search in Array.

#include <iostream>
using namespace std;

int linearSearch(int arr[], int n, int key) {


for(int i=0; i<n; i++) {
if(arr[i] == key) {
return i; // Return index if element is found
}
}
return -1; // Return -1 if element is not found
}

int main() {
int n, key;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n];
cout<<"Enter the array elements: ";
for(int i=0; i<n; i++) {
cin>>arr[i];
}
cout<<"Enter the key to be searched: ";
cin>>key;
int index = linearSearch(arr, n, key);
if(index == -1) {
cout<<"Element not found!";
}
else {
cout<<"Element found at index "<<index;
}
return 0;
}

145: Program and algorithm for selection Sort.

#include <iostream>
using namespace std;

void selectionSort(int arr[], int n) {


int i, j, min_idx;

github.com/aw-junaid 105
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++) {
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);

selectionSort(arr, n);

// Print the sorted array


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

146: Program and algorithm for insertion Sort.

#include <iostream>
using namespace std;

void insertionSort(int arr[], int n) {


int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j = j - 1;
}

github.com/aw-junaid 106
arr[j + 1] = key;
}
}

int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

cout << "Sorted Array: ";


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

return 0;
}

147: Program to find whether a square matrix is a) symmetric b) skew


symmetric c) none of two.

#include <iostream>
using namespace std;

const int MAX = 100;

int main() {
int n, i, j, flag = 1;
int mat[MAX][MAX];

cout << "Enter the size of the square matrix: ";


cin >> n;

cout << "Enter the elements of the matrix:\n";


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

// Check if matrix is symmetric


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

github.com/aw-junaid 107
cin >> mat[i][j];
}
}

// Check if matrix is symmetric


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (mat[i][j] != mat[j][i]) {
flag = 0;
break;
}
}
if (flag == 0) {
break;
}
}
if (flag == 1) {
cout << "Matrix is symmetric\n";
}

// Check if matrix is skew-symmetric


flag = 1;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (mat[i][j] != -mat[j][i]) {
flag = 0;
break;
}
}
if (flag == 0) {
break;
}
}
if (flag == 1) {
cout << "Matrix is skew-symmetric\n";
}

// Check if matrix is none of the two


if (flag == 0) {
cout << "Matrix is none of the two\n";
}

return 0;
}

github.com/aw-junaid 108
148: Program for linked list representation of linear queue.

#include <iostream>
using namespace std;

// Define a structure for the node


struct Node {
int data;
Node* next;
};

// Define a class for the queue


class Queue {
private:
Node* front;
Node* rear;
public:
// Constructor
Queue() {
front = NULL;
rear = NULL;
}

// Function to check if the queue is empty


bool isEmpty() {
return (front == NULL);
}

// Function to enqueue an element to the queue


void enqueue(int x) {
Node* temp = new Node;
temp->data = x;
temp->next = NULL;
if (front == NULL && rear == NULL) {
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}

// Function to dequeue an element from the queue

github.com/aw-junaid 109
void dequeue() {
Node* temp = front;
if (front == NULL) {
cout << "Queue is empty" << endl;
return;
}
if (front == rear) {
front = rear = NULL;
}
else {
front = front->next;
}
delete temp;
}

// Function to display the queue


void display() {
Node* temp = front;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

// Function to get the front element of the queue


int frontElement() {
if (front == NULL) {
cout << "Queue is empty" << endl;
return -1;
}
return front->data;
}
};

int main() {
// Create an object of the Queue class
Queue q;
// Enqueue elements to the queue
q.enqueue(5);
q.enqueue(10);
q.enqueue(15);

github.com/aw-junaid 110
q.enqueue(20);
// Display the queue
cout << "Queue elements: ";
q.display();
// Dequeue an element from the queue
q.dequeue();
// Display the queue after dequeuing an element
cout << "Queue elements: ";
q.display();
// Get the front element of the queue
cout << "Front element of the queue: " << q.frontElement() << endl;
// Check if the queue is empty
if (q.isEmpty()) {
cout << "Queue is empty" << endl;
}
else {
cout << "Queue is not empty" << endl;
}
return 0;
}

149: Program to perform a PUSH operation on a dynamically allocated


stack.

#include <iostream>
using namespace std;

// Define structure for stack node


struct StackNode {
int data;
StackNode* next;
};

// Define class for dynamic stack


class DynamicStack {
private:
StackNode* top;
public:
// Constructor
DynamicStack() {
top = NULL;
}
// Destructor

github.com/aw-junaid 111
~DynamicStack() {
while (top != NULL) {
StackNode* temp = top;
top = top->next;
delete temp;
}
}
// Function to push a new element on top of stack
void push(int data) {
StackNode* new_node = new StackNode;
new_node->data = data;
new_node->next = top;
top = new_node;
cout << "Pushed " << data << " onto the stack." << endl;
}
};

int main() {
// Create dynamic stack object
DynamicStack my_stack;

// Push some elements onto the stack


my_stack.push(10);
my_stack.push(20);
my_stack.push(30);

return 0;
}

150: Program to swap two numbers using class.

#include<iostream>
using namespace std;

class SwapNumbers {
private:
int a, b;
public:
void input() {
cout << "Enter two numbers to be swapped:" << endl;
cin >> a >> b;
}
void swap() {

github.com/aw-junaid 112
int temp = a;
a = b;
b = temp;
}
void display() {
cout << "After swapping, the numbers are: " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
};

int main() {
SwapNumbers obj;
obj.input();
obj.swap();
obj.display();
return 0;
}

151: Program to count occurrence of a word in a text file.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string filename, word;
int count = 0;
cout << "Enter the file name: ";
cin >> filename;
cout << "Enter the word to be counted: ";
cin >> word;

ifstream file(filename);
string temp;

while (file >> temp) {


if (temp == word) {
count++;

github.com/aw-junaid 113
}
}

cout << "The word '" << word << "' appears " << count << " times in the file." <<
endl;
return 0;
}

152: Program to copy files.

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

int main() {
ifstream in_file;
ofstream out_file;
char ch;
string filename1, filename2;
cout << "Enter input file name: ";
cin >> filename1;
cout << "Enter output file name: ";
cin >> filename2;
in_file.open(filename1);
out_file.open(filename2);
if (!in_file) {
cout << "Unable to open input file!";
return 1;
}
if (!out_file) {
cout << "Unable to open output file!";
return 1;
}
while (in_file.get(ch)) {
out_file.put(ch);
}
cout << "File copied successfully!";
in_file.close();
out_file.close();
return 0;
}

github.com/aw-junaid 114
153: Program to merge two files.

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

int main() {
// open first file in read mode
ifstream file1("file1.txt");

// open second file in read mode


ifstream file2("file2.txt");

// open new file in write mode


ofstream mergeFile("mergeFile.txt");

// check if both files are open or not


if (!file1.is_open() || !file2.is_open()) {
cout << "Failed to open files!";
return 0;
}

// read content of first file and write to merge file


string line;
while (getline(file1, line)) {
mergeFile << line << "\n";
}

// read content of second file and write to merge file


while (getline(file2, line)) {
mergeFile << line << "\n";
}

// close all the files


file1.close();
file2.close();
mergeFile.close();

cout << "Merged file created successfully!";


return 0;
}

github.com/aw-junaid 115
154: Program to delete a file.

#include <stdio.h>
#include <stdlib.h>

int main() {
char filename[100];

printf("Enter the filename to delete: ");


scanf("%s", filename);

if (remove(filename) == 0) {
printf("%s file deleted successfully.\n", filename);
} else {
printf("Unable to delete the file.\n");
}

return 0;
}

155: program to write all the members of an array of structure to a file


using fwrite(). Read the array from the file and display on the screen.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct Person {
string name;
int age;
float height;
};

int main() {
// create an array of structures
Person people[3] = {{"John", 25, 1.75},
{"Mary", 30, 1.68},
{"Bob", 20, 1.80}};

// write the array of structures to a file

github.com/aw-junaid 116
ofstream outfile("people.dat", ios::binary);
if (!outfile) {
cerr << "Error: Failed to open file for writing." << endl;
return 1;
}
outfile.write((char*)&people, sizeof(people));
outfile.close();

// read the array of structures from the file


Person readPeople[3];
ifstream infile("people.dat", ios::binary);
if (!infile) {
cerr << "Error: Failed to open file for reading." << endl;
return 1;
}
infile.read((char*)&readPeople, sizeof(readPeople));
infile.close();

// display the array of structures


for (int i = 0; i < 3; i++) {
cout << "Name: " << readPeople[i].name << endl;
cout << "Age: " << readPeople[i].age << endl;
cout << "Height: " << readPeople[i].height << endl;
cout << endl;
}

return 0;
}

156: Program to write on data file and read from data file.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
// Open a file for writing
ofstream outFile("data.txt");

// Write some data to the file


outFile << "Hello, world!\n";

github.com/aw-junaid 117
outFile << "This is some data.\n";
outFile << "12345\n";

// Close the file


outFile.close();

// Open the file for reading


ifstream inFile("data.txt");

// Read the data from the file


string line;
while (getline(inFile, line)) {
cout << line << endl;
}

// Close the file


inFile.close();

return 0;
}

github.com/aw-junaid 118
157: Program to concatenate many files and store them in a file.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main() {
vector<string> filenames = {"file1.txt", "file2.txt", "file3.txt"}; // input filenames
string output_filename = "output.txt"; // output filename

ofstream outfile(output_filename, ios::out | ios::binary); // create output file

for (const string& filename : filenames) {


ifstream infile(filename, ios::in | ios::binary); // open input file
if (infile) {
// read input file and write to output file
infile.seekg(0, ios::end); // seek to end of file
size_t size = infile.tellg(); // get size of file
infile.seekg(0, ios::beg); // seek back to beginning of file
char* buffer = new char[size]; // allocate buffer
infile.read(buffer, size); // read file into buffer
outfile.write(buffer, size); // write buffer to output file
delete[] buffer; // free buffer memory
infile.close(); // close input file
}
else {
cerr << "Error: could not open input file '" << filename << "'\n";
}
}

outfile.close(); // close output file


cout << "Concatenation complete.\n";

return 0;
}

github.com/aw-junaid 119
158: Program to replace specified line in a text file.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
string filename, line, newLine;
int lineNumber;

// Get the filename from user


cout << "Enter filename: ";
cin >> filename;

// Open the file for reading


ifstream inFile(filename);

// Check if the file opened successfully


if (!inFile) {
cerr << "Error: Cannot open file '" << filename << "'" << endl;
return 1;
}

// Read the number of the line to replace


cout << "Enter line number to replace: ";
cin >> lineNumber;

// Read the new line to insert


cout << "Enter new line: ";
cin.ignore(); // Ignore any newline character left in input buffer
getline(cin, newLine);

// Open a temporary file for writing


ofstream outFile("temp.txt");

// Check if the file opened successfully


if (!outFile) {
cerr << "Error: Cannot open file 'temp.txt'" << endl;
return 1;
}

github.com/aw-junaid 120
// Loop through the input file
int currentLine = 1;
while (getline(inFile, line)) {
// Write the new line if the current line matches the specified line number
if (currentLine == lineNumber) {
outFile << newLine << endl;
} else {
// Write the original line to the temporary file
outFile << line << endl;
}
currentLine++;
}

// Close the input and output files


inFile.close();
outFile.close();

// Delete the original file and rename the temporary file


remove(filename.c_str());
rename("temp.txt", filename.c_str());

cout << "Line " << lineNumber << " has been replaced with '" << newLine << "' in
file '" << filename << "'" << endl;

return 0;
}

github.com/aw-junaid 121
159: Program to delete specific line from a text file.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream inFile("input.txt"); // input file
ofstream outFile("output.txt"); // output file
string line;
int lineNumber, currentLine = 0;

// Get the line number to delete


cout << "Enter the line number to delete: ";
cin >> lineNumber;

// Check if the file is open


if (inFile.is_open() && outFile.is_open()) {
// Read the input file line by line
while (getline(inFile, line)) {
currentLine++; // Increment the current line number
// Write to the output file only if the line number is not equal to the line to be
deleted
if (currentLine != lineNumber) {
outFile << line << endl;
}
}

// Close the files


inFile.close();
outFile.close();

// Remove the input file and rename the output file to input file name
remove("input.txt");
rename("output.txt", "input.txt");

cout << "Line " << lineNumber << " has been deleted." << endl;
}
else {

github.com/aw-junaid 122
cout << "Error opening file(s)!" << endl;
}

return 0;
}

160: Program to find GCD of numbers using recursion.

#include <iostream>
using namespace std;

// Function to find GCD of two numbers using recursion


int gcd(int num1, int num2)
{
if (num2 == 0) {
return num1;
}
else {
return gcd(num2, num1 % num2);
}
}

int main()
{
int num1, num2;

cout << "Enter first number: ";


cin >> num1;

cout << "Enter second number: ";


cin >> num2;

int result = gcd(num1, num2);

cout << "GCD of " << num1 << " and " << num2 << " is " << result << endl;

return 0;
}

161: Program to display atm transaction using class.

#include <iostream>
using namespace std;

github.com/aw-junaid 123
class ATM {
private:
int balance;

public:
ATM(int b) {
balance = b;
}

void displayBalance() {
cout << "Current Balance: " << balance << endl;
}

void withdraw(int amount) {


if (amount > balance) {
cout << "Insufficient balance." << endl;
} else {
balance -= amount;
cout << "Withdrawn: " << amount << endl;
displayBalance();
}
}

void deposit(int amount) {


balance += amount;
cout << "Deposited: " << amount << endl;
displayBalance();
}
};

int main() {
ATM account(5000);
int choice, amount;

do {
cout << "1. Display Balance" << endl;
cout << "2. Withdraw" << endl;
cout << "3. Deposit" << endl;
cout << "4. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;

github.com/aw-junaid 124
switch(choice) {
case 1:
account.displayBalance();
break;
case 2:
cout << "Enter amount to withdraw: ";
cin >> amount;
account.withdraw(amount);
break;
case 3:
cout << "Enter amount to deposit: ";
cin >> amount;
account.deposit(amount);
break;
case 4:
cout << "Thank you for using our ATM!" << endl;
break;
default:
cout << "Invalid choice." << endl;
break;
}
} while(choice != 4);

return 0;
}

162: Program for a matchstick game being played between the


computer and a user.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
int totalMatchsticks = 21;
int userChoice, computerChoice;
cout << "Welcome to the matchstick game!\n";
cout << "There are 21 matchsticks on the table.\n";
cout << "You can pick 1, 2, 3, or 4 matchsticks at a time.\n";
cout << "The player who picks up the last matchstick wins.\n\n";

while (totalMatchsticks > 1) {

github.com/aw-junaid 125
cout << "Total matchsticks left on the table: " << totalMatchsticks << endl;

// User's turn
cout << "Your turn: ";
cin >> userChoice;
while (userChoice < 1 || userChoice > 4 || userChoice > totalMatchsticks) {
cout << "Invalid choice! Choose between 1 and 4 matchsticks and make sure
you don't pick more than the remaining matchsticks.\n";
cout << "Your turn: ";
cin >> userChoice;
}
totalMatchsticks -= userChoice;
if (totalMatchsticks == 1) {
cout << "You win!\n";
break;
}
cout << "You picked " << userChoice << " matchsticks.\n";
cout << "Total matchsticks left on the table: " << totalMatchsticks << endl <<
endl;

// Computer's turn
srand(time(NULL));
computerChoice = rand() % 4 + 1;
while (computerChoice > totalMatchsticks) {
computerChoice = rand() % 4 + 1;
}
totalMatchsticks -= computerChoice;
if (totalMatchsticks == 1) {
cout << "The computer wins!\n";
break;
}
cout << "The computer picked " << computerChoice << " matchsticks.\n";
cout << "Total matchsticks left on the table: " << totalMatchsticks << endl <<
endl;
}

cout << "Thanks for playing!\n";

return 0;
}

github.com/aw-junaid 126
163: Write a function power ( a, b ), to calculate the value of a raised to
b.

#include <iostream>
using namespace std;

double power(double a, int b) {


double result = 1;
if (b >= 0) {
for (int i = 1; i <= b; i++) {
result *= a;
}
}
else {
for (int i = 1; i <= -b; i++) {
result /= a;
}
}
return result;
}

int main() {
double base, exponent;
cout << "Enter base: ";
cin >> base;
cout << "Enter exponent: ";
cin >> exponent;
double result = power(base, exponent);
cout << base << " raised to " << exponent << " is " << result << endl;
return 0;
}

164: Write a general-purpose function to convert any given year into its
roman equivalent.

#include <iostream>
using namespace std;

string convertToRoman(int year) {


int decimals[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
string symbols[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
};
string romanNumeral = "";

github.com/aw-junaid 127
for (int i = 0; i < 13; i++) {
while (year >= decimals[i]) {
romanNumeral += symbols[i];
year -= decimals[i];
}
}

return romanNumeral;
}

int main() {
int year;
cout << "Enter a year: ";
cin >> year;
cout << "The Roman numeral equivalent of " << year << " is " <<
convertToRoman(year) << endl;
return 0;
}

165: Program that compares two given dates using structure.

#include <stdio.h>

struct date {
int day;
int month;
int year;
};

int compareDates(struct date date1, struct date date2);

int main() {
struct date date1, date2;
printf("Enter first date (dd/mm/yyyy): ");
scanf("%d/%d/%d", &date1.day, &date1.month, &date1.year);
printf("Enter second date (dd/mm/yyyy): ");
scanf("%d/%d/%d", &date2.day, &date2.month, &date2.year);

int result = compareDates(date1, date2);

if (result == 1) {
printf("First date is later than the second date.\n");

github.com/aw-junaid 128
} else {
printf("Both dates are the same.\n");
}

return 0;
}

int compareDates(struct date date1, struct date date2) {


if (date1.year > date2.year) {
return 1;
} else if (date1.year < date2.year) {
return -1;
} else {
if (date1.month > date2.month) {
return 1;
} else if (date1.month < date2.month) {
return -1;
} else {
if (date1.day > date2.day) {
return 1;
} else if (date1.day < date2.day) {
return -1;
} else {
return 0;
}
}
}
}

166: Program two functions xgets( ) and xputs( ) which work similar to
the standard library functions gets( ) and puts( ).

#include <iostream>
#include <cstring>

// xgets(): function to read a line of text from the console


// The function accepts a char pointer and the maximum number of characters to be
read
void xgets(char *str, int size) {
int i = 0;
char ch;
while (i < size - 1) {
ch = getchar();

github.com/aw-junaid 129
if (ch == '\n')
break;
str[i] = ch;
i++;
}
str[i] = '\0';
}

// xputs(): function to display the string on the console


void xputs(char *str) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
putchar(str[i]);
}
}

int main() {
char str[50];
std::cout << "Enter a string: ";
xgets(str, 50);
std::cout << "The string entered is: ";
xputs(str);
return 0;
}

167: Program to add the contents of one file at the end of another.

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fptr1, *fptr2;
char c;

// Open the first file for reading


fptr1 = fopen("file1.txt", "r");

if (fptr1 == NULL)
{
printf("Cannot open file1.txt \n");
exit(0);
}

github.com/aw-junaid 130
// Open the second file for appending
fptr2 = fopen("file2.txt", "a");

if (fptr2 == NULL)
{
printf("Cannot open file2.txt \n");
exit(0);
}

// Copy the contents of file1 to file2


while ((c = fgetc(fptr1)) != EOF)
{
fputc(c, fptr2);
}

// Close both files


fclose(fptr1);
fclose(fptr2);

printf("Contents added successfully.\n");

return 0;
}

168: Program to encrypt/decrypt a file.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Function to encrypt or decrypt a file using a key


void encrypt_decrypt_file(string file_name, string key, bool encrypt) {
ifstream in_file(file_name, ios::binary); // Open input file
ofstream out_file(file_name + (encrypt ? ".enc" : ".dec"), ios::binary); // Open
output file

// Calculate length of key and read input file


int key_length = key.length();
char c;
int i = 0;

github.com/aw-junaid 131
// Loop through input file, XOR each character with the key, and write to output file
while (in_file.get(c)) {
char k = key[i % key_length];
if (encrypt) {
c = c ^ k;
} else {
c = c ^ k;
}
out_file.put(c);
i++;
}

// Close files
in_file.close();
out_file.close();
}

int main() {
string file_name, key;
bool encrypt;

// Get file name and key from user


cout << "Enter file name: ";
cin >> file_name;
cout << "Enter key: ";
cin >> key;

// Ask user whether to encrypt or decrypt file


char choice;
do {
cout << "Do you want to encrypt (e) or decrypt (d) the file? ";
cin >> choice;
} while (choice != 'e' && choice != 'd');

encrypt = (choice == 'e');

// Call function to encrypt or decrypt file


encrypt_decrypt_file(file_name, key, encrypt);

cout << "Done!\n";

return 0;
}

github.com/aw-junaid 132
169: Program that can be used at command prompt as a calculating
utility.

#include <iostream>
#include <string>

using namespace std;

int main() {
string expression;
cout << "Enter an arithmetic expression: ";
getline(cin, expression);

// Evaluate the expression


double result = 0.0;
try {
result = stod(expression);
} catch (const invalid_argument& e) {
cerr << "Invalid input: " << expression << endl;
return 1;
}

// Print the result


cout << "Result: " << result << endl;
return 0;
}

170: Program that prints the value of hInstance in a message box.

#include <windows.h>
#include <cstdio>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR


lpCmdLine, int nCmdShow) {
char buffer[256];
sprintf(buffer, "hInstance: 0x%p", hInstance);
MessageBox(NULL, buffer, "Instance Handle", MB_OK);
return 0;
}

github.com/aw-junaid 133
171: Program that displays three buttons ‘Yes’, ‘No’ ‘Cancel’ in the
message box.

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR


lpCmdLine, int nCmdShow) {
int result = MessageBox(NULL, "Do you want to continue?", "Message Box",
MB_YESNOCANCEL | MB_ICONQUESTION);
switch (result) {
case IDYES:
MessageBox(NULL, "You clicked 'Yes'", "Message Box", MB_OK |
MB_ICONINFORMATION);
break;
case IDNO:
MessageBox(NULL, "You clicked 'No'", "Message Box", MB_OK |
MB_ICONINFORMATION);
break;
case IDCANCEL:
MessageBox(NULL, "You clicked 'Cancel'", "Message Box", MB_OK |
MB_ICONINFORMATION);
break;
}
return 0;
}

172: Program that displays command line arguments including file


name in a message box.

#include <iostream>
#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR


lpCmdLine, int nCmdShow)
{
MessageBox(NULL, lpCmdLine, "Command Line Arguments", MB_OK);
return 0;
}

github.com/aw-junaid 134
173: Write a program to gradient fill the entire client area with shades
of blue color.

#include <iostream>
#include <windows.h>

int main()
{
// Get handle to the console window
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);

// Set console background color to dark blue


SetConsoleTextAttribute(consoleHandle, BACKGROUND_BLUE);

// Loop to fill entire console window with shades of blue


for (int i = 1; i <= 16; i++)
{
// Set console background color to the next shade of blue
SetConsoleTextAttribute(consoleHandle, BACKGROUND_BLUE | i);

// Fill entire line with spaces to create a solid color


for (int j = 0; j < 80; j++)
{
std::cout << " ";
}
std::cout << std::endl;
}

return 0;
}

github.com/aw-junaid 135
174: Write a program that displays only the upper half of a bitmap of
size 40 x 40.

#include <iostream>
#include <graphics.h>
using namespace std;

int main()
{
initwindow(640, 480, "Upper Half of Bitmap");

// Load the bitmap


readimagefile("bitmap.bmp", 0, 0, 40, 40);

// Display only the upper half of the bitmap


setviewport(0, 0, 40, 20, 1);
clearviewport();
readimagefile("bitmap.bmp", 0, 0, 40, 20);

getch();
closegraph();
return 0;
}

github.com/aw-junaid 136
175: Write a program that displays different text in different colors and
fonts at different places after every 10 seconds.

#include <windows.h>
#include <time.h>

#define TIMER_ID 1
#define TIMER_INTERVAL 10000 // 10 seconds
#define MAX_TEXT_LENGTH 50
#define MAX_FONT_SIZE 36

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam,


LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,


LPSTR lpCmdLine, int nCmdShow)
{
// Register window class
WNDCLASS wc = {0};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW);
wc.lpszClassName = TEXT("RandomTextClass");
RegisterClass(&wc);

// Create window
HWND hwnd = CreateWindowEx(0, TEXT("RandomTextClass"), TEXT("Random
Text"),
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
hInstance, NULL);

// Show window
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);

// Set timer to call update function every 10 seconds


SetTimer(hwnd, TIMER_ID, TIMER_INTERVAL, NULL);

// Message loop
MSG msg;

github.com/aw-junaid 137
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

// Clean up
KillTimer(hwnd, TIMER_ID);
return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam,


LPARAM lParam)
{
switch (msg)
{
case WM_TIMER:
// Generate random text, color, font, and position
TCHAR text[MAX_TEXT_LENGTH];
int r = rand() % 256;
int g = rand() % 256;
int b = rand() % 256;
COLORREF color = RGB(r, g, b);
int font_size = rand() % MAX_FONT_SIZE + 12; // Minimum font size of 12
HFONT font = CreateFont(font_size, 0, 0, 0, FW_NORMAL, FALSE, FALSE,
FALSE,
ANSI_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
NULL);
int x = rand() % (GetSystemMetrics(SM_CXSCREEN) - 100); // Leave some
margin on the sides
int y = rand() % (GetSystemMetrics(SM_CYSCREEN) / 2); // Only show upper
half of the screen
wsprintf(text, TEXT("Random Text %d"), rand());

// Draw text on screen


HDC hdc = GetDC(hwnd);
HBRUSH brush = CreateSolidBrush(color);
SelectObject(hdc, brush);
SelectObject(hdc, font);
TextOut(hdc, x, y, text, lstrlen(text));
DeleteObject(brush);

github.com/aw-junaid 138
DeleteObject(font);
ReleaseDC(hwnd, hdc);
break;

case WM_DESTROY:
PostQuitMessage(0);
break;

default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}

return 0;
}

176: Write a program to read the contents of Boot Sector of a 32-bit


FAT file system and print them on the screen.

#include <iostream>
#include <fstream>

int main() {
std::ifstream file("filename.txt"); // replace with the name of your file
if (file.is_open()) {
std::string line;
while (getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
} else {
std::cout << "Unable to open file." << std::endl;
}
return 0;
}

github.com/aw-junaid 139
177: Write a program that blocks the SIGTERM signal during execution
of the SIGINT signal.

#include <iostream>
#include <signal.h>
#include <unistd.h>

void sigint_handler(int signal) {


std::cout << "Received SIGINT signal." << std::endl;
std::cout << "Blocking SIGTERM signal." << std::endl;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
sigprocmask(SIG_BLOCK, &mask, NULL);
sleep(5);
std::cout << "Unblocking SIGTERM signal." << std::endl;
sigprocmask(SIG_UNBLOCK, &mask, NULL);
}

int main() {
signal(SIGINT, sigint_handler);
while (1) {
std::cout << "Waiting for signals..." << std::endl;
sleep(1);
}
return 0;
}

github.com/aw-junaid 140
178: Write a program to verify that SIGSTOP and SIGKILL signals are
un-catchable signals.

#include <iostream>
#include <signal.h>
#include <unistd.h>

void signal_handler(int signum) {


std::cout << "Caught signal: " << signum << std::endl;
}

int main() {
// Catch SIGSTOP and SIGKILL signals
if (signal(SIGSTOP, signal_handler) == SIG_ERR) {
std::cout << "Unable to catch SIGSTOP signal" << std::endl;
}
if (signal(SIGKILL, signal_handler) == SIG_ERR) {
std::cout << "Unable to catch SIGKILL signal" << std::endl;
}

// Wait for signals


while (true) {
std::cout << "Waiting for signals..." << std::endl;
sleep(1);
}

return 0;
}

github.com/aw-junaid 141
179: Program to create GradeBook object and call its displayMessage
function.

#include <iostream>
#include <string>

using namespace std;

class GradeBook {
public:
void displayMessage() {
cout << "Welcome to the Grade Book program!" << endl;
}
};

int main() {
GradeBook myGradeBook;
myGradeBook.displayMessage();

return 0;
}

180: BMI calculator application

#include <iostream>
using namespace std;

int main() {
float weight, height, bmi;

// read the user's weight in pounds and height in inches


cout << "Enter your weight in pounds: ";
cin >> weight;
cout << "Enter your height in inches: ";
cin >> height;

// calculate the BMI


bmi = (weight * 703) / (height * height);

// display the result


cout << "Your Body Mass Index (BMI) is: " << bmi << endl;

return 0;
}
github.com/aw-junaid 142
181: Write a program that displays the checkerboard pattern using *

#include <iostream>
using namespace std;

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

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


for (int j = 1; j <= size; ++j) {
if ((i+j) % 2 == 0) {
cout << "* ";
} else {
cout << " ";
}
}
cout << endl;
}
return 0;
}

182: Program for counting letter grades with switch.

#include <iostream>
using namespace std;

int main() {
char grade;
int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0;

cout << "Enter the letter grades." << endl


<< "Enter the EOF character to end input." << endl;

while ((grade = cin.get()) != EOF) {


switch (grade) {
case 'A':
case 'a':
++aCount;
break;
case 'B':
case 'b':

github.com/aw-junaid 143
++bCount;
break;
case 'C':
case 'c':
++cCount;
break;
case 'D':
case 'd':
++dCount;
break;
case 'F':
case 'f':
++fCount;
break;
case '\n':
case '\t':
case ' ':
break;
default:
cout << "Incorrect letter grade entered. Enter a new grade." << endl;
break;
}
}

cout << endl


<< "Totals for each letter grade are:" << endl
<< "A: " << aCount << endl
<< "B: " << bCount << endl
<< "C: " << cCount << endl
<< "D: " << dCount << endl
<< "F: " << fCount << endl;

return 0;
}

github.com/aw-junaid 144
183: Program using the break statement in a for statement.

#include <iostream>
using namespace std;

int main() {
int target = 5;

// Loop from 1 to 10
for (int i = 1; i <= 10; i++) {
cout << i << " ";

// If we have reached our target number, break out of the loop


if (i == target) {
cout << "(Target reached)" << endl;
break;
}
}

return 0;
}

github.com/aw-junaid 145
184: Program using the continue statement in a for statement.

#include <iostream>
using namespace std;

int main() {
int i;
for(i=1; i<=10; i++) {
if(i==5) {
continue; // skip rest of the loop body and continue with next iteration
}
cout << i << " "; // print the current value of i
}
return 0;
}

github.com/aw-junaid 146
185: Program to Calculate Weekly Pay.

#include <iostream>
using namespace std;

int main() {
double hourly_rate, hours_worked, weekly_pay;

// Get input from user


cout << "Enter hourly rate: $";
cin >> hourly_rate;
cout << "Enter hours worked: ";
cin >> hours_worked;

// Calculate weekly pay


if (hours_worked <= 40) {
weekly_pay = hourly_rate * hours_worked;
} else {
weekly_pay = hourly_rate * 40 + (hourly_rate * 1.5 * (hours_worked - 40));
}

// Display weekly pay


cout << "Weekly pay: $" << weekly_pay << endl;

return 0;
}

github.com/aw-junaid 147
186: Program using the De Morgan’s Laws.

#include <iostream>
using namespace std;

int main() {
int A = 1, B = 0;

// Original expressions
if (!(A && B)) {
cout << "!(A && B) is true." << endl;
}

if (!(A || B)) {
cout << "!(A || B) is true." << endl;
}

// Equivalent negated expressions


if ((!A || !B)) {
cout << "(!A || !B) is true." << endl;
}

if ((!A && !B)) {


cout << "(!A && !B) is true." << endl;
}

return 0;
}

github.com/aw-junaid 148
187: Write a program for Roman-Numeral Equivalent of Decimal Values.

#include <iostream>
using namespace std;

int main() {
int decimalValue;
string romanValue = "";

cout << "Enter a decimal value between 1 and 3999: ";


cin >> decimalValue;

if(decimalValue < 1 || decimalValue > 3999) {


cout << "Invalid input!";
return 0;
}

while(decimalValue >= 1000) {


romanValue += "M";
decimalValue -= 1000;
}

if(decimalValue >= 900) {


romanValue += "CM";
decimalValue -= 900;
}

while(decimalValue >= 500) {


romanValue += "D";
decimalValue -= 500;
}

if(decimalValue >= 400) {


romanValue += "CD";
decimalValue -= 400;
}

while(decimalValue >= 100) {


romanValue += "C";
decimalValue -= 100;
}

github.com/aw-junaid 149
if(decimalValue >= 90) {
romanValue += "XC";
decimalValue -= 90;
}

while(decimalValue >= 50) {


romanValue += "L";
decimalValue -= 50;
}

if(decimalValue >= 40) {


romanValue += "XL";
decimalValue -= 40;
}

while(decimalValue >= 10) {


romanValue += "X";
decimalValue -= 10;
}

if(decimalValue >= 9) {
romanValue += "IX";
decimalValue -= 9;
}

while(decimalValue >= 5) {
romanValue += "V";
decimalValue -= 5;
}

if(decimalValue >= 4) {
romanValue += "IV";
decimalValue -= 4;
}

while(decimalValue >= 1) {
romanValue += "I";
decimalValue -= 1;
}

cout << "Roman numeral equivalent: " << romanValue;

return 0;
}

github.com/aw-junaid 150
188: Program to demonstrating the function call stack and stack
frames using a function square.

#include <iostream>

int square(int n) {
int result = n * n;
std::cout << "square(" << n << ") -> " << result << std::endl;
return result;
}

int main() {
int x = 3;
int y = square(x + 2) + square(x + 3);
std::cout << "y = " << y << std::endl;
return 0;
}

github.com/aw-junaid 151
189: Write a program to randomizing the die-rolling program.

#include <iostream>
#include <cstdlib> // Required for rand() and srand()
#include <ctime> // Required for time()

using namespace std;

int main() {
int roll; // The variable to store the result of the die roll

// Seed the random number generator with the current time


srand(time(NULL));

// Roll the die and print the result


roll = rand() % 6 + 1; // Generate a random number between 1 and 6
cout << "You rolled a " << roll << endl;

return 0;
}

github.com/aw-junaid 152
190: Program a recursive factorial function.

#include <iostream>

// Recursive function to compute factorial of n


int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: compute factorial of (n-1) and multiply by n
else {
return n * factorial(n - 1);
}
}

int main() {
int n;
std::cout << "Enter a positive integer: ";
std::cin >> n;
std::cout << "Factorial of " << n << " is " << factorial(n) << std::endl;
return 0;
}

github.com/aw-junaid 153
191: Write a program Hypotenuse Calculations using function.

#include <iostream>
#include <cmath>

using namespace std;

// Function to calculate hypotenuse of a right triangle


double hypotenuse(double side1, double side2) {
return sqrt(side1 * side1 + side2 * side2);
}

int main() {
double side1, side2;
cout << "Enter the length of side 1: ";
cin >> side1;
cout << "Enter the length of side 2: ";
cin >> side2;
cout << "The hypotenuse is " << hypotenuse(side1, side2) << endl;
return 0;
}

github.com/aw-junaid 154
192: Program to convert Time in Seconds.

#include <iostream>
using namespace std;

int main()
{
int seconds, minutes, hours, total_seconds;

cout << "Enter time in seconds: ";


cin >> total_seconds;

hours = total_seconds / 3600;


minutes = (total_seconds % 3600) / 60;
seconds = (total_seconds % 3600) % 60;

cout << "Time is " << hours << " hours, " << minutes << " minutes, and " <<
seconds << " seconds." << endl;

return 0;
}

github.com/aw-junaid 155
193: Write a program for Currency Conversion.

#include <iostream>
using namespace std;

int main()
{
double amount, result;
char choice;

cout << "Enter the amount in US Dollars: ";


cin >> amount;

cout << "Choose currency to convert to (E for Euro, P for Pound, Y for Yen): ";
cin >> choice;

switch (choice)
{
case 'E':
case 'e':
result = amount * 0.82; // 1 USD = 0.82 Euro
cout << "Equivalent amount in Euro: " << result << endl;
break;
case 'P':
case 'p':
result = amount * 0.72; // 1 USD = 0.72 Pound
cout << "Equivalent amount in Pound: " << result << endl;
break;
case 'Y':
case 'y':
result = amount * 109.44; // 1 USD = 109.44 Yen
cout << "Equivalent amount in Yen: " << result << endl;
break;
default:
cout << "Invalid choice!" << endl;
break;
}

return 0;
}

github.com/aw-junaid 156
194: Write a program that simulates coin tossing.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
srand(time(0)); // set the seed for random number generation

int numFlips;
cout << "Enter the number of times you want to flip the coin: ";
cin >> numFlips;

int headsCount = 0;
int tailsCount = 0;

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


{
int coin = rand() % 2; // generate a random number either 0 or 1

if (coin == 0)
headsCount++;
else
tailsCount++;
}

cout << "Heads count: " << headsCount << endl;


cout << "Tails count: " << tailsCount << endl;

return 0;
}

github.com/aw-junaid 157
195: Write a recursive function isPrime that determines whether the
given input is a prime number using function.

#include <iostream>
using namespace std;

bool isPrime(int n, int i = 2) {


// base cases
if (n <= 2)
return (n == 2) ? true : false;
if (n % i == 0)
return false;
if (i * i > n)
return true;

// check for next divisor


return isPrime(n, i + 1);
}

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
if (isPrime(num))
cout << num << " is a prime number.";
else
cout << num << " is not a prime number.";
return 0;
}

github.com/aw-junaid 158
196: Write a program to displaying a histogram using array.

#include <iostream>
using namespace std;

int main() {
const int SIZE = 10; // Size of the array
int arr[SIZE] = {3, 6, 8, 2, 9, 1, 4, 5, 7, 0}; // Array of integers
int counts[10] = {}; // Array to hold the counts of each value

// Count the occurrences of each value in the array


for (int i = 0; i < SIZE; i++) {
counts[arr[i]]++;
}

// Display the histogram


for (int i = 0; i < 10; i++) {
cout << i << ": ";
for (int j = 0; j < counts[i]; j++) {
cout << "*";
}
cout << endl;
}

return 0;
}

github.com/aw-junaid 159
197: Write a program to treating character arrays as strings.

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
char name[50];
cout << "Enter your name: ";
cin >> name;

cout << "Hello, " << name << "!" << endl;

int len = strlen(name);


cout << "Length of name: " << len << endl;

char copy[50];
strcpy(copy, name);
cout << "Copy of name: " << copy << endl;

char greeting[50] = "Hello, ";


strcat(greeting, name);
cout << greeting << "!" << endl;

return 0;
}

github.com/aw-junaid 160
198: Write a Program for array name is the same as the address of the
array’s first element.

#include <iostream>

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

std::cout << "Value of arr: " << arr << std::endl;


std::cout << "Value of &arr[0]: " << &arr[0] << std::endl;

return 0;
}

github.com/aw-junaid 161
199: Write a Program for passing arrays and individual array elements
to functions.

#include <iostream>
using namespace std;

// function to accept an integer array and its size and display the array
void displayArray(int arr[], int size) {
cout << "The array elements are: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

// function to accept an integer array and its size and return the sum of its elements
int sumArray(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}

// function to accept an integer element and display it


void displayElement(int element) {
cout << "The element is: " << element << endl;
}

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

displayArray(arr, size);
cout << "The sum of array elements is: " << sumArray(arr, size) << endl;
displayElement(element);

return 0;
}

github.com/aw-junaid 162
200: Write a Program for Survey data analysis with arrays:computing
the mean, median and mode of the data.

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

const int MAX_SIZE = 100;

// Function to compute the mean of the survey data


double computeMean(int data[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += data[i];
}
return static_cast<double>(sum) / size;
}

// Function to compute the median of the survey data


double computeMedian(int data[], int size) {
sort(data, data + size);
if (size % 2 == 0) {
return static_cast<double>(data[size / 2 - 1] + data[size / 2]) / 2;
} else {
return static_cast<double>(data[size / 2]);
}
}

// Function to compute the mode of the survey data


int computeMode(int data[], int size) {
int freq[MAX_SIZE] = {0};
for (int i = 0; i < size; i++) {
freq[data[i]]++;
}
int max_freq = 0;
int mode = 0;
for (int i = 0; i < MAX_SIZE; i++) {
if (freq[i] > max_freq) {
max_freq = freq[i];
mode = i;
}

github.com/aw-junaid 163
}
return mode;
}

int main() {
int data[MAX_SIZE];
int size;
cout << "Enter the number of survey data: ";
cin >> size;
cout << "Enter the survey data: ";
for (int i = 0; i < size; i++) {
cin >> data[i];
}
double mean = computeMean(data, size);
double median = computeMedian(data, size);
int mode = computeMode(data, size);
cout << "Mean: " << mean << endl;
cout << "Median: " << median << endl;
cout << "Mode: " << mode << endl;
return 0;
}

github.com/aw-junaid 164
201: Program to Print a string one character at a time using a non-
constant pointer to constant data.

#include <iostream>
using namespace std;

int main() {
const char* str = "Hello, world!";
const char* ptr = str;

while (*ptr != '\0') {


cout << *ptr;
ptr++;
}

return 0;
}

github.com/aw-junaid 165
202: Write a Program using operator sizeof to determine standard data
type sizes.

#include <iostream>

int main() {
std::cout << "The size of an int is " << sizeof(int) << " bytes" << std::endl;
std::cout << "The size of a double is " << sizeof(double) << " bytes" << std::endl;
std::cout << "The size of a char is " << sizeof(char) << " byte" << std::endl;
std::cout << "The size of a bool is " << sizeof(bool) << " byte" << std::endl;
return 0;
}

github.com/aw-junaid 166
203: Write a program for card shuffling and dealing.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

const int DECK_SIZE = 52;


const int HAND_SIZE = 5;

void shuffle(int * const deck, const int size);


void deal(int * const deck, const int size, int * const hand, const int handSize);
void printCards(int * const cards, const int size);

int main()
{
srand(time(NULL)); // seed the random number generator with current time

int deck[DECK_SIZE];
for (int i = 0; i < DECK_SIZE; i++) {
deck[i] = i;
}

int hand[HAND_SIZE];

shuffle(deck, DECK_SIZE);
deal(deck, DECK_SIZE, hand, HAND_SIZE);

cout << "Your hand is: ";


printCards(hand, HAND_SIZE);

return 0;
}

void shuffle(int * const deck, const int size)


{
for (int i = 0; i < size; i++) {
int j = rand() % size;
int temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}}

github.com/aw-junaid 167
void deal(int * const deck, const int size, int * const hand, const int handSize)
{
for (int i = 0; i < handSize; i++) {
hand[i] = deck[i];
}
}

void printCards(int * const cards, const int size)


{
for (int i = 0; i < size; i++) {
int suit = cards[i] / 13;
int rank = cards[i] % 13;
switch (rank) {
case 0: cout << "Ace"; break;
case 10: cout << "Jack"; break;
case 11: cout << "Queen"; break;
case 12: cout << "King"; break;
default: cout << rank + 1; break;
}
cout << " of ";
switch (suit) {
case 0: cout << "Hearts"; break;
case 1: cout << "Diamonds"; break;
case 2: cout << "Clubs"; break;
case 3: cout << "Spades"; break;
}
if (i < size - 1) {
cout << ", ";
}
}
cout << endl;
}

github.com/aw-junaid 168
204: Write a Program for counting the occurrences of a substring.

#include <iostream>
#include <string>

int countSubstr(std::string str, std::string sub) {


int count = 0;
size_t pos = str.find(sub, 0);
while (pos != std::string::npos) {
count++;
pos = str.find(sub, pos + sub.length());
}
return count;
}

int main() {
std::string str = "the quick brown fox jumps over the lazy dog";
std::string sub = "the";
int count = countSubstr(str, sub);
std::cout << "Number of occurrences of \"" << sub << "\": " << count << std::endl;
return 0;
}

github.com/aw-junaid 169
205: Write a program that reads a series of strings and prints only
those beginning with the letters "Th"

#include <iostream>
#include <string>

int main() {
std::cout << "Enter a series of strings (press Ctrl+Z to end):" << std::endl;
std::string s;
while (std::cin >> s) {
if (s.size() >= 2 && s[0] == 'T' && s[1] == 'h') {
std::cout << s << std::endl;
}
}
return 0;
}

github.com/aw-junaid 170
206: Write a program that reads a series of strings and prints only
those that end with the letters "tion".

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

int main() {
string str;

// read strings from user


cout << "Enter strings (type 'quit' to stop):" << endl;
getline(cin, str);

// check each string for "tion" at the end


while (str != "quit") {
int length = str.length();
if (length >= 4 && str[length-1] == 'n' && str[length-2] == 'o' && str[length-3] == 'i'
&& str[length-4] == 't') {
cout << str << endl;
}
getline(cin, str);
}

return 0;
}

github.com/aw-junaid 171
207: Write your own versions of the functions for converting strings to
numbers.

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int stringToInt(string str) {


int num = 0;
int sign = 1;
int i = 0;

if (str[0] == '-') {
sign = -1;
i++;
}

for (; i < str.size(); i++) {


num += (str[i] - '0') * pow(10, str.size() - i - 1);
}

return sign * num;


}

int main() {
string str = "-1234";
int num = stringToInt(str);
cout << "String: " << str << endl;
cout << "Integer: " << num << endl;
return 0;
}

github.com/aw-junaid 172
208: Function to convert string to double:

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

double stringToDouble(string str) {


double num = 0;
int sign = 1;
int i = 0;
bool decimal = false;
double factor = 1.0;

if (str[0] == '-') {
sign = -1;
i++;
}

for (; i < str.size(); i++) {


if (str[i] == '.') {
decimal = true;
continue;
}
num *= 10.0;
num += (str[i] - '0');
if (decimal) {
factor /= 10.0;
}
}

return sign * num * factor;


}

int main() {
string str = "1234.567";
double num = stringToDouble(str);
cout << "String: " << str << endl;
cout << "Double: " << num << endl;
return 0;
}

github.com/aw-junaid 173
209: Write a program that will assist the user with metric conversions.

#include <iostream>
using namespace std;

// Function to convert meters to feet


double metersToFeet(double meters) {
return meters * 3.28084;
}

// Function to convert feet to meters


double feetToMeters(double feet) {
return feet / 3.28084;
}

// Function to convert kilograms to pounds


double kilogramsToPounds(double kilograms) {
return kilograms * 2.20462;
}

// Function to convert pounds to kilograms


double poundsToKilograms(double pounds) {
return pounds / 2.20462;
}

int main() {
int choice;
double value;

cout << "Metric Conversion Assistant" << endl;


cout << "--------------------------" << endl;

do {
cout << endl << "Select an option:" << endl;
cout << "1. Meters to Feet" << endl;
cout << "2. Feet to Meters" << endl;
cout << "3. Kilograms to Pounds" << endl;
cout << "4. Pounds to Kilograms" << endl;
cout << "5. Exit" << endl;
cout << "Choice: ";
cin >> choice;

github.com/aw-junaid 174
switch (choice) {
case 1:
cout << "Enter meters: ";
cin >> value;
cout << value << " meters is " << metersToFeet(value) << " feet." << endl;
break;
case 2:
cout << "Enter feet: ";
cin >> value;
cout << value << " feet is " << feetToMeters(value) << " meters." << endl;
break;
case 3:
cout << "Enter kilograms: ";
cin >> value;
cout << value << " kilograms is " << kilogramsToPounds(value) << "
pounds." << endl;
break;
case 4:
cout << "Enter pounds: ";
cin >> value;
cout << value << " pounds is " << poundsToKilograms(value) << "
kilograms." << endl;
break;
case 5:
cout << "Exiting program..." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
break;
}
} while (choice != 5);

return 0;
}

github.com/aw-junaid 175
210: Write a program that reverses the order of the bits in an unsigned
int value.

#include <iostream>

unsigned int reverseBits(unsigned int n) {


unsigned int result = 0;
int numBits = sizeof(n) * 8;
for (int i = 0; i < numBits; ++i) {
result <<= 1;
result |= (n & 1);
n >>= 1;
}
return result;
}

int main() {
unsigned int n = 0b110010101;
std::cout << "Original value: " << n << std::endl;
std::cout << "Reversed bits: " << reverseBits(n) << std::endl;
return 0;
}

github.com/aw-junaid 176
211: Program for reading and printing a sequential file.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
ifstream inputFile("input.txt"); // open input file
string line; // to store each line of the file

// check if file is opened successfully


if (!inputFile.is_open()) {
cout << "Failed to open file." << endl;
return 1; // exit program with error code
}

// read and print each line of the file


while (getline(inputFile, line)) {
cout << line << endl;
}

// close input file


inputFile.close();

return 0; // exit program successfully


}

github.com/aw-junaid 177
212: Credit inquiry program.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Function to check if a given credit card number is valid


bool isValidCCNum(string ccNum) {
int sum = 0;
bool alternate = false;
for (int i = ccNum.length() - 1; i >= 0; i--) {
int digit = ccNum[i] - '0';
if (alternate) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
alternate = !alternate;
}
return (sum % 10 == 0);
}

// Function to print a credit report for a given user


void printCreditReport(string username) {
// Open file for reading
ifstream inputFile("credit.txt");
if (!inputFile.is_open()) {
cout << "Error opening file." << endl;
return;
}

// Search for user in file


string line;
bool userFound = false;
while (getline(inputFile, line)) {
if (line == username) {
userFound = true;
break;

github.com/aw-junaid 178
}
}

// Print credit report for user if found


if (userFound) {
cout << "Credit report for " << username << ":" << endl;
getline(inputFile, line); // skip username line
cout << "Credit score: " << line << endl;
getline(inputFile, line); // skip credit score line
cout << "Credit history: " << endl;
while (getline(inputFile, line)) {
cout << line << endl;
}
} else {
cout << "User not found." << endl;
}

inputFile.close();
}

int main() {
string ccNum;
cout << "Enter your credit card number: ";
cin >> ccNum;
if (isValidCCNum(ccNum)) {
cout << "Credit card number is valid." << endl;
string username;
cout << "Enter your username: ";
cin >> username;
printCreditReport(username);
} else {
cout << "Invalid credit card number." << endl;
}
return 0;
}

github.com/aw-junaid 179
213: Program for writing data randomly to a random-access file.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

struct Record {
int id;
char name[20];
double balance;
};

int main() {
// Open the file for writing in binary mode
fstream file("records.dat", ios::out | ios::binary);

// Check if the file is open


if (!file) {
cerr << "Error opening file\n";
exit(1);
}

// Get the number of records to write


int num_records;
cout << "Enter the number of records to write: ";
cin >> num_records;

// Write the records to the file


for (int i = 0; i < num_records; i++) {
Record record;

// Get the record data from the user


cout << "Enter record #" << i+1 << " data:\n";
cout << "ID: ";
cin >> record.id;
cin.ignore(); // Ignore the newline character
cout << "Name: ";
cin.getline(record.name, 20);
cout << "Balance: ";
cin >> record.balance;

github.com/aw-junaid 180
// Calculate the position to write the record to
int position = (record.id - 1) * sizeof(Record);

// Move the file pointer to the correct position


file.seekp(position);

// Write the record to the file


file.write(reinterpret_cast<char*>(&record), sizeof(Record));
}

// Close the file


file.close();

cout << "Records written to file\n";

return 0;
}

github.com/aw-junaid 181
214: Program for inserting and deleting nodes in a list.

#include <iostream>
using namespace std;

// Define the Node structure


struct Node {
int data;
Node* next;
};

// Function to insert a node at the beginning of the list


void insert(Node** head, int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = *head;
*head = newNode;
}

// Function to delete a node from the list


void deleteNode(Node** head, int key) {
Node* temp = *head;
Node* prev = NULL;

// If head node itself holds the key to be deleted


if (temp != NULL && temp->data == key) {
*head = temp->next; // Change head
delete temp; // Free memory
return;
}

// Search for the key to be deleted, keep track of the previous node
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If key was not present in linked list


if (temp == NULL) return;

github.com/aw-junaid 182
// Unlink the node from linked list
prev->next = temp->next;
delete temp; // Free memory
}

// Function to print the list


void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

int main() {
Node* head = NULL;

// Insert some nodes


insert(&head, 10);
insert(&head, 20);
insert(&head, 30);
insert(&head, 40);

cout << "Original List: ";


printList(head);

// Delete some nodes


deleteNode(&head, 20);
cout << "List after deleting 20: ";
printList(head);

deleteNode(&head, 30);
cout << "List after deleting 30: ";
printList(head);

deleteNode(&head, 50);
cout << "List after deleting 50: ";
printList(head);

return 0;
}

github.com/aw-junaid 183
215: Simple stack program.

#include <iostream>
using namespace std;

const int MAX = 10; // Maximum size of the stack

class Stack {
private:
int top; // Index of the top element in the stack
int arr[MAX]; // Array to hold the elements of the stack

public:
Stack() { top = -1; } // Constructor to initialize the stack

bool push(int x) {
// Check if stack is full
if (top == MAX - 1) {
cout << "Stack Overflow!" << endl;
return false;
}
// Increment top and insert element
arr[++top] = x;
return true;
}

bool pop() {
// Check if stack is empty
if (top == -1) {
cout << "Stack Underflow!" << endl;
return false;
}
// Decrement top to remove element
top--;
return true;
}

int peek() {
// Check if stack is empty
if (top == -1) {
cout << "Stack is Empty!" << endl;
return -1;
}

github.com/aw-junaid 184
bool isEmpty() {
// Check if stack is empty
return (top == -1);
}

bool isFull() {
// Check if stack is full
return (top == MAX - 1);
}

void display() {
// Check if stack is empty
if (top == -1) {
cout << "Stack is Empty!" << endl;
return;
}
// Display the elements of the stack
cout << "Stack: ";
for (int i = 0; i <= top; i++)
cout << arr[i] << " ";
cout << endl;
}
};

int main() {
Stack s; // Create an instance of the stack

s.push(5); // Insert elements into the stack


s.push(10);
s.push(15);
s.push(20);

s.display(); // Display the elements of the stack

s.pop(); // Remove an element from the stack


s.pop();

s.display(); // Display the elements of the stack

cout << "Top element: " << s.peek() << endl; // Display the top element

return 0;
}

github.com/aw-junaid 185
216: Program for creating and traversing a binary tree preorder,
inorder, and postorder.

#include <iostream>
using namespace std;

// node struct definition


struct Node {
int data;
Node* left;
Node* right;
};

// function to create a new node


Node* createNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// function to insert a node into the binary tree


Node* insertNode(Node* root, int data) {
if (root == NULL) {
return createNode(data);
} else if (data <= root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}

// function for preorder traversal


void preorderTraversal(Node* root) {
if (root == NULL) {
return;
}
cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}

/
github.com/aw-junaid 186
// function for inorder traversal
void inorderTraversal(Node* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}

// function for postorder traversal


void postorderTraversal(Node* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->data << " ";
}

int main() {
Node* root = NULL;
root = insertNode(root, 10);
insertNode(root, 8);
insertNode(root, 15);
insertNode(root, 6);
insertNode(root, 9);
insertNode(root, 13);
insertNode(root, 18);
cout << "Preorder traversal: ";
preorderTraversal(root);
cout << endl;
cout << "Inorder traversal: ";
inorderTraversal(root);
cout << endl;
cout << "Postorder traversal: ";
postorderTraversal(root);
cout << endl;
return 0;
}

github.com/aw-junaid 187
217: Write a program that concatenates two linked lists of characters.

#include <iostream>
using namespace std;

// Node structure for linked list


struct Node {
char data;
Node* next;
};

// Function to add a new node at the end of the linked list


void addNode(Node*& head, char data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to concatenate two linked lists


Node* concatenateLists(Node* head1, Node* head2) {
Node* result = NULL;
Node* temp = head1;
while (temp != NULL) {
addNode(result, temp->data);
temp = temp->next;
}
temp = head2;
while (temp != NULL) {
addNode(result, temp->data);
temp = temp->next;
}
return result;
}

github.com/aw-junaid 189
// Function to display the linked list
void displayList(Node* head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

int main() {
// Create the first linked list
Node* head1 = NULL;
addNode(head1, 'H');
addNode(head1, 'e');
addNode(head1, 'l');
addNode(head1, 'l');
addNode(head1, 'o');
cout << "List 1: ";
displayList(head1);

// Create the second linked list


Node* head2 = NULL;
addNode(head2, 'W');
addNode(head2, 'o');
addNode(head2, 'r');
addNode(head2, 'l');
addNode(head2, 'd');
cout << "List 2: ";
displayList(head2);

// Concatenate the two linked lists


Node* result = concatenateLists(head1, head2);
cout << "Concatenated list: ";
displayList(result);

return 0;
}

github.com/aw-junaid 190
218: Write a program that merges two ordered lists of integers into a
single ordered list of integers.

#include <iostream>
#include <vector>

using namespace std;

// Function to merge two ordered lists of integers


vector<int> mergeLists(const vector<int>& list1, const vector<int>& list2) {
// Create a vector to store the merged list
vector<int> mergedList;

// Declare iterators for both input lists


auto it1 = list1.begin();
auto it2 = list2.begin();

// Merge the two lists while they still have elements


while (it1 != list1.end() && it2 != list2.end()) {
if (*it1 < *it2) {
mergedList.push_back(*it1);
++it1;
} else {
mergedList.push_back(*it2);
++it2;
}
}

// Copy any remaining elements from list1 to the merged list


while (it1 != list1.end()) {
mergedList.push_back(*it1);
++it1;
}

// Copy any remaining elements from list2 to the merged list


while (it2 != list2.end()) {
mergedList.push_back(*it2);
++it2;
}

// Return the merged list


return mergedList;
}

github.com/aw-junaid 191
int main() {
// Create two ordered lists of integers
vector<int> list1 = {1, 3, 5, 7, 9};
vector<int> list2 = {2, 4, 6, 8, 10};

// Merge the two lists and store the result in a new list
vector<int> mergedList = mergeLists(list1, list2);

// Print the merged list


for (int num : mergedList) {
cout << num << " ";
}
cout << endl;

return 0;
}

github.com/aw-junaid 192
219: Write a program that inserts 25 random integers from 0 to 100 in
order in a linked list.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

// Define a node structure for the linked list


struct Node {
int data;
Node* next;
};

// Function to insert a node with given data in ascending order


void insert(Node*& head, int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = nullptr;

if (head == nullptr) {
// Empty list, insert at beginning
head = newNode;
} else if (data <= head->data) {
// Insert at beginning
newNode->next = head;
head = newNode;
} else {
// Find the node to insert after
Node* curr = head;
while (curr->next != nullptr && curr->next->data < data) {
curr = curr->next;
}
// Insert after the current node
newNode->next = curr->next;
curr->next = newNode;
}
}

github.com/aw-junaid 193
// Function to print the linked list
void printList(Node* head) {
Node* curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}

int main() {
// Seed the random number generator
srand(time(nullptr));

Node* head = nullptr;

// Insert 25 random integers in order


for (int i = 0; i < 25; i++) {
int data = rand() % 101; // Generate a random integer between 0 and 100
insert(head, data);
}

// Print the linked list


cout << "Linked List: ";
printList(head);

return 0;
}

github.com/aw-junaid 194
220: Write a program that creates a linked list of 10 characters, then
creates a copy of the list in reverse order.

#include <iostream>

using namespace std;

struct Node {
char data;
Node* next;
};

Node* createNode(char data) {


Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}

void insertNode(Node** head, char data) {


Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}

void printList(Node* head) {


while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}

Node* reverseList(Node* head) {


Node* prev = NULL;
Node* curr = head;
Node* next;

while (curr != NULL) {


next = curr->next;
curr->next = prev;
prev = curr;
curr = next;

github.com/aw-junaid 195
}

return prev;
}

int main() {
Node* head = NULL;
Node* copy = NULL;

// insert 10 characters in the list


insertNode(&head, 'a');
insertNode(&head, 'b');
insertNode(&head, 'c');
insertNode(&head, 'd');
insertNode(&head, 'e');
insertNode(&head, 'f');
insertNode(&head, 'g');
insertNode(&head, 'h');
insertNode(&head, 'i');
insertNode(&head, 'j');

cout << "Original List: ";


printList(head);

// reverse the original list and create a copy


copy = reverseList(head);

cout << "Reversed List: ";


printList(copy);

return 0;
}

github.com/aw-junaid 196
221: Write a program that inputs a line of text and uses a stack to print
the line reversed.

#include <iostream>
#include <stack>
#include <string>

int main() {
std::string line;
std::cout << "Enter a line of text: ";
std::getline(std::cin, line);

std::stack<char> s;
for (char c : line) {
s.push(c);
}

std::cout << "The line in reverse order is: ";


while (!s.empty()) {
std::cout << s.top();
s.pop();
}
std::cout << std::endl;

return 0;
}

github.com/aw-junaid 197
222: Write a function searchList that recursively searches a linked list
for a specified value.

#include <iostream>
using namespace std;

struct Node {
int data;
Node* next;
};

Node* createNode(int data) {


Node* newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
return newNode;
}

void insertNode(Node*& head, int data) {


Node* newNode = createNode(data);
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}

bool searchList(Node* head, int value) {


if (head == nullptr) {
return false;
}
if (head->data == value) {
return true;
}
return searchList(head->next, value);
}

github.com/aw-junaid 198
int main() {
Node* head = nullptr;
insertNode(head, 5);
insertNode(head, 10);
insertNode(head, 15);
insertNode(head, 20);

int value = 10;


bool found = searchList(head, value);
if (found) {
cout << "Value " << value << " found in the list." << endl;
} else {
cout << "Value " << value << " not found in the list." << endl;
}

return 0;
}

github.com/aw-junaid 199
223: Write a program that prints the command-line arguments of the
program.

#include <iostream>

int main(int argc, char* argv[]) {


std::cout << "Number of arguments: " << argc << std::endl;
std::cout << "Arguments: ";
for (int i = 0; i < argc; ++i) {
std::cout << argv[i] << " ";
}
std::cout << std::endl;
return 0;
}

github.com/aw-junaid 200
224: Overloaded square functions.

#include <iostream>

int square(int x) {
std::cout << "Calculating square of integer: " << x << std::endl;
return x * x;
}

double square(double x) {
std::cout << "Calculating square of double: " << x << std::endl;
return x * x;
}

int main() {
std::cout << square(5) << std::endl; // calls int version
std::cout << square(2.5) << std::endl; // calls double version
return 0;
}

github.com/aw-junaid 201
225: Inline function that calculates the volume of a sphere.

#include <iostream>
using namespace std;

// Define the inline function to calculate the volume of a sphere


inline double sphereVolume(double radius)
{
return (4.0 / 3.0) * 3.14159 * radius * radius * radius;
}

int main()
{
double radius;
cout << "Enter the radius of a sphere: ";
cin >> radius;

double volume = sphereVolume(radius);


cout << "The volume of the sphere is: " << volume << endl;

return 0;
}

github.com/aw-junaid 202
226: Create a class called Date that includes three pieces of
information as data members—a month (type int), a day (type int) and a
year (type int). Y

#include <iostream>

class Date {
public:
// Default constructor initializes date to 01/01/2000
Date() : month(1), day(1), year(2000) {}

// Constructor to set the date to a specific month, day, and year


Date(int m, int d, int y) : month(m), day(d), year(y) {}

// Accessor functions to get the month, day, and year


int getMonth() const {
return month;
}

int getDay() const {


return day;
}

int getYear() const {


return year;
}

// Mutator functions to set the month, day, and year


void setMonth(int m) {
month = m;
}

void setDay(int d) {
day = d;
}

void setYear(int y) {
year = y;
}

github.com/aw-junaid 203
// Function to display the date in the format mm/dd/yyyy
void displayDate() const {
std::cout << month << '/' << day << '/' << year << std::endl;
}

private:
int month;
int day;
int year;
};

github.com/aw-junaid 204
227: Write a program that demonstrates several exception types being
caught with the catch(...) exception handler

#include <iostream>
#include <string>

int main() {
try {
int x, y, result;
std::cout << "Enter two integers: ";
std::cin >> x >> y;

if (y == 0) {
throw std::string("Division by zero error");
}

result = x / y;

if (result > 100) {


throw std::out_of_range("Result is too large");
}

if (result < 0) {
throw std::runtime_error("Result is negative");
}

std::cout << "Result: " << result << std::endl;


}
catch (...) {
std::cout << "An exception occurred" << std::endl;
}

return 0;
}

github.com/aw-junaid 205
228: Write a program that shows a constructor passing information
about constructor failure to an exception handler after a try block.

#include <iostream>
#include <string>

class MyException {
private:
std::string message;
public:
MyException(const std::string& msg) : message(msg) {}
const std::string& getMessage() const {
return message;
}
};

class MyClass {
public:
MyClass(int value) {
if (value < 0) {
throw MyException("Invalid value passed to constructor");
}
// rest of the constructor code
}
};

int main() {
try {
MyClass obj(-1); // create object with invalid value
} catch (MyException& e) {
std::cout << "Exception caught: " << e.getMessage() << std::endl;
}

return 0;
}

github.com/aw-junaid 206
229: Write a program that illustrates rethrowing an exception.

#include <iostream>
#include <stdexcept>

void foo()
{
try {
// divide by zero to throw an exception
int x = 10 / 0;
}
catch (const std::exception& e) {
std::cerr << "Exception caught in foo(): " << e.what() << '\n';
// rethrow the exception to the caller
throw;
}
}

int main()
{
try {
foo();
}
catch (const std::exception& e) {
std::cerr << "Exception caught in main(): " << e.what() << '\n';
}

return 0;
}

github.com/aw-junaid 207

You might also like