# Top 15 C++ Programs for Interview with Explanations

Are you preparing for a C++ programming interview? If yes, you are on the right blog.

Here we offer a comprehensive collection of the most asked C++ programs in interviews with answers, designed to help you ace your programming interview. From basic syntax to advanced algorithms, we have got you covered.

Brush up on your C++ skills and impress your interviewer with your knowledge and confidence. With our blog, you will be fully prepared to tackle any C++ programming interview question thrown your way.

## Top C++ Programs for Interview with Explanations

Prepare these C++ programs and take the first step toward landing your dream job!

### 1. C++ program to print hello world without using namespace?

``````#include <iostream>
int main() {
std::cout << "Hello World" << std::endl;
return 0;
}``````
``````Output:
Hello World``````

Explanation:

Here the iostream is the input output stream library in c++ std::cout is used to print anything in c++ and std::endl is used to go the newline.

### 2. C++ code for Fibonacci series?

``````#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i) {
if(i == 1) {
cout << t1 << " ";
continue;
}
if(i == 2) {
cout << t2 << " ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;

cout << nextTerm << " ";
}
return 0;
}``````
``````Input:
Enter the number of terms: 4

Output:
Fibonacci Series: 0 1 1 2``````

Explanation:

The code implements the Fibonacci sequence, which is a series of numbers in which each number is the sum of the two preceding ones. The first two terms of the series are 0 and 1.

For the rest of the terms, the next term is calculated by adding t1 and t2, which are then assigned to t2 and nextTerm respectively. The nextTerm value is then printed.

### 3. C++ program to check for prime numbers?

``````#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
if (isPrime(n))
cout << n << " is a prime number." << endl;
else
cout << n << " is not a prime number." << endl;
return 0;
}``````
``````Input:
Enter a positive integer: 5

Output:
5 is a prime number.``````

Explanation:

The isPrime function takes an integer n as input and returns true if n is a prime number, or false otherwise. Within the isPrime function, an if statement is used to check if n is less than or equal to 1, in which case false is returned because 1 is not considered a prime number.

A for loop is then used to check for the presence of any factors of n other than 1 and itself. If a factor is found (that is, if n % i == 0), false is returned. If no factors are found, true is returned, indicating that n is a prime number.

### 4. C++ program to check for factorial of a number?

``````#include <iostream>
using namespace std;
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << n << "! = " << factorial(n) << endl;
return 0;
}``````
``````Input:
Enter a positive integer: 4

Output:
4! = 24``````

Explanation:

The factorial function takes an integer n as input and returns the factorial of n.Within the factorial function, a variable result is declared and initialized to 1. This variable will be used to store the result of the calculation. A for loop is then used to calculate the factorial of n.

The loop starts with i equal to 1 and continues as long as i is less than or equal to n. On each iteration, result is multiplied by i. The final value of result is returned as the result of the factorial function.

### 5. Write a c++ program to find the largest among three numbers in C++?

``````#include <iostream>
using namespace std;
int main() {
int a, b, c;
cout << "Enter three integers: ";
cin >> a >> b >> c;
int largest = a;
if (b > largest) largest = b;
if (c > largest) largest = c;
cout << "The largest of " << a << ", " << b << ", and " << c << " is " << largest << endl;
return 0;
}``````
``````Input:
Enter three integers: 1
4
5

Output:
The largest of 1, 4, and 5 is 5``````

Explanation:

Here we initialize three variables a, b, c we fix one as the largest and we compare with other two and replace if one is larger than the other and we return the largest among the three numbers.

### 6. C++ program to reverse a string?

``````#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
cout << "The reversed string: ";
for (int i = str.length() - 1; i >= 0; i--) {
cout << str[i];
}
cout << endl;
return 0;
}``````
``````Input:
Enter a string: AVICHAL

Output:
The reversed string: LAHCIVA``````

Explanation:

What we do is declare a string str and then we take the string as input from the user after that we run a loop in reverse on the string till it reaches the first position hence giving the string as output in reverse.

### 7. C++ program to find the area and perimeter of a rectangle?

``````#include <iostream>
using namespace std;
int main() {
int length, width;
cout << "Enter the length and width of a rectangle: ";
cin >> length >> width;
int area = length * width;
int perimeter = 2 * (length + width);
cout << "The area of the rectangle is " << area << " and its perimeter is " << perimeter << endl;
return 0;
}``````
``````Input:
Enter the length and width of a rectangle: 4
5

Output:
The area of the rectangle is 20 and its perimeter is 18``````

Explanation:

We input the length and width from the user we give area and perimeter using the simple math formulae as you can see in the code itself.

### 8. C++ program to check if a year is a leap year or not?

``````#include <iostream>
using namespace std;
bool isLeapYear(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return true;
else
return false;
}

int main() {
int year;
cout << "Enter a year: ";
cin >> year;
if (isLeapYear(year))
cout << year << " is a leap year." << endl;
else
cout << year << " is not a leap year." << endl;
return 0;
}``````
``````Input:
Enter a year: 2012

Output:
2012 is a leap year.``````

Explanation:

The function bool isleapyear checks if a year is leap year or not if a year provided to this function is a leap year it returns true else it returns false. If the year is a multiple of 400 it is a leap year or if it is divisible by 4 but not 100 it is a leap year.

### 9. C++ program to get a sum of digits of a number?

``````#include <iostream>
using namespace std;
int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "The sum of digits of " << n << " is " << sumOfDigits(n) << endl;
return 0;
}``````
``````Input:
Enter a positive integer: 34

Output:
The sum of digits of 34 is 7``````

Explanation:

num is the input number and sum is the sum of its digits. The code uses a while loop to iteratively extract the last digit of the number and add it to the sum. In each iteration, the last digit is extracted by taking the modulus of the number with 10. This gives the last digit of the number.

The last digit is then added to the sum. The number is then updated by dividing it by 10. This removes the last digit from the number. The loop continues until the number becomes 0. Finally, the sum of the digits is printed.

### 10. C++ code to check palindrome with explanation?

``````#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string str) {
int n = str.length();
for (int i = 0; i < n / 2; i++) {
if (str[i] != str[n - i - 1]) {
return false;
}
}
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isPalindrome(str)) {
cout << "The string is a palindrome" << endl;
} else {
cout << "The string is not a palindrome" << endl;
}
return 0;
}``````
``````Input:
Enter a string: qwerty

Output:
The string is not a palindrome``````

Explanation:

The isPalindrome function takes a string as input and returns a bool value indicating if the string is a palindrome or not. The length of the string is stored in n. The function uses a for loop to compare the characters at the beginning and end of the string.

If the characters are not equal, the function returns false. If all the characters are equal, the function returns true. The main function takes input from the user, calls the isPalindrome function, and prints the result.

### 11. C++ code to check for Armstrong number ?

``````#include <iostream>
#include <cmath>
using namespace std;
bool isArmstrong(int num) {
int originalNum, rem, n = 0, result = 0;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0) {
rem = originalNum % 10;
result += pow(rem, n);
originalNum /= 10;
}
return (result == num);
}

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
if (isArmstrong(num)) {
cout << num << " is an Armstrong number" << endl;
} else {
cout << num << " is not an Armstrong number" << endl;
}
return 0;
}``````
``````Input:
Enter a positive integer: 555

Output
555 is not an Armstrong number``````

Explanation:

The isArmstrong function takes an integer as input and returns a bool value indicating if the number is an Armstrong number or not. The n variable stores the number of digits in the given number. The function uses a while loop to calculate the number of digits.

Another while loop is used to calculate the sum of the cubes of the digits. In each iteration, the last digit is extracted by taking the modulus of the number with 10. The extracted digit is raised to the power of n and added to the result. The number is then updated by dividing it by 10.

This removes the last digit from the number. The loop continues until the number becomes 0. The function returns true if the sum of the cubes of the digits is equal to the original number, otherwise, it returns false.

### 12. C++ code for quicksort?

``````#include <iostream>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quicksort(arr, low, pivotIndex - 1);
quicksort(arr, pivotIndex + 1, high);
}
}
void sort(int arr[], int n) {
quicksort(arr, 0, n - 1);
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr);
sort(arr, n);
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}``````
``````Output:
Sorted array:
1 5 7 8 9 10``````

Explanation:

The partition function is used to partition the elements around a pivot. It selects the last element as the pivot and rearranges the elements such that all elements less than or equal to the pivot are to the left of it and all elements greater than the pivot are to the right of it.

The quicksort function is a recursive function that sorts the elements in the array. If the low index is less than the high index, it calls the partition function to partition the elements around a pivot.

It then sorts the elements to the left of the pivot and the elements to the right of the pivot using two separate calls to quicksort. The sort function is a wrapper function that calls quicksort to sort the entire array.

### 13. C++ program for pattern printing?

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

int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}``````
``````Output:
*
**
***
****
*****``````

Explanation:

The outer for loop iterates 5 times, representing the number of rows in the pattern. The inner for loop iterates i times, where i is the current iteration of the outer loop. The inner loop prints a * character for each iteration, creating a right-angled triangle pattern.

The endl statement is used to insert a newline character after each row, allowing the pattern to be displayed correctly on the console.

### 14. C++ program for linear search?

``````#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}

int main() {
int arr[] = {1, 10, 30, 15};
int n = sizeof(arr) / sizeof(arr);
int key = 30;
int result = linearSearch(arr, n, key);
if (result == -1) {
} else {
cout << "Element found at index " << result << endl;
}
return 0;
}``````
``````Output:
Element found at index 2``````

Explanation:

The linearSearch function takes in an array, the number of elements in the array, and the key to be searched as arguments. The function performs a linear search by iterating through the array, starting from the first element. If an element matches the key, the function returns its index. If the key is not found in the array, the function returns -1.

### 15. C++ program for binary search?

``````#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int key) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}

int main() {
int arr[] = {1, 10, 30, 15};
int n = sizeof(arr) / sizeof(arr);
int key = 30;
int result = binarySearch(arr, n, key);
if (result == -1) {
} else {
cout << "Element found at index " << result << endl;
}
return 0;
}``````
``````Output:
Element found at index 2``````

Explanation:

The binarySearch function takes an array, the lower and upper bounds of the search, and the key value as input. Inside the function, a while loop is used to keep searching until the low value becomes greater than the high value, meaning that the key has not been found. Inside the loop, the mid value is calculated as the average of the low and high values.

This value is used to check if the key is found or not. If the mid value is equal to the key, the function returns the mid value as the index of the key. If the mid value is less than the key, the low value is updated to be one more than the mid value, and the search continues on the right side of the array.

If the mid value is greater than the key, the high value is updated to be one less than the mid value, and the search continues on the left side of the array. If the while loop ends and the key is not found, the function returns -1 to indicate that the key was not found.

In the main function, the binary search is called on an array of values, with the key value being 6. The result is then checked, and if the key was found, the index is printed. If the key was not found, a message indicating this is printed.