C Programming Examples From Basics to Advanced
C Programming Examples From Basics to Advanced
github.com/aw-junaid 1
C++ Programming Examples: From Basics to Advanced
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.
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
#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
}
#include <iostream>
using namespace std;
github.com/aw-junaid 10
int main() {
int num1, num2, num3;
int product;
return 0;
#include <iostream>
using namespace std;
int main() {
cout << "Hello, ";
cout << "world!";
cout << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
cout << "Hello,\nworld!\n";
return 0;
}
github.com/aw-junaid 11
#include <iostream>
using namespace std;
int main() {
int num1, num2, sum;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int num1 = 5, num2 = 10;
// Use the SWAP macro to swap the values of the two numbers
SWAP(num1, num2);
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;
}
#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);
return 0;
}
#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;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int num1, 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;
}
#include <iostream>
github.com/aw-junaid 14
using namespace std;
int main() {
int sum = 0;
cout << "The sum of integers from 1 to 5 is " << sum << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
char ch;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int rows;
github.com/aw-junaid 15
cout << "Enter the number of rows: ";
cin >> rows;
return 0;
}
#include <iostream>
using namespace std;
int main() {
double num1, num2, product, quotient;
cout << "The product of the two numbers is: " << product << endl;
cout << "The quotient of the two numbers is: " << quotient << endl;
return 0;
}
#include <iostream>
using namespace std;
github.com/aw-junaid 16
int main() {
int rollNo;
float marks[7], total = 0, average;
average = total / 7;
return 0;
}
#include <iostream>
int main() {
int 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;
}
#include <iostream>
int main() {
int x, y, result = 1;
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>
int main() {
int num, newNum = 0, 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;
}
#include <iostream>
#include <cmath>
int main() {
long long binaryNum, decimalNum = 0;
int power = 0;
cout << "The decimal equivalent of the binary number is " << decimalNum << endl;
return 0;
}
#include <iostream>
using namespace std;
github.com/aw-junaid 19
nt main() {
float base1, base2, height, area;
cout << "The area of the trapezium is " << area << endl;
return 0;
}
#include <iostream>
int main() {
float side, area;
cout << "The area of the square is " << area << endl;
return 0;
}
#include <iostream>
github.com/aw-junaid 20
#include <iostream>
int main() {
float base, height, area;
cout << "Enter the length of the base of the triangle: ";
cin >> base;
cout << "The area of the triangle is " << area << endl;
return 0;
}
#include <iostream>
int main() {
float num1, num2, num3, num4, num5, max;
max = num1;
github.com/aw-junaid 21
if (num4 > max) {
max = num4;
}
cout << "The greatest number among " << num1 << ", " << num2 << ", " << num3
<< ", " << num4 << ", and " << num5 << " is " << max << endl;
return 0;
}
#include <iostream>
int main() {
int decimalNum, binaryNum = 0, i = 1, rem;
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;
}
#include <iostream>
using namespace std;
github.com/aw-junaid 22
#include <iostream>
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;
// 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;
}
#include <iostream>
#include <iomanip>
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;
}
#include <iostream>
github.com/aw-junaid 23
using namespace std;
int main() {
cout << "The odd numbers from 1 to 7 are:" << endl;
return 0;
}
#include <iostream>
int main() {
int num1, num2, num3, num4, maxNum;
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;
}
#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>
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;
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;
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>
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
return 0;
}
#include <iostream>
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;
}
#include <iostream>
#include <random>
int main() {
// Define the range of the random integer (0 to 99)
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0, 99);
github.com/aw-junaid 27
cout << "Shifted and scaled integer: " << scaled_num << endl;
return 0;
}
#include <iostream>
int main() {
int num;
cout << "Enter a number to print its multiplication table: ";
cin >> num;
cout << "Multiplication table of " << num << ":" << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
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;
return 0;
}
#include <iostream>
int main() {
int num, reversed = 0;
cout << "Enter a number: ";
cin >> num;
cout << "The reversed number is: " << reversed << endl;
return 0;
}
#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;
int arr[n];
cout << "Enter " << n << " elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
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;
ptr1 = &num1;
ptr2 = &num2;
cout << "Sum of " << *ptr1 << " and " << *ptr2 << " is " << sum << endl;
return 0;
}
#include <iostream>
using namespace std;
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;
}
#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;
}
#include <iostream>
using namespace std;
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;
}
#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;
}
#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;
cout << "Roll: " << roll1 << " + " << roll2 << " = " << sum << endl;
github.com/aw-junaid 35
return 0;
}
#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;
}
int main() {
double x;
int n;
return 0;
}
github.com/aw-junaid 36
#include <iostream>
using namespace std;
int main() {
int num;
bool isPrime = true;
if(isPrime)
cout << num << " is a prime number";
else
cout << num << " is not a prime number";
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
github.com/aw-junaid 37
}
cout << "The sum of the series 1 + 2 + 3 + ... + " << n << " is " << sum << endl;
return 0;
}
#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
return 0;
}
#include <iostream>
using namespace std;
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;
}
#include <iostream>
using namespace std;
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;
}
#include <iostream>
github.com/aw-junaid 39
using namespace std;
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;
}
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
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;
}
#include <iostream>
using namespace std;
int main()
{
int num;
long long factorial = 1;
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;
}
#include <iostream>
using namespace std;
int main()
{
int n, i, a = 0, b = 1, c;
return 0;
}
#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;
}
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int number, originalNumber, remainder, result = 0, n = 0;
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;
}
#include <iostream>
int main()
{
bool x, y, z;
github.com/aw-junaid 45
}
return 0;
}
#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;
}
github.com/aw-junaid 46
#include <iostream>
#include <unordered_set>
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;
}
#include <iostream>
using namespace std;
int main() {
int num1, num2;
github.com/aw-junaid 47
cout << "Before swapping, num1 = " << num1 << " and num2 = " << num2 << endl;
cout << "After swapping, num1 = " << num1 << " and num2 = " << num2 << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
char op;
float num1, num2, result;
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;
}
#include <iostream>
using namespace std;
int main() {
float num1, num2, result;
int 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;
}
#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>
int main() {
int year;
return 0;
}
#include <iostream>
using namespace std;
int main() {
double gallons, liters;
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;
}
#include <iostream>
using namespace std;
int main() {
int num, reversed = 0, remainder, original;
cout << "Enter a number: ";
cin >> num;
original = num;
github.com/aw-junaid 52
}
return 0;
}
#include <iostream>
int main()
{
int first_term, common_diff, num_terms, sum;
cout << "The sum of the AP series is: " << sum << endl;
return 0;
}
github.com/aw-junaid 53
#include <iostream>
#include <cmath>
int main() {
double a, r, n, sum;
cout << "The sum of the G.P series is: " << sum << endl;
return 0;
}
#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;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int num, digit, sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
github.com/aw-junaid 55
num /= 10;
}
cout << "The sum of the digits is: " << sum << endl;
return 0;
}
#include <iostream>
#include <string>
#include <cctype>
int main() {
string text;
int count = 0;
cout << "The number of letters in the text is: " << count << endl;
return 0;
}
#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];
}
return 0;
}
#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;
}
#include <iostream>
using namespace std;
github.com/aw-junaid 57
int main() {
int num;
cout << "The entered number is: " << num << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "GCD of " << num1 << " and " << num2 << " is: " << gcd(num1, num2);
return 0;
}
#include <iostream>
using namespace std;
int main() {
int num, fact = 1;
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;
}
#include <iostream>
using namespace std;
int main() {
int num, absValue;
return 0;
}
#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;
// input matrix1
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
cin >> matrix1[i][j];
}
}
// input matrix2
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
cin >> matrix2[i][j];
}
}
return 0;
}
github.com/aw-junaid 60
84: Program to find roots of a quadratic equation.
#include <iostream>
#include <cmath>
int main() {
double a, b, c, root1, root2, discriminant;
// Calculate discriminant
discriminant = b * b - 4 * a * c;
return 0;
}
#include <iostream>
using namespace std;
github.com/aw-junaid 61
int main() {
int rows, coef = 1;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int rows, num=1;
cout << "Enter the number of rows: ";
cin >> rows;
github.com/aw-junaid 62
num++;
cout << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n, num = 1;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int rows, num = 1;
github.com/aw-junaid 63
for(int i = rows; i >= 1; i--)
{
for(int j = 1; j <= i; j++)
{
cout << "* ";
}
cout << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int n, i, j, space;
github.com/aw-junaid 64
return 0;
}
#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;
}
return 0;
}
#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;
}
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;
return 0;
}
#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"};
return 0;
}
#include <iostream>
using namespace std;
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 -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];
}
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;
quotient = decimalNumber;
while (quotient != 0) {
octalNumber[i++] = quotient % 8;
quotient /= 8;
}
return 0;
}
#include <iostream>
#include <string>
#include <algorithm>
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;
}
#include <iostream>
#include <string>
int main() {
string hexNum;
cout << "Enter a hexadecimal number: ";
cin >> hexNum;
github.com/aw-junaid 70
int len = hexNum.length();
cout << "The binary equivalent is " << binNum << endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
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;
}
#include <iostream>
using namespace std;
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;
}
#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;
}
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;
}
#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>
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;
}
#include <iostream>
#include <cstring>
int main()
{
char str[100];
int len;
len = strlen(str);
cout << "Length of the string is: " << len << endl;
return 0;
}
github.com/aw-junaid 74
#include <iostream>
#include <string>
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();
#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];
}
}
return 0;
}
107: Program to find compound interest.
#include <iostream>
#include <cmath>
int main()
{
double principle, rate, time, compound_interest;
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;
weeks = days / 7;
days = days % 7;
return 0;
}
#include <iostream>
#define CUBE(x) (x * x * x)
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Cube of " << num << " is: " << CUBE(num) << endl;
return 0;
}
#include <iostream>
using namespace std;
github.com/aw-junaid 77
int main() {
int arr[50], size, pos, 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];
}
return 0;
}
#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];
}
return 0;
}
#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}};
// 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
}
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};
// 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;
}
#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++;
}
}
}
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
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;
return 0;
}
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 5; // change this to adjust the size of the arrays
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;
// 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;
}
#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;
}
#include <iostream>
using namespace std;
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];
}
}
}
}
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];
return 0;
}
github.com/aw-junaid 86
120: Program to find inverse of a matrix.
#include <iostream>
using namespace std;
github.com/aw-junaid 86
sign = ((i+j) % 2 == 0) ? 1 : -1;
adj[j][i] = sign * determinant(temp, N-1);
}
}
}
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;
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;
}
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;
}
#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];
cout << "The second largest element in the array is: " << secondLargest << endl; //
print second largest element
return 0;
}
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;
cout << "The second smallest element in the array is: " << secondSmallest <<
endl; // print second smallest element
return 0;
}
#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];
}
github.com/aw-junaid 90
// increment the size of the array
n++;
return 0;
}
#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
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";
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;
}
#include <iostream>
using namespace std;
int main() {
char str1[100], str2[100];
int i, j, flag = 0;
if(i != j) {
cout << "The two strings are not equal" << endl;
github.com/aw-junaid 92
return 0;
}
if(flag == 0) {
cout << "The two strings are equal" << endl;
} else {
cout << "The two strings are not equal" << endl;
}
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[100];
cout << "The length of the string is: " << length << endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
github.com/aw-junaid 93
int main() {
char sourceStr[100], destStr[100];
strcpy(destStr, sourceStr);
cout << "The copied string is: " << destStr << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
char sourceStr[100], destStr[100];
int i = 0;
cout << "The copied string is: " << destStr << endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
github.com/aw-junaid 94
int main() {
char str[100];
reverseString(str);
cout << "The reversed string is: " << str << endl;
return 0;
}
#include <iostream>
#include <string>
#include <algorithm>
int main() {
string str1, str2;
github.com/aw-junaid 95
cout << "String 2 = " << str2 << endl;
swap(str1, str2);
return 0;
}
#include <iostream>
#include <string>
#include <algorithm>
int main() {
string 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>
return 0;
}
#include <iostream>
#include <algorithm>
#include <cstring>
github.com/aw-junaid 97
using namespace std;
int main()
{
char str1[100], str2[100];
if (len1 != len2) {
cout << "Strings are not anagrams of each other." << endl;
return 0;
}
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
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;
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;
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];
return 0;
}
github.com/aw-junaid 101
#include <iostream>
using namespace std;
int main() {
// create two complex numbers
ComplexNumber num1, num2;
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;
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
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 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;
}
#include <iostream>
using namespace std;
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);
#include <iostream>
using namespace std;
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);
return 0;
}
#include <iostream>
using namespace std;
int main() {
int n, i, j, flag = 1;
int mat[MAX][MAX];
github.com/aw-junaid 107
cin >> mat[i][j];
}
}
return 0;
}
github.com/aw-junaid 108
148: Program for linked list representation of linear queue.
#include <iostream>
using namespace std;
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;
}
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;
}
#include <iostream>
using namespace std;
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;
return 0;
}
#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;
}
#include <iostream>
#include <fstream>
#include <string>
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;
github.com/aw-junaid 113
}
}
cout << "The word '" << word << "' appears " << count << " times in the file." <<
endl;
return 0;
}
#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");
github.com/aw-junaid 115
154: Program to delete a file.
#include <stdio.h>
#include <stdlib.h>
int main() {
char filename[100];
if (remove(filename) == 0) {
printf("%s file deleted successfully.\n", filename);
} else {
printf("Unable to delete the file.\n");
}
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
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}};
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();
return 0;
}
156: Program to write on data file and read from data file.
#include <iostream>
#include <fstream>
#include <string>
int main() {
// Open a file for writing
ofstream outFile("data.txt");
github.com/aw-junaid 117
outFile << "This is some data.\n";
outFile << "12345\n";
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>
int main() {
vector<string> filenames = {"file1.txt", "file2.txt", "file3.txt"}; // input filenames
string output_filename = "output.txt"; // output filename
return 0;
}
github.com/aw-junaid 119
158: Program to replace specified line in a text file.
#include <iostream>
#include <fstream>
#include <string>
int main() {
string filename, line, newLine;
int lineNumber;
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++;
}
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>
int main()
{
ifstream inFile("input.txt"); // input file
ofstream outFile("output.txt"); // output file
string line;
int lineNumber, currentLine = 0;
// 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;
}
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout << "GCD of " << num1 << " and " << num2 << " is " << result << endl;
return 0;
}
#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;
}
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;
}
#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";
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;
}
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;
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;
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;
}
#include <stdio.h>
struct date {
int day;
int month;
int year;
};
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);
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;
}
166: Program two functions xgets( ) and xputs( ) which work similar to
the standard library functions gets( ) and puts( ).
#include <iostream>
#include <cstring>
github.com/aw-junaid 129
if (ch == '\n')
break;
str[i] = ch;
i++;
}
str[i] = '\0';
}
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;
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);
}
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
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;
return 0;
}
github.com/aw-junaid 132
169: Program that can be used at command prompt as a calculating
utility.
#include <iostream>
#include <string>
int main() {
string expression;
cout << "Enter an arithmetic expression: ";
getline(cin, expression);
#include <windows.h>
#include <cstdio>
github.com/aw-junaid 133
171: Program that displays three buttons ‘Yes’, ‘No’ ‘Cancel’ in the
message box.
#include <windows.h>
#include <iostream>
#include <windows.h>
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);
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");
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
// 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);
// 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;
}
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;
}
#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>
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>
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;
}
return 0;
}
github.com/aw-junaid 141
179: Program to create GradeBook object and call its displayMessage
function.
#include <iostream>
#include <string>
class GradeBook {
public:
void displayMessage() {
cout << "Welcome to the Grade Book program!" << endl;
}
};
int main() {
GradeBook myGradeBook;
myGradeBook.displayMessage();
return 0;
}
#include <iostream>
using namespace std;
int main() {
float weight, height, bmi;
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;
#include <iostream>
using namespace std;
int main() {
char grade;
int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0;
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;
}
}
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 << " ";
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;
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;
}
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 = "";
github.com/aw-junaid 149
if(decimalValue >= 90) {
romanValue += "XC";
decimalValue -= 90;
}
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;
}
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()
int main() {
int roll; // The variable to store the result of the die roll
return 0;
}
github.com/aw-junaid 152
190: Program a recursive factorial function.
#include <iostream>
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>
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 << "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 << "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>
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;
if (coin == 0)
headsCount++;
else
tailsCount++;
}
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;
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
return 0;
}
github.com/aw-junaid 159
197: Write a program to treating character arrays as strings.
#include <iostream>
#include <cstring>
int main()
{
char name[50];
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " << name << "!" << endl;
char copy[50];
strcpy(copy, name);
cout << "Copy of name: " << copy << 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};
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;
}
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;
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;
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;
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);
return 0;
}
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];
}
}
github.com/aw-junaid 168
204: Write a Program for counting the occurrences of a substring.
#include <iostream>
#include <string>
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;
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>
if (str[0] == '-') {
sign = -1;
i++;
}
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>
if (str[0] == '-') {
sign = -1;
i++;
}
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;
int main() {
int choice;
double value;
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>
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>
int main() {
ifstream inputFile("input.txt"); // open input file
string line; // to store each line of the file
github.com/aw-junaid 177
212: Credit inquiry program.
#include <iostream>
#include <fstream>
#include <string>
github.com/aw-junaid 178
}
}
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>
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);
github.com/aw-junaid 180
// Calculate the position to write the record to
int position = (record.id - 1) * sizeof(Record);
return 0;
}
github.com/aw-junaid 181
214: Program for inserting and deleting nodes in a list.
#include <iostream>
using namespace std;
// Search for the key to be deleted, keep track of the previous node
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
github.com/aw-junaid 182
// Unlink the node from linked list
prev->next = temp->next;
delete temp; // Free memory
}
int main() {
Node* head = NULL;
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;
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
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;
/
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);
}
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;
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);
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>
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);
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>
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));
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>
struct Node {
char data;
Node* next;
};
github.com/aw-junaid 195
}
return prev;
}
int main() {
Node* head = NULL;
Node* copy = NULL;
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);
}
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;
};
github.com/aw-junaid 198
int main() {
Node* head = nullptr;
insertNode(head, 5);
insertNode(head, 10);
insertNode(head, 15);
insertNode(head, 20);
return 0;
}
github.com/aw-junaid 199
223: Write a program that prints the command-line arguments of the
program.
#include <iostream>
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;
int main()
{
double radius;
cout << "Enter the radius of a sphere: ";
cin >> radius;
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) {}
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 < 0) {
throw std::runtime_error("Result is negative");
}
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