100 C++
100 C++
Negative Number.
C++
// C++ Program to check whether a number is positive or
// negative
#include <iostream>
using namespace std;
int main()
{
int number;
number = -100;
if (number >= 0) {
cout << number << " is a positive number." << endl;
}
else {
cout << number << " is a negative number." << endl;
}
return 0;
}
Output
-100 is a negative number.
2. Write a Program to Find the Greatest of the Three Numbers.
C++
// C++ program to find greatest
// among three numbers using
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20, c = 30;
return 0;
}
Output
The Greatest Among Three Numbers is : 30
3. C++ Program To Check Whether Number is Even Or Odd
C++
// C++ program to check
// for even or odd
#include <iostream>
using namespace std;
// Returns true if n is
// even, else odd
bool isEven(int n) { return (n % 2 == 0); }
// Driver code
int main()
{
int n = 247;
if (isEven(n) == true) {
cout << "Even" << endl;
}
else {
cout << "Odd";
}
return 0;
}
Output
Odd
For more information, refer to the article – C++ Program To Check Whether
Number is Even Or Odd
4. Write a Program to Find the ASCII Value of a Character
C++
// C++ Program to find ASCII value of a character
#include <iostream>
using namespace std;
int main()
{
char ch;
ch = 'A';
cout << "The ASCII value of " << ch << " is " << int(ch)
<< endl;
return 0;
}
Output
The ASCII value of A is 65
5. Write a Program to Check Whether a Character is a Vowel or
Consonant
C++
// C++ Program to print whether a character is vowel or not
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
char ch = 'e';
if (isalpha(ch)) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'
|| ch == 'u' || ch == 'A' || ch == 'E'
|| ch == 'I' || ch == 'O' || ch == 'U') {
cout << ch << " is a vowel." << endl;
}
else {
cout << ch << " is a consonant." << endl;
}
}
else {
cout << ch << " is not an alphabet." << endl;
}
return 0;
}
Output
e is a vowel.
6. Write a Program to Print Check Whether a Character is an Alphabet
or Not
C++
// C++ program to print whether a character is an alphabet
// or not
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
char ch;
ch = 'a';
if (isalpha(ch)) {
cout << ch << " is an alphabet." << endl;
}
else {
cout << ch << " is not an alphabet." << endl;
}
return 0;
}
a is an alphabet.
7. Write a Program to Find the Length of the String Without using
strlen() Function
C++
// C++ Program to find the length of a string without using
// strlen()
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
string str = "GeeksforGeeks";
int length = 0;
cout << "The length of the string is: " << length
<< endl;
return 0;
}
Output
The length of the string is: 13
8. Write a Program to Toggle Each Character in a String
C++
// C++ Program to toggle string
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
string str = "GeeksforGeeks";
return 0;
}
Output
Toggled string: gEEKSFORgEEKS
9. Write a Program to Count the Number of Vowels
C++
// C++ Program to count the number of vowels
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
string str = "GeeksforGeeks to the moon";
int vowels = 0;
return 0;
}
Output
Number of vowels in the string: 9
10. Write a Program to Remove the Vowels from a String
C++
// C++ Program to remove the vowels from a string
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
int j = 0;
str[j] = '\0';
j++;
}
cout << "String without vowels: " << str << endl;
return 0;
}
Output
String without vowels: GksfrGks
11. Write a Program to Remove All Characters From a String Except
Alphabets
C++
// C++ Programto remove all characters from a string except
// alphabets
#include <cctype>
#include <iostream>
#include <string>
int main()
{
string str = "Gee$ksfor$geeks";
return 0;
}
Output
Alphabets only: Geeksforgeeks
12. Write a Program to Remove Spaces From a String
C++
// C++ Program to remove spaces from a string
#include <iostream>
#include <string>
int main()
{
string str = "Gfg to the moon";
return 0;
}
Output
Without spaces: Gfgtothemoon
13. Write a Program to Find the Sum of the First N Natural Numbers
C++
// C++ program to find
// Sum of first
// n natural numbers.
#include <iostream>
using namespace std;
int main()
{
int n = 7;
cout << findSum(n);
return 0;
}
Output
28
14. Write a Program to Find the Factorial of a Number Using Loops
C++
// C++ program to find factorial using loops
#include <bits/stdc++.h>
using namespace std;
return fact;
}
// driver code
int main()
{
int num = 5;
return 0;
}
Output
120
15. Write a Program to Find a Leap Year or Not
C++
// C++ program to check if a given
// year is leap year or not
#include <iostream>
using namespace std;
// leap year
if (year % 4 == 0)
return true;
int main()
{
int year = 2000;
if (checkYear(year))
cout << "Leap Year";
else
cout << "Not a Leap Year";
return 0;
}
Output
Leap Year
16. Write a Program to Check the Prime Number
C++
// C++ program to check if a
// Number is prime
#include <iostream>
using namespace std;
bool isPrime(int n)
{
// base condition
if (n <= 1)
return false;
return true;
}
int main()
{
isPrime(21) ? cout << " true\n" : cout << " false\n";
isPrime(17) ? cout << " true\n" : cout << " false\n";
return 0;
}
Output
false
true
17. Write a Program to Check Palindrome
C++
// C++ program to check if a
// number is Palindrome or not
#include <iostream>
using namespace std;
int main()
{
int n = 12321;
if (checkPalindrome(n) == 1) {
cout << "Yes\n";
}
else {
cout << "No\n";
}
return 0;
}
Output
Yes
18. Write a Program to Check Whether a Number is an Armstrong
Number or Not
C++
// C++ Program to check
// if number is Armstrong
// or not
#include <iostream>
using namespace std;
int main()
{
int n = 153;
int temp = n;
int ans = 0;
// function to calculate
// the sum of individual digits
while (n > 0) {
// condition to check
if (temp == ans) {
cout << ("Yes, it is Armstrong Number");
}
else {
cout << ("No, it is not an Armstrong Number");
}
return 0;
}
Output
Yes, it is Armstrong Number
19. Write a Program to Find the Nth Term of the Fibonacci Series
C++
// C++ Program to Find the
// Nth Term of the Fibonacci Series
#include <iostream>
using namespace std;
int fib(int n)
{
int first = 0, second = 1, ans;
if (n == 0)
return first;
return ans;
}
int main()
{
int n = 13;
cout << fib(n);
return 0;
}
Output
233
20. Write a Program to Calculate the Greatest Common Divisor of Two
Numbers
C++
// C++ program to find
// GCD of two numbers
#include <iostream>
return result;
}
int main()
{
int a = 54, b = 33;
return 0;
}
Output
GCD: 3
21. Write a Program to Calculate the Lowest Common Multiple (LCM)
of Two Numbers
C++
// C++ program to
// Find LCM of two numbers
#include <iostream>
using namespace std;
int main()
{
int a = 24, b = 13;
cout << "LCM : " << lcm(a, b);
return 0;
}
Output
LCM : 312
22. Write a Program for Finding the Roots of a Quadratic Equation
C++
// C++ program to find
// Roots of a quadratic equation
#include <iostream>
#include <math.h>
using namespace std;
// Formulae to calculate D
int d = b * b - 4 * a * c;
// Formulae to calculate
// square root of D
double sqrt_val = sqrt(abs(d));
int main()
{
int a = 1, b = 4, c = 4;
findRoots(a, b, c);
return 0;
}
Output
Roots are real and same
-2
23. Write a Program to Find the Smallest and Largest Element in an
Array
C++
// C++ code to for
// Finding the minimum
// And maximum of the array
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
findMinMax(arr, N);
return 0;
}
Output
Min: 1
Max: 5
24. Write a Program to Find the Second Smallest Element in an Array
C++
// C++ program to find
// Second smallest elements
#include <climits>
#include <iostream>
using namespace std;
if (n < 2) {
cout << " Invalid Input ";
return;
}
int main()
{
int arr[] = { 21, 3, 15, 41, 34, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
print2Smallest(arr, n);
return 0;
}
Output
Second smallest element is 10
25. Write a Program to Calculate the Sum of Elements in an Array
C++
// C++ Program to calculate
// sum of elements in an array
#include <iostream>
using namespace std;
int sum(int arr[], int n)
{
int sum = 0;
return sum;
}
int main()
{
int arr[] = { 1, 23, 54, 12, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
Output
Sum: 99
26. Write a Program to Check if the Given String is Palindrome or Not
C++
// C++ program for checking
// if it is Palindrome or not
#include <iostream>
using namespace std;
string isPalindrome(string S)
{
for (int i = 0; i < S.length() / 2; i++) {
if (S[i] != S[S.length() - i - 1]) {
return "No";
}
}
return "Yes";
}
int main()
{
string S = "GeekeeG";
return 0;
}
Output
Yes
27. Write a Program to Check if Two Strings are Anagram or Not
C++
// C++ program to check if two strings
// Are anagrams of each other
#include <iostream>
using namespace std;
if (str1[i] || str2[i])
return false;
return true;
}
int main()
{
char str1[] = "Geek";
char str2[] = "for";
if (areAnagram(str1, str2))
cout << "The two strings are anagram of each other";
else
cout << "The two strings are not anagram of each "
"other";
return 0;
}
Output
The two strings are not anagram of each other
28. Write a Program to Print a Diamond Pattern
*
***
*****
*******
*****
***
*
C++
// C++ program to print
// Diamond shape
#include <iostream>
using namespace std;
void printDiamond(int n)
{
int space = n - 1;
space = 0;
// Print i stars
for (int j = 0; j < i; j++)
cout << "* ";
int main()
{
printDiamond(5);
return 0;
}
Output
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
29. Write a Program to Print a Pyramid Pattern
*
***
*****
*******
C++
// C++ Program to
// Print Pyramid pattern
#include <iostream>
using namespace std;
void pattern(int n)
{
int k = 2 * n - 2;
k = k - 1;
for (int j = 0; j <= i; j++) {
// Printing stars
cout << "* ";
}
cout << endl;
}
}
int main()
{
int n = 5;
pattern(n);
return 0;
}
Output
*
* *
* * *
* * * *
* * * * *
30. Write a Program to Print the Hourglass Pattern
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
C++
// C Program to print hourglass pattern
#include <iostream>
using namespace std;
// assigning comparator
int comp;
if (i < rows) {
comp = 2 * i + 1;
}
else {
comp = 2 * (2 * rows - i) - 3;
}
int main()
{
hourglass(5);
return 0;
}
Output
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
31. Write a Program to Print the Rotated Hourglass Pattern
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
C++
// C++ Program to print
// star pattern given
#include <iostream>
using namespace std;
void pattern(int n)
{
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= i; j++) {
cout << "* ";
}
int main()
{
int n = 5;
pattern(n);
return 0;
}
Output
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
32. Write a Program to Print a Simple Pyramid Pattern
C++
// C++ Program to print a simple pyramid
#include <iostream>
using namespace std;
int main()
{
int rows = 5;
return 0;
}
Output
*
***
*****
*******
*********
33. Write a Program to print an Inverted Pyramid
C++
// C++ Program to print inverted pyramid
#include <iostream>
using namespace std;
int main()
{
int rows = 5;
return 0;
}
Output
*********
*******
*****
***
*
34. Write a Program to Print a Triangle Star Pattern
C++
// C++ Program to print a triangle star patter
#include <iostream>
using namespace std;
int main()
{
int rows;
rows = 5;
return 0;
}
Output
*
**
***
****
*****
35. Write a Program to Print Floyd’s Triangle
1
2 3
4 5 6
7 8 9 10
C++
// C Program to print the Floyd's Triangle
#include <stdio.h>
int main()
{
int rows = 4;
int n = 1;
Output
1
2 3
4 5 6
7 8 9 10
36. Write a Program to Print the Pascal Triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
C++
// C++ program to print
// Pascal’s Triangle
#include <iostream>
using namespace std;
void printPascal(int n)
{
int arr[n][n];
int main()
{
int n = 6;
printPascal(n);
return 0;
}
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
37. Write a Program to Print the Given String in Reverse Order
C++
// C++ Program to reversea string
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
int len;
len = str.size();
return 0;
}
Output
Reverse of the string: skeeGrofskeeG
38. Write a C++ Program to Print the Given String in Reverse Order
Using Recursion
C++
// C++ Program to
// Reverse string using
// recursion
#include <iostream>
using namespace std;
swap(s[i], s[n]);
reverse_str(s, n - 1, i + 1);
}
int main()
{
string str = "GeeksforGeeks";
reverse_str(str, str.length() - 1, 0);
cout << str << endl;
}
Output
skeeGrofskeeG
39. Write a Program to Check if the Given String is Palindrome or not
Using Recursion
C++
// C++ program to check
// Whether a given number
// Is palindrome or not
#include <bits/stdc++.h>
using namespace std;
if (s < n + 1)
return isPalRec(str, s + 1, n - 1);
return true;
}
bool isPalindrome(char str[])
{
int n = strlen(str);
if (n == 0)
return true;
int main()
{
char str[] = "GeeKeeG";
if (isPalindrome(str))
cout << "Yes";
else
cout << "No";
return 0;
}
Output
Yes
40. Write a Program to Calculate the Length of the String Using
Recursion
C++
// C++ Program for calculating
// the length of string
#include <iostream>
using namespace std;
int main()
{
char str[] = "GeeksforGeeks";
cout << cal(str);
return 0;
}
Output
13
41. Write a Program to Calculate the Factorial of a Number Using
Recursion
C++
// C++ program to calculate
// Factorial of given number
#include <iostream>
using namespace std;
int main()
{
unsigned long long num = 15;
return 0;
}
Output
Factorial of 15 is 1307674368000
42. Write a Program to Count the Sum of Numbers in a String
C++
// C++ Program to count the sume of numbers in a string
#include <iostream>
#include <sstream>
#include <string>
int main()
{
string str;
str = "1234";
return 0;
}
Output
Sum of numbers: 10
43. Write a Program to Print All Natural Numbers up to N Without
Using a Semi-Colon
C++
// C++ program to print all natural numbers upto
// N without using semi-colon
#include <iostream>
int main()
{
static int x = 1;
if (cout << x << " " && x++ < N && main()) {
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
44. Write a Program to Swap the Values of Two Variables Without
Using any Extra Variable
C++
// C++ program to check
// If two numbers are equal
#include <iostream>
using namespace std;
int main()
{
int x = 3;
int y = 4;
x = x + y;
y = x - y;
x = x - y;
return 0;
}
Output
X : 3
Y : 4
After:
X : 4
Y : 3
45. Write a Program to Print the Maximum Value of an Unsigned int
Using One’s Complement (~) Operator
C++
// C++ program to print maximum value of
// unsigned int.
#include <iostream>
int main()
{
unsigned int max;
max = 0;
max = ~max;
return 0;
}
Output
Max value possible : 4294967295
46. Write a Program to Check for the Equality of Two Numbers Without
Using Arithmetic or Comparison Operator
C++
// C++ Program to equality of
// Two numbers without using
// Arithmetic or comparison operator
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 10;
if (a ^ b)
cout << "Not-Equal";
else
cout << "Equal";
return 0;
}
Output
Equal
47. Write a Program to Find the Maximum and Minimum of the Two
Numbers Without Using the Comparison Operator
C++
// C++ program to find
// maximum and minimum of
// Two numbers without using
// loop and conditions
#include <iostream>
int main()
{
int a = 5, b = 10;
cout << "max :" << (((a + b) + abs(a - b)) / 2) << endl;
cout << "min :" << (((a + b) - abs(a - b)) / 2) << endl;
return 0;
}
Output
max :10
min :5
48. Write a Program for Octal to Decimal Conversion
C++
// C++ Program to convert ocatal to decimal
#include <cmath>
#include <iostream>
int main()
{
int oct, dec = 0, place = 0;
// 67 is an octal number with binary equivalent 110000
oct = 67;
cout << "Decimal equivalent is: " << dec << endl;
return 0;
}
Output
Decimal equivalent is: 55
49. Write a Program for Hexadecimal to Decimal Conversion
C++
// C++ Program to convert hexadecimal to decimal conversion
#include <cmath>
#include <iostream>
int main()
{
string hex;
int decimal = 0, place = 0;
hex = "67";
int n = hex.length();
for (int i = n - 1; i >= 0; i--) {
int digit = hexToDecimal(hex[i]);
decimal += digit * pow(16, place);
place++;
}
return 0;
}
Output
Decimal equivalent 103
50. Write a Program for Decimal to Binary Conversion
C++
// c++ program to convert decimal to binary
#include <bitset>
#include <iostream>
int main()
{
int decimal = 7;
return 0;
}
Output
Binary equivalent: 00000000000000000000000000000111
51. Write a Program for Decimal Octal Conversion
C++
// C++ Program to convert decimal to octal equivalent
#include <cmath>
#include <iostream>
int main()
{
int decimal, octal = 0, place = 1;
decimal = 55;
return 0;
}
Output
Octal equivalent 67
52. Write a Program for Decimal to Hexadecimal Conversion
C++
// C++ program to convert decimal to hexadecimal
#include <cmath>
#include <iostream>
#include <string>
int main()
{
int decimal = 103;
return 0;
}
Output
Hexadecimal equivalent: 67
53. Write a Program for Binary to Octal Conversion
C++
// C++ implementation to convert a binary number
// to octal number
#include <bits/stdc++.h>
using namespace std;
while (1) {
// one by one extract from left, substring
// of size 3 and add its octal code
octal += bin_oct_map[bin.substr(i, 3)];
i += 3;
if (i == bin.size())
break;
Output
Octal number = 1712241.26633
54. Write a Program for Octal to Binary Conversion
C++
// C++ program to convert
// Octal number to Binary
#include <iostream>
using namespace std;
// Function to convert an
// Octal to Binary Number
string OctToBin(string octnum)
{
long int i = 0;
while (octnum[i]) {
switch (octnum[i]) {
case '0':
binary += "000";
break;
case '1':
binary += "001";
break;
case '2':
binary += "010";
break;
case '3':
binary += "011";
break;
case '4':
binary += "100";
break;
case '5':
binary += "101";
break;
case '6':
binary += "110";
break;
case '7':
binary += "111";
break;
default:
cout << "\nInvalid Octal Digit " << octnum[i];
break;
}
i++;
}
return binary;
}
// Driver code
int main()
{
// Get the Hexadecimal number
string octnum = "345";
return 0;
}
Output
Equivalent Binary Value = 011100101
55. Write a Program to Implement the Use of Encapsulation
C++
// C++ Program to implement
// The concept of Encapsulation
#include <iostream>
using namespace std;
class Encapsulation {
private:
// data hidden from outer functions
int x;
public:
// function to set value of
// variable x
void setter(int a) { x = a; }
// function to return value of
// variable x
int getter() { return x; }
};
int main()
{
Encapsulation obj;
obj.setter(13);
return 0;
}
Output
13
56. Write a Program to Implement the Concept of Abstraction
C++
// C++ Program to implement
// Working of Abstraction
#include <iostream>
using namespace std;
class implementAbstraction {
private:
int p, q;
public:
// method to set values of
// private members
void setter(int x, int y)
{
p = x;
q = y;
}
void display()
{
cout << "p = " << p << endl;
cout << "q = " << q << endl;
}
};
int main()
{
implementAbstraction obj;
obj.setter(1, 2);
obj.display();
return 0;
}
Output
p = 1
q = 2
57. Write a Program to Implement the Concept of Compile-Time
Polymorphism or Function Overloading
C++
// C++ program to demonstrate
// Function overloading or
// Compile-time Polymorphism
#include <iostream>
class Geeks {
public:
// Function same name different
// Parameters
void func(int x)
{
cout << "value of x is " << x << endl;
}
void func(double x)
{
cout << "value of x is " << x << endl;
}
int main()
{
Geeks obj1;
Output
value of x is 10
value of x is 5.321
value of x and y is 94, 32
58. Write a Program to Implement the Concept of Operator Overloading
C++
// C++ program to demonstrate
// Operator Overloading
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
int main()
{
Complex c1(15, 5), c2(3, 5);
Complex c3 = c1 + c2;
c3.print();
}
Output
18 + 10i
59. Write a Program to Implement the Concept of Function Overriding
or Runtime Polymorphism
C++
// C++ program for implementation
// of Function Overloading or
// Compile time Polymorphism
#include <iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}
int main()
{
base* bptr;
derived d;
bptr = &d;
bptr->print();
return 0;
}
Output
print derived class
show base class
60. Write a Program to Implement Single-Level Inheritance
C++
// C++ Program to implement
// Single level inheritance
#include <iostream>
#include <string.h>
class Person {
int id;
char name[100];
public:
void set_p(int id, char* name)
{
strcpy(this->name, name);
this->id = id;
}
void display_p()
{
cout << endl << id << "\t" << name << "\t";
}
};
public:
void set_s(int id, char* name, char* course, int fee)
{
set_p(id, name);
strcpy(this->course, course);
this->fee = fee;
}
void display_s()
{
display_p();
main()
{
Student s;
char name[] = "XYZ";
char course[] = "ABC";
s.set_s(132451, name, course, 100000);
s.display_s();
return 0;
}
Output
132451 XYZ ABC 100000
61. Write a Program to Create a Class for Complex Numbers
C++
// C++ Program to create a class of complex numbers
#include <bits/stdc++.h>
using namespace std;
// complex clss
class Complex {
private:
struct c num;
public:
// constructors
Complex() {}
Complex(double real, double img)
{
num.img = img;
num.real = real;
}
Complex(Complex& var)
{
num.img = var.num.img;
num.real = var.num.real;
}
// utility functions
void print()
{
cout << num.real << " + i" << num.img << endl;
}
// overloaded operators
Complex operator+(Complex& obj1)
{
Complex var;
var.num.real = num.real + obj1.num.real;
var.num.img = num.img + obj1.num.img;
return var;
}
Complex operator-(Complex& obj1)
{
Complex var;
var.num.real = num.real - obj1.num.real;
var.num.img = num.img - obj1.num.img;
return var;
}
return var;
}
};
// driver code
int main()
{
Complex a(11, 12), b(5, 8);
Complex c;
c = a + b;
a.print();
b.print();
c.print();
return 0;
}
Output
11 + i12
5 + i8
16 + i20
62. Write a Program to Implement the Inch Feet System
C++
// C++ Program to create a class of inchFeet length system
#include <bits/stdc++.h>
using namespace std;
// inchFeet class
class inchFeet {
private:
struct c length;
public:
// constructors
inchFeet() {}
inchFeet(double feet, double inch)
{
length.inch = inch;
length.feet = feet;
}
inchFeet(inchFeet& var)
{
length.inch = var.length.inch;
length.feet = var.length.feet;
}
// utility functions
void print()
{
cout << length.feet << " feet and " << length.inch
<< " inches" << endl;
}
// overloaded operators
inchFeet operator+(inchFeet& obj1)
{
inchFeet var;
var.length.feet = length.feet + obj1.length.feet;
var.length.inch = length.inch + obj1.length.inch;
if (var.length.inch >= 12.0) {
var.length.feet++;
var.length.inch - 12.0;
}
return var;
}
inchFeet operator-(inchFeet& obj1)
{
inchFeet var;
struct c temp = length;
if (temp.feet > obj1.length.feet) {
if (temp.inch < obj1.length.inch) {
temp.feet--;
temp.inch += 12;
}
var.length.feet = temp.feet - obj1.length.feet;
var.length.inch = temp.inch - obj1.length.inch;
}
else {
cout << "Negative Length is not Possible\n";
}
return var;
}
};
// driver code
int main()
{
inchFeet a(11, 4), b(5, 8);
inchFeet c;
c = a - b;
a.print();
b.print();
c.print();
return 0;
}
Output
11 feet and 4 inches
5 feet and 8 inches
5 feet and 8 inches
63. Write a Program to Implement Bubble Sort
C++
// C++ program to implement
// of Bubble sort
#include <iostream>
using namespace std;
// Function to sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
int main()
{
int arr[] = { 3, 1, 4, 2, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
Output
Sorted array: 1 2 3 4 5
64. Write a Program to Implement Insertion Sort
C++
// C++ program to implement
// Insertion sort
#include <bits/stdc++.h>
using namespace std;
// Print array
void print_array(int arr[], int n)
{
cout << " Sorted array:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = { 1, 4, 3, 2, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
insertion_sort(arr, N);
print_array(arr, N);
return 0;
}
Output
Sorted array:1 2 3 4 5
65. Write a Program to Implement Selection Sort
C++
// C++ program to implement
// Selection sort
#include <iostream>
using namespace std;
// Swap function
void swap(int* p, int* q)
{
int temp = *p;
*p = *q;
*q = temp;
}
// Print Array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = { 5, 4, 3, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
return 0;
}
Output
Sorted array: 1 2 3 4 5
66. Write a Program to Implement Merge Sort
C++
// C++ program to implement
// Merge Sort
#include <iostream>
using namespace std;
// Print Array
void print_array(int A[], int size)
{
for (auto i = 0; i < size; i++)
cout << A[i] << " ";
}
int main()
{
int arr[] = { 5, 6, 3, 10, 1, 4, 9 };
auto arr_size = sizeof(arr) / sizeof(arr[0]);
Output
Array: 5 6 3 10 1 4 9
Sorted array: 1 3 4 5 6 9 10
67. Write a Program to Implement Quick Sort
C++
// C++ Program to implement
// QuickSort
#include <iostream>
using namespace std;
// Swap elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
// Partition function to check pivot location
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1);
// Print Array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = { 2, 5, 6, 9, 1, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
Output
Array: 2 5 6 9 1 3 4
Sorted array: 1 2 3 4 5 6 9
68. Write a Program to Implement Linear Search
C++
// C++ Program to implement
// Linear Sort
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 5, 4, 1, 6, 10, 9, 23, 2 };
int x = 9;
int N = sizeof(arr) / sizeof(arr[0]);
if (result == -1)
cout << "Element is not present in array";
else
cout << "Element is present at index " << result;
return 0;
}
Output
Element is present at index 5
69. Write a Program to Implement Binary Search
C++
// C++ program to implement
// Binary Search
#include <iostream>
using namespace std;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
int main(void)
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int x = 5;
int n = sizeof(arr) / sizeof(arr[0]);
if (result == -1)
cout << "Element is not present in array";
else
cout << "Element is present at index " << result;
return 0;
}
Output
Element is present at index 4
70. Write a Program to Find the Index of a Given Element in a Vector
C++
// C++ program to find the index
// of an element in a vector
#include <bits/stdc++.h>
int main()
{
vector<int> v = { 1, 2, 3, 4, 5, 6 };
int element = 5;
print_index(v, element);
return 0;
}
Output
4
71. Write a Program to Remove Duplicate Elements in an Array Using
STL
C++
// C++ program to remove the
// duplicate elements from the array
// using STL in C++
#include <bits/stdc++.h>
int i;
set<int> s;
set<int>::iterator it;
int main()
{
int arr[] = { 1, 2, 2, 4, 3, 3, 2, 1 };
// Print array
cout << "\nBefore removing duplicates:\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
removeDuplicates(arr, n);
return 0;
}
Output
Before removing duplicates:
1 2 2 4 3 3 2 1
After removing duplicates:
1 2 3 4
72. Write a Program to Sort an Array in Descending Order Using STL
C++
// C++ program to sort Array
// in descending order
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Get the array
int arr[] = { 1, 2, 3, 4, 5, 6 };
return 0;
}
Output
Array: 1 2 3 4 5 6
Descending Sorted Array:6 5 4 3 2 1
73. Write a Program to Calculate the Frequency of Each Word in the
Given String
C++
// C++ program to calculate
// frequency of each word
// in given string
#include <bits/stdc++.h>
using namespace std;
// if element is empty
if (str[i] == ' ') {
// If the current word
// is not found then insert
// current word with frequency 1
if (M.find(word) == M.end()) {
M.insert(make_pair(word, 1));
word = "";
}
else {
M[word]++;
word = "";
}
}
else
word += str[i];
}
int main()
{
string str = "Geeks For Geeks is for Geeks";
printFrequency(str);
return 0;
}
Output
For - 1
Geeks - 3
for - 1
is - 1
74. Write a Program to Find k Maximum Elements of an Array in the
Original Order
C++
// C++ program to find k Maximum elements
#include <bits/stdc++.h>
using namespace std;
// Printing elements
for (int i = 0; i < n; i++) {
if (result[i] == 1)
cout << c[i] << " ";
}
}
int main()
{
int arr[] = { 50, 8, 45, 12, 25, 40, 84 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
printMax(arr, n, k);
return 0;
}
Output
50 45 84
75. Write a Program to Find All Unique Subsets of a Given Set Using
STL
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
v.push_back(arr[i]);
solve(arr, n, ans, v, i + 1);
}
sort(arr.begin(), arr.end());
vector<int> v;
solve(arr, n, ans, v, 0);
// Print Function
void print(int N, vector<int>& A)
{
vector<vector<int> > result = AllSubsets(A, N);
int main()
{
int N = 3;
vector<int> A = { 1, 2, 3 };
print(N, A);
return 0;
}
Output
(), (1), (1 2), (1 2 3), (1 3), (2), (2 3), (3),
76. Write a Program to Iterate Over a Queue Without Removing the
Element
C++
// C++ program to iterate a
// STL Queue by Creating
// copy of given queue
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
// Copy queue
queue<int> copy_queue = q;
while (!copy_queue.empty()) {
cout << copy_queue.front() << " ";
copy_queue.pop();
}
return 0;
}
Output
Queue elements :
1 2 3 4 5
77. Write a Program for the Implementation of Stacks Using an Array
C++
// C++ Program to implement stacks using array
#include <iostream>
using namespace std;
class Stack {
private:
int top;
// Array to store stack elements
int arr[MAX];
public:
// Constructor to initialize top as -1
Stack() { top = -1; }
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
return 0;
}
Output
Popped element: 5
Top element: 4
78. Write a Program for the Implementation of a Queue Using an Array
C++
// C++ Program to implement queue using array
#include <iostream>
using namespace std;
class Queue {
private:
int front, rear;
// Array to store queue elements
int arr[MAX];
public:
// Constructor to initialize front and rear as -1
int main()
{
Queue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
return 0;
}
Output
Dequeued element: 1
Front element: 2
79. Write a Program Implementation of Stacks Using a Queue
C++
// C++ Program to implement
// Stack using queue
#include <bits/stdc++.h>
class Stack {
queue<int> q1, q2;
public:
void push(int x)
{
// Push x first in empty q2
q2.push(x);
void pop()
{
// if no elements are there in q1
if (q1.empty())
return;
q1.pop();
}
int top()
{
if (q1.empty())
return -1;
return q1.front();
}
int main()
{
Stack s;
Output
Size: 4
4
3
2
Size: 2
80. Write a Program to Implement a Stack Using the List in STL
C++
// C++ Program to implement
// stack using list
#include <bits/stdc++.h>
// Template declared
template <typename T> class Stack {
public:
list<T> l;
int cs = 0;
// current size of the stack
Output
Size: 4
Top element:4
Top element:3
Top element:2
Size:2
81. Write a Program to Determine Array is a Subset of Another Array or
Not
C++
// C++ Program to check if
// Array is a subset of another array or not
#include <iostream>
using namespace std;
if (j == m)
return 0;
}
return 1;
}
int main()
{
int arr1[] = { 1, 11, 31, 21, 30, 17 };
int arr2[] = { 11, 30, 17, 1 };
return 0;
}
Output
arr2 is subset of arr1
82. Write a Program for Finding the Circular Rotation of an Array by K
Positions
C++
// C++ Program for Finding
// Circular rotation of an array
// by K positions
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
int k = 2;
// Function calling
Rotate(arr, k, N);
print_array(arr, N);
return 0;
}
Output
3 4 5 1 2
83. Write a Program to Sort the First Half in Ascending Order and the
Second Half in Descending
C++
// C++ Program to Sort first half
// in ascending order and second half in descending
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int len = sizeof(arr) / sizeof(arr[0]);
ascDecFunc(arr, len);
return 0;
}
Output
1 2 3 4 8 7 6 5
84. Write a Program to Print the Given String in Reverse Order
C++
// C++ program to demonstrate reverse
// of a string using Last to First
#include <iostream>
using namespace std;
int main(void)
{
string str = "GeeksforGeeks";
reverse(str);
return (0);
}
Output
skeeGrofskeeG
85. Write a Program to Print All Permutations of a String Using
Recursion
C++
// C++ Program to Print
// Permutaions of string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "ABC";
string answer = "";
permute(s, answer);
return 0;
}
Output
ABC
ACB
BAC
BCA
CAB
CBA
86. Write a Program to Print All Permutations of a Given String in
Lexicographically Sorted Order
C++
// C++ Program to Print all permutations
// Of a given string in lexicographically sorted order
#include <bits/stdc++.h>
using namespace std;
return ceilIndex;
}
if (i == -1)
isFinished = true;
else {
int ceilIndex
= findCeil(str, str[i], i + 1, size - 1);
swap(&str[i], &str[ceilIndex]);
qsort(str + i + 1, size - i - 1, sizeof(str[0]),
compare);
}
}
}
int main()
{
char str[] = "XYZ";
Permutations(str);
return 0;
}
Output
XYZ
XZY
YXZ
YZX
ZXY
ZYX
87. Write a Program to Remove Brackets From an Algebraic Expression
C++
// C++ Program to remove brackets from an algebraic exp
#include <iostream>
#include <string>
int main()
{
string str = "Geeks)(for)(geeks";
return 0;
}
struct Node {
int data;
Node* next;
};
// function to print LL
void printList()
{
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main()
{
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
cout << "Linked List is \n";
printList();
deleteNode(3);
cout << "Linked List after deletion of 3: ";
printList();
return 0;
}
Output
Linked List is
5 4 3 2 1
Linked List after deletion of 3: 5 4 2 1
89. Program to Perform Insert, Delete, and Print Operations Doubly
Linked List
C++
// C++ Program to implement insert, delete, and print
// operation in doubly linked list
#include <iostream>
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList()
: head(NULL)
{
}
if (head != NULL)
head->prev = newNode;
head = newNode;
}
if (temp == NULL)
return;
if (temp->prev != NULL)
temp->prev->next = temp->next;
else
head = temp->next;
if (temp->next != NULL)
temp->next->prev = temp->prev;
delete temp;
}
void printList()
{
Node* temp = head;
while (temp != NULL) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
};
int main()
{
DoublyLinkedList dll;
dll.insertAtStart(1);
dll.insertAtStart(2);
dll.insertAtStart(3);
dll.insertAtStart(4);
dll.insertAtStart(5);
dll.deleteNode(2);
return 0;
}
Output
Original Doubly Linked List: 5 4 3 2 1
Doubly Linked List after deletion: 5 4 3 1
90. Program to Perform Insert, Delete, and Print Operations Circular
Linked List
C++
// C++ Program to implement insert, delete, and print in
// circular linked list
#include <iostream>
struct Node {
int data;
Node* next;
};
class CircularLinkedList {
private:
Node* head;
public:
CircularLinkedList()
: head(NULL)
{
}
if (head == NULL) {
head = newNode;
newNode->next = head;
}
else {
Node* temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = newNode;
head = newNode;
}
}
if (temp->next == head) {
head = NULL;
delete temp;
return;
}
if (temp->data != data)
return;
prev->next = temp->next;
if (temp == head)
head = temp->next;
delete temp;
}
void printList()
{
Node* temp = head;
while (temp->next != head) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << temp->data << std::endl;
}
};
int main()
{
CircularLinkedList cll;
cll.insertAtStart(1);
cll.insertAtStart(2);
cll.insertAtStart(3);
cll.insertAtStart(4);
cll.insertAtStart(5);
return 0;
}
Output
Original Circular Linked list 5 4 3 2 1
Circular Linked List after deletion 5 4 3 1
91. Program for Inorder Traversal in a Binary Tree
C++
// C++ program Inorder Traversal
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
cout << "Inorder traversal of binary tree is \n";
printInorder(root);
return 0;
}
Output
Inorder traversal of binary tree is
4 2 5 1 3
92. Program to Find All its Subsets From a Set of Positive Integers
C++
// C++ Program to find all subsets from the given set of
// positive integers
#include <bits/stdc++.h>
subset.push_back(A[i]);
find_subset(A, ans, subset, i + 1);
subset.pop_back();
}
return;
}
int index = 0;
find_subset(A, ans, subset, index);
return ans;
}
int main()
{
vector<int> array = { 1, 2, 3, 4, 5 };
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 5
1 2 4
1 2 4 5
1 2 5
1 3
1 3 4
1 3 4 5
1 3 5
1 4
1 4 5
1 5
2
2 3
2 3 4
2 3 4 5
2 3 5
2 4
2 4 5
2 5
3
3 4
3 4 5
3 5
4
4 5
5
93. Program for Preorder Traversal in a Binary Tree
C++
// C++ program for preorder traversal
#include <bits/stdc++.h>
using namespace std;
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
cout << "Preorder traversal of binary tree is \n";
printPreorder(root);
return 0;
}
Output
Preorder traversal of binary tree is
1 2 4 5 3
94. Program for Postorder Traversal in a Binary Tree
C++
// C++ program for post order traversal
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
};
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
cout << "Postorder traversal of binary tree is \n";
printPostorder(root);
return 0;
}
Output
Postorder traversal of binary tree is
4 5 2 3 1
95. Program for Level-Order Traversal in a Binary Tree
C++
// C++ program for post order traversal
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
};
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
cout << "Levelorder traversal of binary tree is \n";
printLevelOrder(root);
return 0;
}
Output
Levelorder traversal of binary tree is
1 2 3 4 5
96. Write a Program for the Top View of a Binary Tree
C++
// C++ program for top view of a binary tree
#include <bits/stdc++.h>
using namespace std;
q.push(root);
while (q.size()) {
hd = root->hd;
if (m.count(hd) == 0)
m[hd] = root->data;
if (root->left) {
root->left->hd = hd - 1;
q.push(root->left);
}
if (root->right) {
root->right->hd = hd + 1;
q.push(root->right);
}
q.pop();
root = q.front();
}
// Driver code
int main()
{
// new binary tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->right = newNode(5);
topView(root);
return 0;
}
Output
4 2 1 3 5
97. Write a Program to Print the Bottom View of a Binary Tree
C++
// C++ program for bottom view of a binary tree
#include <bits/stdc++.h>
using namespace std;
return node;
}
queue<Node*> q;
map<int, int> m;
int hd = 0;
root->hd = hd;
q.push(root);
while (!q.empty()) {
Node* temp = q.front();
q.pop();
hd = temp->hd;
m[hd] = temp->data;
if (temp->left != NULL) {
temp->left->hd = hd - 1;
q.push(temp->left);
}
if (temp->right != NULL) {
temp->right->hd = hd + 1;
q.push(temp->right);
}
}
// Driver Code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->right = newNode(5);
bottomView(root);
return 0;
}
Output
4 2 1 3 5
98. Write a Program to Print the Left View of a Binary Tree
C++
// C++ program to print left view of a binary tree
#include <bits/stdc++.h>
using namespace std;
// node datatype
struct Node {
Node* left;
Node* right;
int data;
};
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
if (i == 1)
cout << temp->data << " ";
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
}
}
// Driver code
int main()
{
leftView(root);
}
Output
1 2 4
99. Write a Program to Print the Right View of the Binary Tree
C++
// C++ program to print the right view of a binary tree
#include <bits/stdc++.h>
using namespace std;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
while (n--) {
Node* x = q.front();
q.pop();
if (n == 0) {
cout << x->data << " ";
}
if (x->left) {
q.push(x->left);
}
if (x->right) {
q.push(x->right);
}
}
}
}
// Driver code
int main()
{
rightView(root);
}
Output
1 3 5
100. Write a Program for the Conversion of Infix Expression to Postfix
Expression
C++
// C++ program for infix expression to postfix expression
// conversion
#include <bits/stdc++.h>
using namespace std;
return postfix;
}
// driver code
int main()
{
string s = "a*b+(c-d)";
cout << infixToPostfix(s);
return 0;
}
Output
ab*cd-+