Top 100 C++ Coding Interview Questions and Answers [2025 Updated]
Last Updated :
23 Jul, 2025
C++ is one of the most popular languages in the software industry for developing software ranging from operating systems, and DBMS to games. That is why it is also popular to be asked to write C++ Programs in live coding sessions in job placement interviews.
This article provides a list of C++ coding interview questions for beginners as well as experienced professionals. The questions are designed to test candidates' understanding of the following topics:
- C++ syntax and semantics
- Data structures and algorithms
- Object-oriented programming
- Memory management
- Pointers
- Templates
List of 100 C++ Coding Interview Questions and Answers
Here is a list of 100 C++ coding interview questions and answers
1. Write a C++ Program to Check Whether a Number is a Positive or 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;
cout << "The Greatest Among Three Numbers is : ";
if (a >= b && a >= c) {
cout << a << endl;
}
else if (b >= a && b >= c) {
cout << b << endl;
}
else {
cout << c << endl;
}
return 0;
}
OutputThe 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;
}
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;
}
OutputThe 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;
}
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;
}
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;
for (int i = 0; str[i] != '\0'; i++) {
length++;
}
cout << "The length of the string is: " << length
<< endl;
return 0;
}
OutputThe 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";
for (int i = 0; str[i] != '\0'; i++) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
else if (isupper(str[i])) {
str[i] = tolower(str[i]);
}
}
cout << "Toggled string: " << str << endl;
return 0;
}
OutputToggled 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;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i'
|| str[i] == 'o' || str[i] == 'u'
|| str[i] == 'A' || str[i] == 'E'
|| str[i] == 'I' || str[i] == 'O'
|| str[i] == 'U') {
vowels++;
}
}
cout << "Number of vowels in the string: " << vowels
<< endl;
return 0;
}
OutputNumber 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;
string str = "GeeksforGeeks";
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] != 'a' && str[i] != 'e' && str[i] != 'i'
&& str[i] != 'o' && str[i] != 'u'
&& str[i] != 'A' && str[i] != 'E'
&& str[i] != 'I' && str[i] != 'O'
&& str[i] != 'U') {
str[j++] = str[i];
}
}
while (j < str.size()) {
str[j] = '\0';
j++;
}
cout << "String without vowels: " << str << endl;
return 0;
}
OutputString 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>
using namespace std;
string remove_non_alphabets(string str)
{
string result = "";
for (char c : str) {
if (isalpha(c)) {
result += c;
}
}
return result;
}
int main()
{
string str = "Gee$ksfor$geeks";
cout << "Alphabets only: " << remove_non_alphabets(str)
<< endl;
return 0;
}
OutputAlphabets 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>
using namespace std;
string remove_spaces(string str)
{
string result = "";
for (char c : str) {
if (c != ' ') {
result += c;
}
}
return result;
}
int main()
{
string str = "Gfg to the moon";
cout << "Without spaces: " << remove_spaces(str)
<< endl;
return 0;
}
OutputWithout 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;
// Function to find sum
int findSum(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
sum = sum + i;
return sum;
}
int main()
{
int n = 7;
cout << findSum(n);
return 0;
}
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;
// function to find factorial
int factorial(int n)
{
int fact = 1;
while (n > 1) {
fact *= n;
n--;
}
return fact;
}
// driver code
int main()
{
int num = 5;
cout << factorial(num);
return 0;
}
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;
bool checkYear(int year)
{
// leap year
if (year % 400 == 0)
return true;
// Not leap year
if (year % 100 == 0)
return false;
// leap year
if (year % 4 == 0)
return true;
// Not leap year
return false;
}
int main()
{
int year = 2000;
if (checkYear(year))
cout << "Leap Year";
else
cout << "Not a Leap Year";
return 0;
}
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;
// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
int main()
{
isPrime(21) ? cout << " true\n" : cout << " false\n";
isPrime(17) ? cout << " true\n" : cout << " false\n";
return 0;
}
17. Write a Program to Check Palindrome
C++
// C++ program to check if a
// number is Palindrome or not
#include <iostream>
using namespace std;
// Function to check Palindrome
bool checkPalindrome(int n)
{
int ans = 0;
int temp = n;
while (temp != 0) {
ans = (ans * 10) + (temp % 10);
temp = temp / 10;
}
return (ans == n);
}
int main()
{
int n = 12321;
if (checkPalindrome(n) == 1) {
cout << "Yes\n";
}
else {
cout << "No\n";
}
return 0;
}
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) {
int rem = n % 10;
ans = (ans) + (rem * rem * rem);
n = n / 10;
}
// condition to check
if (temp == ans) {
cout << ("Yes, it is Armstrong Number");
}
else {
cout << ("No, it is not an Armstrong Number");
}
return 0;
}
OutputYes, 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;
for (int i = 2; i <= n; i++) {
ans = first + second;
first = second;
second = ans;
}
return ans;
}
int main()
{
int n = 13;
cout << fib(n);
return 0;
}
20. Write a Program to Calculate the Greatest Common Divisor of Two Numbers
C++
// C++ program to find
// GCD of two numbers
#include <iostream>
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
int result = min(a, b);
while (result > 0) {
if (a % result == 0 && b % result == 0) {
break;
}
result--;
}
return result;
}
int main()
{
int a = 54, b = 33;
cout << "GCD: " << gcd(a, b);
return 0;
}
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;
long long gcd(long long int a, long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to return LCM of two numbers
long long lcm(int a, int b)
{
long long result = (a / gcd(a, b)) * b;
return result;
}
int main()
{
int a = 24, b = 13;
cout << "LCM : " << lcm(a, b);
return 0;
}
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;
// Prints roots of quadratic equation ax*2 + bx + c
void findRoots(int a, int b, int c)
{
// If a is 0, then equation is not quadratic
if (a == 0) {
cout << "Invalid";
return;
}
// Formulae to calculate D
int d = b * b - 4 * a * c;
// Formulae to calculate
// square root of D
double sqrt_val = sqrt(abs(d));
// Conditons for checking root
if (d > 0) {
cout << "Roots are real and different \n";
cout << (double)(-b + sqrt_val) / (2 * a) << "\n"
<< (double)(-b - sqrt_val) / (2 * a);
}
else if (d == 0) {
cout << "Roots are real and same \n";
cout << -(double)b / (2 * a);
}
else {
cout << "Roots are complex \n";
cout << -(double)b / (2 * a) << " + i"
<< sqrt_val / (2 * a) << "\n"
<< -(double)b / (2 * a) << " - i"
<< sqrt_val / (2 * a);
}
}
int main()
{
int a = 1, b = 4, c = 4;
findRoots(a, b, c);
return 0;
}
OutputRoots 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;
// Function to find the minimum
// and maximum of the array
void findMinMax(int arr[], int n)
{
int mini = arr[0];
int maxi = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] < mini) {
mini = arr[i];
}
else if (arr[i] > maxi) {
maxi = arr[i];
}
}
cout << "Min: " << mini << endl;
cout << "Max: " << maxi << endl;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
findMinMax(arr, N);
return 0;
}
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;
void print2Smallest(int arr[], int n)
{
int first, second;
if (n < 2) {
cout << " Invalid Input ";
return;
}
first = second = INT_MAX;
for (int i = 0; i < n; i++) {
// If current element is smaller than first
// Then update both first and second
if (arr[i] < first) {
second = first;
first = arr[i];
}
// If arr[i] is in between first and second
// Then update second
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == INT_MAX)
cout << "There is no second smallest element\n";
else
cout << " Second smallest element is " << second
<< endl;
}
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;
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
int main()
{
int arr[] = { 1, 23, 54, 12, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Sum: " << sum(arr, n);
return 0;
}
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";
cout << isPalindrome(S);
return 0;
}
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;
#define NO_OF_CHARS 256
bool areAnagram(char* str1, char* str2)
{
// Create 2 count arrays and initialize all values as 0
int count1[NO_OF_CHARS] = { 0 };
int count2[NO_OF_CHARS] = { 0 };
int i;
// For each character in input strings, increment count
// in the corresponding count array
for (i = 0; str1[i] && str2[i]; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}
if (str1[i] || str2[i])
return false;
// Compare count arrays
for (i = 0; i < NO_OF_CHARS; i++)
if (count1[i] != count2[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;
}
OutputThe 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;
for (int i = 0; i < n; i++) {
for (int j = 0; j < space; j++)
cout << " ";
// Print i+1 stars
for (int j = 0; j <= i; j++)
cout << "* ";
cout << endl;
space--;
}
space = 0;
// run loop (parent loop)
for (int i = n; i > 0; i--) {
for (int j = 0; j < space; j++)
cout << " ";
// Print i stars
for (int j = 0; j < i; j++)
cout << "* ";
cout << endl;
space++;
}
}
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;
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++)
cout << " ";
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;
// function to print hourglass pattern
void hourglass(int rows)
{
// first outer loop to iterate each row
for (int i = 0; i < 2 * rows - 1; i++) {
// assigning comparator
int comp;
if (i < rows) {
comp = 2 * i + 1;
}
else {
comp = 2 * (2 * rows - i) - 3;
}
// first inner loop to print leading spaces
for (int j = 0; j < comp; j++) {
cout << ' ';
}
// second inner loop to print star *
for (int k = 0; k < 2 * rows - comp; k++) {
cout << "* ";
}
cout << '\n';
}
}
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 spaces = 2 * (n - i);
for (int j = 0; j < spaces; j++) {
cout << " ";
}
for (int j = 0; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
// Printing bottom part.
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
cout << "* ";
}
int spaces = 2 * (n - i);
for (int j = 0; j < spaces; j++) {
cout << " ";
}
for (int j = 0; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
}
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;
for (int i = 1; i <= rows; i++) {
for (int j = rows; j >= i; j--) {
cout << " ";
}
for (int k = 1; k <= (2 * i - 1); k++) {
cout << "*";
}
cout << endl;
}
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;
for (int i = rows; i >= 1; i--) {
for (int j = rows; j > i; j--) {
cout << " ";
}
for (int k = 1; k <= (2 * i - 1); k++) {
cout << "*";
}
cout << endl;
}
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;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}
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;
// outer loop to print all rows
for (int i = 0; i < rows; i++) {
// innter loop to print abphabet in each row
for (int j = 0; j <= i; j++) {
printf("%d ", n++);
}
printf("\n");
}
return 0;
}
Output1
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];
for (int line = 0; line < n; line++) {
// Every line has number of integers
// equal to line number
for (int i = 0; i <= line; i++) {
// First and last values in every row are 1
if (line == i || i == 0)
arr[line][i] = 1;
else
arr[line][i] = arr[line - 1][i - 1]
+ arr[line - 1][i];
cout << arr[line][i] << " ";
}
cout << "\n";
}
}
int main()
{
int n = 6;
printPascal(n);
return 0;
}
Output1
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;
string str = "GeeksforGeeks";
len = str.size();
cout << "Reverse of the string: ";
for (int i = len - 1; i >= 0; i--) {
cout << str[i];
}
cout << endl;
return 0;
}
OutputReverse 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;
void reverse_str(string& s, int n, int i)
{
if (n <= i) {
return;
}
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;
}
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;
bool isPalRec(char str[], int s, int n)
{
// If there is only one character
if (s == n)
return true;
// If first and last
// characters do not match
if (str[s] != str[n])
return false;
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;
return isPalRec(str, 0, n - 1);
}
int main()
{
char str[] = "GeeKeeG";
if (isPalindrome(str))
cout << "Yes";
else
cout << "No";
return 0;
}
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 cal(char* str)
{
// base condition
if (*str == '\0')
return 0;
else
return 1 + cal(str + 1);
}
int main()
{
char str[] = "GeeksforGeeks";
cout << cal(str);
return 0;
}
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;
unsigned long long factorial(unsigned long long n)
{
if (n == 0 || n == 1)
return 1;
return n * factorial(n - 1);
}
int main()
{
unsigned long long num = 15;
cout << "Factorial of " << num << " is "
<< factorial(num) << endl;
return 0;
}
OutputFactorial 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>
using namespace std;
int sum_of_numbers(string str)
{
int sum = 0;
for (char ch : str) {
if (isdigit(ch)) {
sum += ch - '0';
}
}
return sum;
}
int main()
{
string str;
str = "1234";
cout << "Sum of numbers: " << sum_of_numbers(str)
<< endl;
return 0;
}
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>
using namespace std;
#define N 10
int main()
{
static int x = 1;
if (cout << x << " " && x++ < N && main()) {
}
return 0;
}
Output1 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;
cout << "X : " << x << endl;
cout << "Y : " << y << endl;
x = x + y;
y = x - y;
x = x - y;
cout << endl;
cout << "After:" << endl;
cout << "X : " << x << endl;
cout << "Y : " << y << endl;
return 0;
}
OutputX : 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>
using namespace std;
int main()
{
unsigned int max;
max = 0;
max = ~max;
cout << "Max value possible : " << max;
return 0;
}
OutputMax 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;
}
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>
using namespace std;
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;
}
48. Write a Program for Octal to Decimal Conversion
C++
// C++ Program to convert ocatal to decimal
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int oct, dec = 0, place = 0;
// 67 is an octal number with binary equivalent 110000
oct = 67;
int temp = oct;
while (temp) {
int lastDigit = temp % 10;
temp /= 10;
dec += lastDigit * pow(8, place);
++place;
}
cout << "Decimal equivalent is: " << dec << endl;
return 0;
}
OutputDecimal 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>
using namespace std;
int hexToDecimal(char hexDigit)
{
if (hexDigit >= '0' && hexDigit <= '9') {
return int(hexDigit - '0');
}
else if (hexDigit >= 'A' && hexDigit <= 'F') {
return int(hexDigit - 'A' + 10);
}
else if (hexDigit >= 'a' && hexDigit <= 'f') {
return int(hexDigit - 'a' + 10);
}
return -1;
}
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++;
}
cout << "Decimal equivalent " << decimal << endl;
return 0;
}
OutputDecimal equivalent 103
50. Write a Program for Decimal to Binary Conversion
C++
// c++ program to convert decimal to binary
#include <bitset>
#include <iostream>
using namespace std;
int main()
{
int decimal = 7;
// simplest method to convert decimal to binary
bitset<32> binary(decimal);
cout << "Binary equivalent: " << binary << endl;
return 0;
}
OutputBinary equivalent: 00000000000000000000000000000111
51. Write a Program for Decimal Octal Conversion
C++
// C++ Program to convert decimal to octal equivalent
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int decimal, octal = 0, place = 1;
decimal = 55;
int temp = decimal;
while (temp) {
int lastDigit = temp % 8;
temp /= 8;
octal += lastDigit * place;
place *= 10;
}
cout << "Octal equivalent " << octal << endl;
return 0;
}
OutputOctal 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>
using namespace std;
string decimalToHexa(int decimal)
{
string hexadecimal = "";
char hexaDecimals[16]
= { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
while (decimal > 0) {
int remainder = decimal % 16;
hexadecimal = hexaDecimals[remainder] + hexadecimal;
decimal /= 16;
}
return hexadecimal;
}
int main()
{
int decimal = 103;
cout << "Hexadecimal equivalent: "
<< decimalToHexa(decimal) << endl;
return 0;
}
OutputHexadecimal 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;
// function to create map between binary
// number and its equivalent octal
void createMap(unordered_map<string, char>* um)
{
(*um)["000"] = '0';
(*um)["001"] = '1';
(*um)["010"] = '2';
(*um)["011"] = '3';
(*um)["100"] = '4';
(*um)["101"] = '5';
(*um)["110"] = '6';
(*um)["111"] = '7';
}
// Function to find octal equivalent of binary
string convertBinToOct(string bin)
{
int l = bin.size();
int t = bin.find_first_of('.');
// length of string before '.'
int len_left = t != -1 ? t : l;
// add min 0's in the beginning to make
// left substring length divisible by 3
for (int i = 1; i <= (3 - len_left % 3) % 3; i++)
bin = '0' + bin;
// if decimal point exists
if (t != -1) {
// length of string after '.'
int len_right = l - len_left - 1;
// add min 0's in the end to make right
// substring length divisible by 3
for (int i = 1; i <= (3 - len_right % 3) % 3; i++)
bin = bin + '0';
}
// create map between binary and its
// equivalent octal code
unordered_map<string, char> bin_oct_map;
createMap(&bin_oct_map);
int i = 0;
string octal = "";
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;
// if '.' is encountered add it to result
if (bin.at(i) == '.') {
octal += '.';
i++;
}
}
// required octal number
return octal;
}
// Driver program to test above
int main()
{
string bin = "1111001010010100001.010110110011011";
cout << "Octal number = " << convertBinToOct(bin);
return 0;
}
OutputOctal 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;
string binary = "";
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";
// Convert Octal to Binary
cout << "Equivalent Binary Value = "
<< OctToBin(octnum);
return 0;
}
OutputEquivalent 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);
cout << obj.getter();
return 0;
}
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;
}
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>
using namespace std;
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;
}
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};
int main()
{
Geeks obj1;
// Function being called depends
// on the parameters passed
// func() is called with int value
obj1.func(10);
// func() is called with double value
obj1.func(5.321);
// func() is called with 2 int values
obj1.func(94, 32);
return 0;
}
Outputvalue 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;
}
// This is automatically called
// when '+' is used
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + " << imag << "i\n"; }
};
int main()
{
Complex c1(15, 5), c2(3, 5);
Complex c3 = c1 + c2;
c3.print();
}
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;
}
void show() { cout << "show base class" << endl; }
};
class derived : public base {
public:
void print() { cout << "print derived class" << endl; }
void show() { cout << "show derived class" << endl; }
};
int main()
{
base* bptr;
derived d;
bptr = &d;
bptr->print();
// Non-virtual function, binded
// at compile time
bptr->show();
return 0;
}
Outputprint 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>
using namespace std;
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";
}
};
class Student : private Person {
char course[50];
int fee;
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();
cout << course << "\t" << fee << endl;
}
};
main()
{
Student s;
char name[] = "XYZ";
char course[] = "ABC";
s.set_s(132451, name, course, 100000);
s.display_s();
return 0;
}
Output132451 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 number datatype
struct c {
double real;
double img;
};
// 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;
}
double imag() { return num.img; }
double real() { return num.real; }
// 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;
}
Complex operator*(Complex& obj1)
{
Complex var;
var.num.real = num.real * obj1.num.real
- num.img * obj1.num.img;
var.num.img = num.real * obj1.num.img
+ num.img * obj1.num.real;
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;
}
Output11 + 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;
// inch-feet length system datatype
struct c {
double feet;
double inch;
};
// 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;
}
double inches() { return length.inch; }
double feet() { return length.feet; }
// 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;
}
Output11 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++)
// Last i elements are already
// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = { 3, 1, 4, 2, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
cout << "Sorted array: ";
printArray(arr, N);
return 0;
}
OutputSorted 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;
// Function to sort using
// Insertion
void insertion_sort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// 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;
}
void selectionSort(int arr[], int n)
{
int min_index;
for (int i = 0; i < n - 1; i++) {
min_index = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_index])
min_index = j;
// Swap the found minimum element
// with the first element
if (min_index != i)
swap(&arr[min_index], &arr[i]);
}
}
// 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);
cout << "Sorted array: ";
printArray(arr, n);
return 0;
}
OutputSorted 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;
// Merge Sorted arrays
void merge(int array[], int const left, int const mid,
int const right)
{
auto const subArrayOne = mid - left + 1;
auto const subArrayTwo = right - mid;
// Create temp arrays
auto *leftArray = new int[subArrayOne],
*rightArray = new int[subArrayTwo];
// Copy data to temp arrays leftArray[] and rightArray[]
for (auto i = 0; i < subArrayOne; i++)
leftArray[i] = array[left + i];
for (auto j = 0; j < subArrayTwo; j++)
rightArray[j] = array[mid + 1 + j];
auto indexOfSubArrayOne = 0, indexOfSubArrayTwo = 0;
int indexOfMergedArray = left;
// Merge the temp arrays back into array[left..right]
while (indexOfSubArrayOne < subArrayOne
&& indexOfSubArrayTwo < subArrayTwo) {
if (leftArray[indexOfSubArrayOne]
<= rightArray[indexOfSubArrayTwo]) {
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
}
else {
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
}
indexOfMergedArray++;
}
// Copying remaing elements
while (indexOfSubArrayOne < subArrayOne) {
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
}
while (indexOfSubArrayTwo < subArrayTwo) {
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
}
delete[] leftArray;
delete[] rightArray;
}
void mergeSort(int array[], int const begin, int const end)
{
// base condition
if (begin >= end)
return;
auto mid = begin + (end - begin) / 2;
mergeSort(array, begin, mid);
mergeSort(array, mid + 1, end);
merge(array, begin, mid, end);
}
// 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]);
cout << "Array: ";
print_array(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
cout << "\nSorted array: ";
print_array(arr, arr_size);
return 0;
}
OutputArray: 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);
for (int j = low; j <= high - 1; j++) {
// If current element is smaller than the pivot
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
// Quick Sort function
void quickSort(int arr[], int low, int high)
{
if (low < high) {
// pi is partitioning index, arr[p] is now
// at right place
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// 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]);
cout << "Array: ";
printArray(arr, n);
quickSort(arr, 0, n - 1);
cout << "Sorted array: ";
printArray(arr, n);
return 0;
}
OutputArray: 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 search(int arr[], int N, int x)
{
int i;
for (i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}
int main()
{
int arr[] = { 5, 4, 1, 6, 10, 9, 23, 2 };
int x = 9;
int N = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, N, x);
if (result == -1)
cout << "Element is not present in array";
else
cout << "Element is present at index " << result;
return 0;
}
OutputElement 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;
// Binary Search Function
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
// Middle element
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
int main(void)
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int x = 5;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
if (result == -1)
cout << "Element is not present in array";
else
cout << "Element is present at index " << result;
return 0;
}
OutputElement 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>
using namespace std;
// print index of element
void print_index(vector<int> v, int element)
{
auto it = find(v.begin(), v.end(), element);
// Condition if element found
if (it != v.end()) {
// Calculating the index
// of element
int index = it - v.begin();
cout << index << endl;
}
// No such element in vector
else {
cout << "-1" << endl;
}
}
int main()
{
vector<int> v = { 1, 2, 3, 4, 5, 6 };
int element = 5;
print_index(v, element);
return 0;
}
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>
using namespace std;
// Function to remove duplicate elements
void removeDuplicates(int arr[], int n)
{
int i;
set<int> s;
// Insert the array elements
// into the set
for (i = 0; i < n; i++) {
s.insert(arr[i]);
}
set<int>::iterator it;
// Print the array with duplicates removed
cout << "\nAfter removing duplicates:\n";
for (it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
cout << '\n';
}
int main()
{
int arr[] = { 1, 2, 2, 4, 3, 3, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
// Print array
cout << "\nBefore removing duplicates:\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
removeDuplicates(arr, n);
return 0;
}
OutputBefore 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 };
// Compute the sizes
int n = sizeof(arr) / sizeof(arr[0]);
// Print the array
cout << "Array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
// Sort the array in descending order
sort(arr, arr + n, greater<int>());
// Print the array
cout << "\nDescending Sorted Array:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
OutputArray: 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;
// Function to print frequency of each word
void printFrequency(string str)
{
map<string, int> M;
string word = "";
for (int i = 0; i < str.size(); i++) {
// 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];
}
// Storing the last word of the string
if (M.find(word) == M.end())
M.insert(make_pair(word, 1));
// Update the frequency
else
M[word]++;
// Traverse the map
for (auto& it : M) {
cout << it.first << " - " << it.second << endl;
}
}
int main()
{
string str = "Geeks For Geeks is for Geeks";
printFrequency(str);
return 0;
}
OutputFor - 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;
// Function to print k Maximum elements
void printMax(int arr[], int n, int k)
{
int result[n], c[n];
// Coping the array a
// into c and initialising
for (int i = 0; i < n; i++) {
c[i] = arr[i];
result[i] = 0;
}
for (int i = 0; i < k; i++) {
int maxi = INT_MIN;
int index;
for (int j = 0; j < n; j++) {
if (arr[j] > maxi) {
maxi = arr[j];
index = j;
}
}
// Assigning 1 in order
// to mark the position
// of all k maximum numbers
result[index] = 1;
arr[index] = INT_MIN;
}
// 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;
}
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;
void solve(vector<int>& arr, int n, set<vector<int> >& ans,
vector<int> v, int i)
{
// Base Condition
if (i >= n) {
ans.insert(v);
return;
}
solve(arr, n, ans, v, i + 1);
v.push_back(arr[i]);
solve(arr, n, ans, v, i + 1);
}
vector<vector<int> > AllSubsets(vector<int> arr, int n)
{
// Set of vectors to store
// required unique subsets
set<vector<int> > ans;
sort(arr.begin(), arr.end());
vector<int> v;
solve(arr, n, ans, v, 0);
// Vector of vectors to store final result
vector<vector<int> > res;
while (!ans.empty()) {
res.push_back(*ans.begin());
ans.erase(ans.begin());
}
return res;
}
// Print Function
void print(int N, vector<int>& A)
{
vector<vector<int> > result = AllSubsets(A, N);
// printing the output
for (int i = 0; i < result.size(); i++) {
cout << '(';
for (int j = 0; j < result[i].size(); j++) {
cout << result[i][j];
if (j < result[i].size() - 1)
cout << " ";
}
cout << "), ";
}
cout << "\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;
// Inserting elements in queue
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
// Copy queue
queue<int> copy_queue = q;
cout << "Queue elements :\n";
while (!copy_queue.empty()) {
cout << copy_queue.front() << " ";
copy_queue.pop();
}
return 0;
}
OutputQueue 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;
// Maximum size of stack
#define MAX 100
class Stack {
private:
int top;
// Array to store stack elements
int arr[MAX];
public:
// Constructor to initialize top as -1
Stack() { top = -1; }
// Function to push an element to the stack
void push(int x)
{
if (top == MAX - 1) {
cout << "Stack overflow" << endl;
return;
}
arr[++top] = x;
}
// Function to pop an element from the stack
int pop()
{
if (top == -1) {
cout << "Stack underflow" << endl;
return -1;
}
return arr[top--];
}
// Function to check if stack is empty
bool isEmpty() { return (top == -1); }
// Function to return the top element of the stack
int peek()
{
if (top == -1) {
cout << "Stack is empty" << endl;
return -1;
}
return arr[top];
}
};
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
cout << "Popped element: " << s.pop() << endl;
cout << "Top element: " << s.peek() << endl;
return 0;
}
OutputPopped 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;
// Maximum size of the queue
#define MAX 100
class Queue {
private:
int front, rear;
// Array to store queue elements
int arr[MAX];
public:
// Constructor to initialize front and rear as -1
Queue() { front = rear = -1; }
// Function to add an element to the queue
void enqueue(int x)
{
if (rear == MAX - 1) {
cout << "Error: Queue overflow" << endl;
return;
}
arr[++rear] = x;
if (front == -1)
front = 0;
}
// Function to remove an element from the queue
int dequeue()
{
if (front == -1) {
cout << "Queue underflow" << endl;
return -1;
}
int x = arr[front];
if (front == rear)
front = rear = -1;
else
front++;
return x;
}
// Function to check if queue is empty
bool isEmpty() { return (front == -1); }
// Function to return the front element of the queue
int peek()
{
if (front == -1) {
cout << "Queue is empty" << endl;
return -1;
}
return arr[front];
}
};
int main()
{
Queue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
cout << "Dequeued element: " << q.dequeue() << endl;
cout << "Front element: " << q.peek() << endl;
return 0;
}
OutputDequeued 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>
using namespace std;
class Stack {
queue<int> q1, q2;
public:
void push(int x)
{
// Push x first in empty q2
q2.push(x);
// Push all the remaining
// elements in q1 to q2.
while (!q1.empty()) {
q2.push(q1.front());
q1.pop();
}
// swap the names of two queues
queue<int> q = q1;
q1 = q2;
q2 = q;
}
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 size() { return q1.size(); }
};
int main()
{
Stack s;
// Inserting elements in Stack
s.push(1);
s.push(2);
s.push(3);
s.push(4);
cout << "Size: " << s.size() << endl;
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
cout << "Size: " << s.size() << endl;
return 0;
}
OutputSize: 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>
using namespace std;
// Template declared
template <typename T> class Stack {
public:
list<T> l;
int cs = 0;
// current size of the stack
// pushing an element into the stack
void push(T d)
{
cs++;
// increasing the current size of the stack
l.push_front(d);
}
// popping an element from the stack
void pop()
{
if (cs <= 0) {
// cannot pop us stack does not contain an
// elements
cout << "Stack empty" << endl;
}
else {
// decreasing the current size of the stack
cs--;
l.pop_front();
}
}
// if current size is 0 then stack is empty
bool empty() { return cs == 0; }
// getting the element present at the top of the stack
T top() { return l.front(); }
int size()
{
// getting the size of the stack
return cs;
}
// printing the elements of the stack
void print()
{
for (auto x : l) {
cout << x << endl;
}
}
};
int main()
{
// Inserting elements in stack
Stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
cout << "Size: " << s.size() << endl;
cout << "Top element:" << s.top() << endl;
s.pop();
cout << "Top element:" << s.top() << endl;
s.pop();
cout << "Top element:" << s.top() << endl;
cout << "Size:" << s.size() << endl;
return 0;
}
OutputSize: 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;
bool isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0;
int j = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (arr2[i] == arr1[j])
break;
}
if (j == m)
return 0;
}
return 1;
}
int main()
{
int arr1[] = { 1, 11, 31, 21, 30, 17 };
int arr2[] = { 11, 30, 17, 1 };
int m = sizeof(arr1) / sizeof(arr1[0]);
int n = sizeof(arr2) / sizeof(arr2[0]);
if (isSubset(arr1, arr2, m, n))
cout << "arr2 is subset of arr1 ";
else
cout << "arr2 is not a subset of arr1";
return 0;
}
Outputarr2 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;
void Rotate(int arr[], int k, int n)
{
// temp array
int temp[n];
// Keepig track of the current index
// of temp[]
int t = 0;
// Storing the n - d elements of
// array arr[] to the front of temp[]
for (int i = k; i < n; i++) {
temp[t] = arr[i];
t++;
}
// Storing the first d elements of array arr[]
// into temp
for (int i = 0; i < k; i++) {
temp[t] = arr[i];
t++;
}
// Copying the elements of temp[] in arr[]
for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
void print_array(int arr[], int n)
{
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}
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;
}
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;
void ascDecFunc(int a[], int n)
{
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n / 2; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
for (int j = n / 2; j < n - 1; j++) {
if (a[j] < a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int len = sizeof(arr) / sizeof(arr[0]);
ascDecFunc(arr, len);
return 0;
}
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;
void reverse(string str)
{
for (int i = str.length() - 1; i >= 0; i--)
cout << str[i];
}
int main(void)
{
string str = "GeeksforGeeks";
reverse(str);
return (0);
}
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;
void permute(string s, string answer)
{
if (s.length() == 0) {
cout << answer << endl;
return;
}
for (int i = 0; i < s.length(); i++) {
char ch = s[i];
string left = s.substr(0, i);
string right = s.substr(i + 1);
string result = left + right;
permute(result, answer + ch);
}
}
int main()
{
string s = "ABC";
string answer = "";
permute(s, answer);
return 0;
}
OutputABC
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;
int compare(const void* a, const void* b)
{
return (*(char*)a - *(char*)b);
}
void swap(char* a, char* b)
{
char t = *a;
*a = *b;
*b = t;
}
int findCeil(char str[], char first, int l, int h)
{
int ceilIndex = l;
for (int i = l + 1; i <= h; i++)
if (str[i] > first && str[i] < str[ceilIndex])
ceilIndex = i;
return ceilIndex;
}
void Permutations(char str[])
{
int size = strlen(str);
qsort(str, size, sizeof(str[0]), compare);
bool isFinished = false;
while (!isFinished) {
cout << str << endl;
int i;
for (i = size - 2; i >= 0; --i)
if (str[i] < str[i + 1])
break;
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;
}
OutputXYZ
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>
using namespace std;
string remove_brackets(string str)
{
string result = "";
for (char c : str) {
if (c != '(' && c != ')') {
result += c;
}
}
return result;
}
int main()
{
string str = "Geeks)(for)(geeks";
cout << "Without brackets: " << remove_brackets(str)
<< endl;
return 0;
}
88. Program to Perform Insert, Delete, and Print Operations Singly Linked List
C++
// C++ Program to perform insertion, deletion, and print
// operations in LL
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head = nullptr;
// Function to insert node in LL
void insert(int data)
{
Node* newNode = new Node();
newNode->data = data;
newNode->next = head;
head = newNode;
}
// function to delete node of LL
void deleteNode(int data)
{
Node *temp = head, *prev = nullptr;
if (temp != nullptr && temp->data == data) {
head = temp->next;
delete temp;
return;
}
while (temp != nullptr && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == nullptr)
return;
prev->next = temp->next;
delete temp;
}
// 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;
}
OutputLinked 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>
using namespace std;
struct Node {
int data;
Node* next;
Node* prev;
};
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList()
: head(NULL)
{
}
void insertAtStart(int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = head;
newNode->prev = NULL;
if (head != NULL)
head->prev = newNode;
head = newNode;
}
void deleteNode(int data)
{
Node* temp = head;
while (temp != NULL && temp->data != data)
temp = temp->next;
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);
std::cout << "Original Doubly Linked List: ";
dll.printList();
dll.deleteNode(2);
std::cout << "Doubly Linked List after deletion: ";
dll.printList();
return 0;
}
OutputOriginal 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)
{
}
void insertAtStart(int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = head;
if (head == NULL) {
head = newNode;
newNode->next = head;
}
else {
Node* temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = newNode;
head = newNode;
}
}
void deleteNode(int data)
{
Node* temp = head;
if (temp == NULL)
return;
if (temp->next == head) {
head = NULL;
delete temp;
return;
}
Node* prev = NULL;
while (temp->next != head && temp->data != data) {
prev = temp;
temp = temp->next;
}
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);
std::cout << "Original Circular Linked list ";
cll.printList();
cll.deleteNode(2);
std::cout << "Circular Linked List after deletion ";
cll.printList();
return 0;
}
OutputOriginal 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;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
};
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
/* Given a binary tree, print its nodes in inorder*/
void printInorder(struct Node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
cout << node->data << " ";
/* now recur on right child */
printInorder(node->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;
}
OutputInorder 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>
using namespace std;
void find_subset(vector<int>& A, vector<vector<int> >& ans,
vector<int>& subset, int index)
{
ans.push_back(subset);
for (int i = index; i < A.size(); i++) {
subset.push_back(A[i]);
find_subset(A, ans, subset, i + 1);
subset.pop_back();
}
return;
}
vector<vector<int> > subsets(vector<int>& A)
{
vector<int> subset;
vector<vector<int> > ans;
int index = 0;
find_subset(A, ans, subset, index);
return ans;
}
int main()
{
vector<int> array = { 1, 2, 3, 4, 5 };
vector<vector<int> > ans = subsets(array);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++)
cout << ans[i][j] << " ";
cout << endl;
}
return 0;
}
Output1
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;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
};
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
/* Given a binary tree, print its nodes in preorder*/
void printPreorder(struct Node* node)
{
if (node == NULL)
return;
/* first print data of node */
cout << node->data << " ";
/* then recur on left subtree */
printPreorder(node->left);
/* now recur on right subtree */
printPreorder(node->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 << "Preorder traversal of binary tree is \n";
printPreorder(root);
return 0;
}
OutputPreorder 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;
};
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
/* Given a binary tree, print its nodes according to the
"bottom-up" postorder traversal. */
void printPostorder(struct Node* node)
{
if (node == NULL)
return;
// first recur on left subtree
printPostorder(node->left);
// then recur on right subtree
printPostorder(node->right);
// now deal with the node
cout << node->data << " ";
}
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;
}
OutputPostorder 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;
};
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
/* Given a binary tree, print its nodes according to the
"bottom-up" postorder traversal. */
void printLevelOrder(struct Node* node)
{
if (node == NULL)
return;
queue<struct Node*> q;
while (node) {
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
cout << node->data << " ";
node = q.front();
q.pop();
}
}
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;
}
OutputLevelorder 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;
// node data type
struct Node {
Node* left;
Node* right;
int hd;
int data;
};
// utility function to create new node
Node* newNode(int key)
{
Node* node = new Node();
node->left = node->right = NULL;
node->data = key;
return node;
}
// function to print top view of a binary tree
void topView(Node* root)
{
if (root == NULL) {
return;
}
queue<Node*> q;
map<int, int> m;
int hd = 0;
root->hd = hd;
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();
}
// printing top view
for (auto i = m.begin(); i != m.end(); i++) {
cout << i->second << " ";
}
}
// 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;
}
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;
// node data type
struct Node {
Node* left;
Node* right;
int data;
int hd;
};
// utility function for new node
Node* newNode(int key)
{
Node* node = new Node();
node->data = key;
node->left = node->right = NULL;
node->hd = 0;
return node;
}
// function to print bottom view
void bottomView(Node* root)
{
if (root == NULL)
return;
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);
}
}
// printing top view
for (auto i = m.begin(); i != m.end(); ++i)
cout << i->second << " ";
}
// 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;
}
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;
};
// utility function to create a new node
Node* newNode(int key)
{
Node* node = new Node;
node->data = key;
node->left = node->right = NULL;
return node;
}
// function to print left view
void leftView(Node* root)
{
if (!root) {
return;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
for (int i = 1; i <= n; i++) {
Node* temp = q.front();
q.pop();
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()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->right = newNode(5);
leftView(root);
}
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;
// node data type
struct Node {
Node* left;
Node* right;
int data;
};
// utility function to create new node
Node* newNode(int key)
{
Node* node = new Node;
node->data = key;
node->left = node->right = NULL;
return node;
}
// function to print right view of a binary tree
void rightView(Node* root)
{
if (root == NULL) {
return;
}
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()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->right = newNode(5);
rightView(root);
}
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;
// infix to postfix conversion
// supported operators => + - * /
string infixToPostfix(string& expression)
{
// string to store postfix expression
string postfix;
// operator stack
stack<char> ope_stack;
// operator precedence map
unordered_map<char, int> pre = { { '+', 1 },
{ '-', 1 },
{ '*', 2 },
{ '/', 2 },
{ '(', 0 } };
int length = expression.length();
for (int i = 0; i < length; i++) {
char c = expression[i];
// checking operands
if ((c >= 92 && c <= 122) || (c >= 48 && c <= 57)) {
postfix.push_back(c);
}
// checking braces
else if (c == '(') {
ope_stack.push(c);
}
else if (c == ')') {
while (ope_stack.top() != '(') {
postfix.push_back(ope_stack.top());
ope_stack.pop();
}
ope_stack.pop();
}
// checking operators
else {
while (!ope_stack.empty()
&& pre.at(c) < pre.at(ope_stack.top())) {
postfix.push_back(ope_stack.top());
ope_stack.pop();
}
ope_stack.push(c);
}
}
// popping whole stack at the end
while (!ope_stack.empty()) {
postfix.push_back(ope_stack.top());
ope_stack.pop();
}
return postfix;
}
// driver code
int main()
{
string s = "a*b+(c-d)";
cout << infixToPostfix(s);
return 0;
}
Conclusion
Coding interviews can be challenging task, but they are also a great opportunity to test your skills and knowledge. By practicing with commonly ask C++ coding interview questions, you can increase your chances of success.
Remember to stay calm, communicate your thought process clearly, and don't be afraid to ask for clarification if needed. With hard work and preparation, you can ace your interview and land your dream job!
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
C++ Overview
Introduction to C++ Programming LanguageC++ is a general-purpose programming language that was developed by Bjarne Stroustrup as an enhancement of the C language to add object-oriented paradigm. It is considered as a middle-level language as it combines features of both high-level and low-level languages. It has high level language featur
3 min read
Features of C++C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including:Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopul
5 min read
History of C++The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development EnvironmentC++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using Online IDEIDE stands for an integrated development environment. IDE is a software application that provides facilities to
8 min read
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
C++ Basics
Understanding First C++ ProgramThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
C++ Basic SyntaxSyntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language.The C++ language also has its syntax for the functionalities it provides. Different statements have different
4 min read
C++ CommentsComments in C++ are meant to explain the code as well as to make it more readable. Their purpose is to provide information about code lines. When testing alternative code, they can also be used to prevent execution of some part of the code. Programmers commonly use comments to document their work.Ex
3 min read
Tokens in CIn C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
C++ KeywordsKeywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
2 min read
Difference between Keyword and Identifier in CIn C, keywords and identifiers are basically the fundamental parts of the language used. Identifiers are the names that can be given to a variable, function or other entity while keywords are the reserved words that have predefined meaning in the language.The below table illustrates the primary diff
3 min read
C++ Variables and Constants
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Constants in CIn C programming, const is a keyword used to declare a variable as constant, meaning its value cannot be changed after it is initialized. It is mainly used to protect variables from being accidentally modified, making the program safer and easier to understand. These constants can be of various type
4 min read
Scope of Variables in C++In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with.Let's take a look at an example:C++#include <iostream> using namespace std; //
7 min read
Storage Classes in C++ with ExamplesC++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
6 min read
Static Keyword in C++The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses.In C++, a static keyword can be used in the following context:Table of ContentStatic Variables in a FunctionStatic Member Variab
5 min read
C++ Data Types and Literals
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
Literals in CIn C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Derived Data Types in C++The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality.In C++, there are four different derived data types:Table of Cont
4 min read
User Defined Data Types in C++User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types:Table of ContentClassStructu
4 min read
Data Type Ranges and Their Macros in C++Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
3 min read
C++ Type ModifiersIn C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store.C++ have 4 type modifiers which are as follows:Table of Contentsigned Modifierunsigned Mod
4 min read
Type Conversion in C++Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { // Two variables of different t
4 min read
Casting Operators in C++The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).Let's take a look at an example:C++#
5 min read
C++ Operators
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
C++ Arithmetic OperatorsArithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, â+â is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary Operators in CIn C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
Bitwise Operators in CIn C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
Assignment Operators in CIn C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error.Let's take a look at an example:C#include
4 min read
C++ sizeof OperatorThe sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions.Let's take a look at an example:C++#include <iostream> using namespace std; int ma
3 min read
Scope Resolution Operator in C++In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example:C++#include <iostream> int main() { // Accessing cout from std namespace using scope // r
4 min read
C++ Input/Output
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
7 min read
C++ if StatementThe C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { int
3 min read
C++ if else StatementThe if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
3 min read
C++ if else if LadderIn C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
Switch Statement in C++In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is a simpler alternative to the long if-else-if ladder.SyntaxC++switch (expression) { case value_1: // code to be executed. break; case v
5 min read
Jump statements in C++Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.In C++, there is four jump statement:Table of Contentcontinue Statementbreak Statementreturn Statementgoto S
4 min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
for Loop in C++In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand.Let's take a look at an example:C++#include <bits/stdc++.h
6 min read
Range-Based for Loop in C++In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.Let's take
3 min read
C++ While LoopIn C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while LoopIn C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Functions
Functions in C++A Function is a reusable block of code designed to perform a specific task. It helps break large programs into smaller, logical parts. Functions make code cleaner, easier to understand, and more maintainable.Just like in other languages, C++ functions can take inputs (called parameters), execute a b
8 min read
return Statement in C++In C++, the return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was calle
4 min read
Parameter Passing Techniques in CIn C, passing values to a function means providing data to the function when it is called so that the function can use or manipulate that data. Here:Formal Parameters: Variables used in parameter list in a function declaration/definition as placeholders. Also called only parameters.Actual Parameters
3 min read
Difference Between Call by Value and Call by Reference in CFunctions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.The following table lists the differences between the call-by-value and call-by-reference methods of parameter passing.Call By Valu
4 min read
Default Arguments in C++A default argument is a value provided for a parameter in a function declaration that is automatically assigned by the compiler if no value is provided for those parameters in function call. If the value is passed for it, the default value is overwritten by the passed value.Example:C++#include <i
5 min read
Inline Functions in C++In C++, inline functions provide a way to optimize the performance of the program by reducing the overhead related to a function call. When a function is specified as inline the whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of us
6 min read
Lambda Expression in C++C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused. Therefore, they do not require a name. They are mostly used in STL algorithms as callback functions.Example:C++#include <iostream> using namespace std; i
4 min read
C++ Pointers and References
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ PointersA pointer is a special variable that holds the memory address of another variable, rather than storing a direct value itself. Pointers allow programs to access and manipulate data in memory efficiently, making them a key feature for system-level programming and dynamic memory management. When we acc
8 min read
Dangling, Void , Null and Wild Pointers in CIn C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in CPointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++Consider the following C++ program that shows problem with NULL (need of nullptr) CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Overloaded fun
3 min read
References in C++In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly.Example:C++#include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x; // printing v
5 min read
Can References Refer to Invalid Location in C++?Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?Let's first understand what Passing by Pointer and Passing by Reference in C++ mean:Passing by
5 min read
When do we pass arguments by pointer?In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read