0% found this document useful (0 votes)
17 views18 pages

Coding Questions IN C++

Uploaded by

khushi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views18 pages

Coding Questions IN C++

Uploaded by

khushi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Write a code to reverse a number

C++

//Reverse of a number
#include
using namespace std;
//main program
int main()
{
//variables initialization
int num, reverse=0, rem;
cout<<"Enter a number: ";
//user input
cin>>num;
//loop to find reverse number
do
{
rem=num%10;
reverse=reverse*10+rem;
num/=10;
}while(num!=0);
//output
cout<<"Reversed Number: "<<reverse;
return 0;
}

Write the code to find the Fibonacci series upto the


nth term.
C
C++

#include<iostream>
using namespace std;

int main()
{
int num = 15;
int a = 0, b = 1;

// Here we are printing 0th and 1st terms


cout << a << ", " << b << ", ";

int nextTerm;

// printing the rest of the terms here


for(int i = 2; i < num; i++){
nextTerm = a + b;
a = b;
b = nextTerm;

cout << nextTerm << ", ";


}

return 0;
}

Write code of Greatest Common Divisor


C
C++
//C++ Program
//GCD of Two Numbers
#include
using namespace std;
// Recursive function declaration
int findGCD(int, int);
// main program
int main()
{
int first, second;
cout<<"Enter First Number: ";
cin>>first;
cout<<"Enter second Number: ";
cin>>second;
cout<<"GCD of "<<first<<" and "<<second<<" is "<<findGCD(first,second);
return 0;
}
//body of the function
int findGCD(int first, int second)
{
// 0 is divisible by every number
if(first == 0)
{
return second;
}
if(second == 0)
{
return first;
}
// both numbers are equal
if(first == second)
{
return first;
}
// first is greater
else if(first > second)
{
return findGCD(first - second, second);
}
return findGCD(first, second - first);
}

Write code of Perfect number


C
C++

#include
using namespace std;
//main Program
int main ()
{
int div, num, sum=0;
cout << "Enter the number to check : ";
//user input
cin >> num;
//loop to find the sum of divisors
for(int i=1; i < num; i++)
{
div = num % i;
if(div == 0)
sum += i;
}
//checking for perfect number
if (sum == num)
cout<< num <<" is a perfect number.";
else
cout<< num <<" is not a perfect number.";
return 0;
}

Write code to Check if two strings are Anagram or not


C
C++
#include<iostream>
using namespace std;
int main()
{
//Initializing variables.
char str1[100],str2[100];
int first[26]={0}, second[26]={0}, c=0, flag=0;

//Accepting inputs.
cout<<"Enter First String: ";
gets(str1);
cout<<"Enter Second String: ";
gets(str2);

//Calculating frequencies of characters in first string.


while(str1[c] != '\0')
{
first[str1[c]-'a']++;
c++;
}

c=0;
//Calculating frequencies of characters in second string.
while(str2[c] != '\0')
{
second[str2[c]-'a']++;
c++;
}
//Checking if frequencies of both the strings are same or not.
for(c=0;c<26;c++)
{
if(first[c] != second[c])
flag=1;
}
//Priting result.
if(flag == 0)
{
cout<<"Strings are anagram.";
}
else
{
cout<<"Strings are not anagram.";
}
return 0;

Write code Check if the given string is Palindrome or


not
C
C++

#include
#include
using namespace std;

int main()
{
//Initializing variable.
char str[100];
int i,length=0,flag=0;

//Accepting input.
cout<<"Enter the string : "<<endl;
gets(str);
length=strlen(str);

//Initializing for loop.


for(i=0;i<length/2;i++)
{
//Checking if string is palindrome or not.
if(str[i]==str[length-i-1])
flag++;

}
//Printing result.
if(flag==i)
cout<<"String entered is palindrome";
else
cout<<"String entered is not palindrome";

return 0;
}

Write code to Calculate frequency of characters in a


string
C
C++

#include
using namespace std;

int main()
{
//Initializing variables.
char str[100];
int i;
int freq[256] = {0};

//Accepting inputs.
cout<<"Enter the string: ";
gets(str);

//Calculating frequency of each character.


for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}

//Printing frequency of each character.


for(i = 0; i < 256; i++)
{
if(freq[i] != 0)
{
cout<<"The frequency of "<<char(i)<<" is "<<freq[i]<<endl;
}
}
return 0;
}

Write code to check if two strings match where one


string contains wildcard characters
C
C++
#include

using namespace std;

int main()
{
//Initialize the variables.
string wild,str;

//Accept the inputs.


cout<<"Enter string containing wild characters: "; cin>>wild;
cout<<"Enter string to be matched: "; cin>>str;

bool TRUE=true,FALSE=false;
bool check[wild.length()+1][str.length()+1];

check[0][0]=TRUE;

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

check[0][i]=FALSE;

for(int i=1;i<=wild.length();i++)

if(wild[i-1] == '*')//Checking for wild characters.

check[i][0]=check[i-1][0];

else

check[i][0]=FALSE;

for(int i=1;i<=wild.length();i++)

for(int j=1;j<=wild.length();j++)

if(wild[i-1] == str[j-1])

check[i][j]=check[i-1][j-1];

else if(wild[i-1] == '?')//Checking for wild character '?'.

check[i][j]=check[i-1][j-1];

else if(wild[i-1] == '*')//Checking for wild character '*'.

check[i][j]=check[i-1][j]||check[i][j-1];

else
check[i][j] =FALSE;

//Printing result
if(check[wild.length()][str.length()])
cout<<"TRUE";
else
cout<<"FALSE</span.";

Write a code for bubble sort


C
C++
#include<iostream>
using namespace std;

void swap(int *var1, int *var2)


{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
//Here we will implement bubbleSort.
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
//Since, after each iteration rightmost i elements are sorted.
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
// Function to print array.
void display(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << "\t";

cout<<endl;
}
//Main function to run the program.
int main()
{
int array[] = {5, 3, 1, 9, 8, 2, 4,7};
int size = sizeof(array)/sizeof(array[0]);

cout<<"Before bubble sort: \n";


display(array, size);//Calling display function to print unsorted array.

bubbleSort(array, size);

cout<<"After bubble sort: \n";


display(array, size);//Calling display function to print sorted array.

return 0;
}

How is the merge sort algorithm implemented?


C
C++
#include<iostream>
using namespace std;

void mergeSort(int[],int,int);
void merge(int[],int,int,int);

void printArray(int arr[], int size){


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

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

int size = sizeof(array)/sizeof(array[0]);


printArray(array, size);

mergeSort(array, 0, size-1);
printArray(array, size);
}

void mergeSort(int a[], int left, int right)


{
int mid;
if(left < right)
{
// can also use mid = left + (right - left) / 2
// this can avoid data type overflow
mid = (left + right)/2;

// recursive calls to sort first half and second half subarrays


mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}

void merge(int arr[], int left, int mid, int right)


{
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

// create temp arrays to store left and right subarrays


int L[n1], R[n2];

// Copying data to temp arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// here we merge the temp arrays back into arr[l..r]


i = 0; // Starting index of L[i]
j = 0; // Starting index of R[i]
k = left; // Starting index of merged subarray

while (i < n1 && j < n2)


{
// place the smaller item at arr[k] pos
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

Write to code to check whether a given year is leap


year or not.
C
C++

#include<bits/stdc++.h>
using namespace std;

int main()
{
int year;

cout << "Enter Year:" << endl;


cin >> year;

if(year % 400 == 0)
cout << year << " is a Leap Year";

else if(year % 4 == 0 && year % 100 != 0)


cout << year << " is a Leap Year";

else
cout << year << " is not a Leap Year";

return 0;
}

Find non-repeating characters in a string


C
C++

#include <iostream>
using namespace std;
int main()
{
//Initializing variables.
char str[100]="prepinsta";
int i;
int freq[256] = {0};

//Calculating frequency of each character.


for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}
cout<<"The non repeating characters are: ";
for(i = 0; i < 256; i++)
{
if(freq[i] == 1)//Finding non repeating charcters and printing them.
{
cout<<char(i)<<" " ;
}
}
return 0;
}

Write a code to replace a substring in a string.


C
C++

//Replace a Substring in a String


#include<iostream.h>
#include<string.h>
using namespace std;
void replaceSubstring(char st[],char sub[],char new_str[])//Function to replace substring.
{
int stLen,subLen,newLen;
int i=0,j,k;
int flag=0,start,end;
stLen=strlen(st);
subLen=strlen(sub);
newLen=strlen(new_str);
for(i=0;i<stLen;i++)//Finding substring.
{
flag=0;
start=i;
for(j=0;st[i]==sub[j];j++,i++)
if(j==subLen-1)
flag=1;
end=i;
if(flag==0)
i-=j;
else
{
for(j=start;j<end;j++)
{
for(k=start;k<stLen;k++)
st[k]=st[k+1];
stLen--;
i--;
}
for(j=start;j<start+newLen;j++)//Replacing suv string with the input string
{
for(k=stLen;k>=j;k--)
st[k+1]=st[k];
st[j]=new_str[j-start];
stLen++;
i++;
}
}
}
}
//Main function.
int main()
{
char st[100] = "prepinsta",sub[100] = "insta",new_str[100]="ster ";

replaceSubstring(st,sub,new_str); //Calling created function.


//Printing result using called function.
cout<<"The string after replacing substring: "<<st<<endl;
return 0;
}

Write a code for Heap sort.


C
C++
#include <iostream>

using namespace std;

void heapify(int arr[], int n, int i)


{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;

//If left child is larger than root


if (l < n && arr[l] > arr[largest])
largest = l;

//If right child largest


if (r < n && arr[r] > arr[largest])
largest = r;

//If root is nor largest


if (largest != i)
{
swap(arr[i], arr[largest]);

//Recursively heapifying the sub-tree


heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n)


{

for (int i = n / 2 - 1; i >= 0; i--)


heapify(arr, n, i);

//One by one extract an element from heap


for (int i=n-1; i>=0; i--)
{
//Moving current root to end
swap(arr[0], arr[i]);

//Calling max heapify on the reduced heap


heapify(arr, i, 0);
}
}

//Function to print array


void display(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << "\t";
}
cout << "\n";
}

int main()
{
int arr[] = {1, 14, 3, 7, 0};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Unsorted array \n";
display(arr, n);

heapSort(arr, n);

cout << "Sorted array \n";


display(arr, n);
}
Write a code to replace each element in an array by its
rank in the array
C
C++

#include<bits/stdc++.h>
using namespace std;

int main(){
int arr[] = { 100, 2, 70, 12 , 90};
int n = sizeof(arr) / sizeof(arr[0]);

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

//sort the copied array


sort(temp, temp+n);

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

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


if(temp[j]==arr[i])
{
arr[i] = j+1;
break;
}
}
}

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


cout<<arr[i]<<" ";
}

Write a code to find circular rotation of an array by K


positions.
C
C++

#include <bits/stdc++.h>
using namespace std;

int main()
{

int n; // variable to store the size of the array


int k; // variable to store the position for rotation

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


cin >> n;

cout << "\nEnter the position for rotation : ";


cin >> k;

std::vector A(n); // declaring a vector of size n

cout << "\nEnter the elements of the array : ";

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


cin >> A[i];

k = (n - k) % n; // set k to the index which comes first


reverse(A.begin(), A.begin() + k); //reverse the array from 0 to k position
reverse(A.begin() + k, A.end()); //reverse the array from k to n-1 position
reverse(A.begin(), A.end()); //reverse the array from 0 to n-1 position

cout << "\nArray after rotation: ";

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


cout << A[i] << " ";

return 0;

Write a code to find non-repeating elements in an


array.
C
C++

#include <bits/stdc++.h>
using namespace std;

// Main function to run the program


int main()
{
int arr[] = {10, 30, 10, 20, 40, 20, 50, 10};
int n = sizeof(arr)/sizeof(arr[0]);

int visited[n], count_dis=0;

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

if(visited[i]!=1){
int count = 1;
for(int j=i+1; j<n; j++){
if(arr[i]==arr[j]){
count++;
visited[j]=1;
}
}
if(count==1)
cout<<arr[i]<<" ";
}
}

return 0;
}

Write a code to check for the longest palindrome in an


array.
C
C++

#include<bits/stdc++.h>
using namespace std;

int ispalindrome(int n){


int rev=0, temp = n;

while(temp>0){
int rem = temp%10;
rev = rev*10 + rem;
temp /= 10;
}

if(n==rev)
return 1;

return 0;
}

int main(){
int arr[] = {1, 121, 55551, 545545, 10111, 90};
int n = sizeof(arr)/sizeof(arr[0]);
int res = INT_MIN;

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


if(ispalindrome(arr[i]) && res<arr[i])
res = arr[i];
}

if(res==INT_MIN)
res = -1;

cout<<res;
}

Write a code to find the factorial of a number.


C
C++

#include<iostream>
using namespace std;
int main ()
{
int num = 6, fact = 1;

// Factorial of negative number doesn't exist


// Read more here - https://www.quora.com/Is-the-factorial-of-a-negative-number-possible
if(num < 0)
cout << "Not Possible";
else
{
for(int i = 1; i <= num; i++)
fact = fact * i;
}

cout << "Fact " << num << ": " << fact;
}
// Time complexity: O(N)
// Space complexity: O(1)

Write the code to for Armstrong number


C
C++

#include<iostream>
#include<math.h>
using namespace std;

// Armstrong number is any number following the given rule


// abcd... = a^n + b^n + c^n + d^n + ...
// Where n is the order(length/digits in number)
// Example = 153 (order/length = 3)
// 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

// Example = 1634 (order/length = 4)


// 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

// number of digits in a number is order


int order(int x)
{
int len = 0;
while (x)
{
len++;
x = x/10;
}
return len;
}

bool armstrong(int num, int len){

int sum = 0, temp, digit;


temp = num;

// loop to extract digit, find power & add to sum


while(temp != 0)
{
// extract digit
digit = temp % 10;

// add power to sum


sum = sum + pow(digit,len);
temp /= 10;
};

return num == sum;


}

// Driver Code
int main ()
{
//variables initialization
int num = 407, len;

// function to get order(length)


len = order(num);

// check if Armstrong
if (armstrong(num, len))
cout << num << " is armstrong";
else
cout << num << " is not armstrong";

return 0;
}

Write a program to find the sum of Natural Numbers


using Recursion.
C
C++

#include<bits/stdc++.h>
using namespace std;

int getSum(int n)
{
if(n==0)
return n;
return n + getSum(n-1);
}

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

int sum = getSum(n);

cout << sum;

return 0;
}

Write a program to add Two Matrices using Multi-


dimensional Array.
C
#include
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}

Write a Program to Find the Sum of Natural Numbers


using Recursion.
C
C++

#include<bits/stdc++.h>
using namespace std;

int getSum(int n)
{
if(n==0)
return n;

return n + getSum(n-1);
}

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

int sum = getSum(n);

cout << sum;

return 0;
}

Write code to check a String is palindrome or not?


C
C++

#include

#include

using namespace std;

int main()

char str1[20], str2[20];

int i, j, len = 0, flag = 0;

cout << "Enter the string : "; gets(str1); len = strlen(str1) - 1; for (i = len, j = 0; i >= 0 ; i--, j++)

str2[j] = str1[i];

if (strcmp(str1, str2))

flag = 1;

if (flag == 1)

cout << str1 << " is not a palindrome";

else

cout << str1 << " is a palindrome";

return 0;

Write a program for Binary to Decimal to conversion


C
C++

//C++ Program
//Convert binary to decimal
#include
#include using namespace std;
//function to convert binary to decimal
int convert(long n)
{
int i = 0,decimal= 0;
//converting binary to decimal
while (n!=0)
{
int rem = n%10;
n /= 10;
int res = rem * pow(2,i);
decimal += res;
i++;
}
return decimal;
}
//main program
int main()
{
long binary;
cout << "Enter binary number: ";
cin >> binary;
cout << binary << " in binary = " << convert(binary) << " in decimal";
return 0;
}

Write a program to check whether a character is a


vowel or consonant
C
C++

//C++ Program to check whether alphabet is vowel or consonant


#include <iostream>
using namespace std;
//main function
int main()
{
char c;
cout<<"Enter an alphabet: ";
cin>>c;
//checking for vowels
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
{
cout<<c<<" is a vowel"; //condition true input is vowel
}
else
{
cout<<c<<" is a consonant"; //condition false input is consonant
}
return 0;
}

Write a code to find an Automorphic number


C
C++
//C++ Program
//Automorphic number or not
#include<iostream>
using namespace std;
//main program
int main()
{
int num,flag=0;
cout<<"Enter a positive number to check: ";
//user input
cin>>num;
int sq= num*num;
int store=num;
//check for automorphic number
while(num>0)
{
if(num%10!=sq%10)
{
flag=1;
break;
}
num=num/10;
sq=sq/10;
}
if(flag==1)
cout<<store<<" is not an Automorphic number.";
else
cout<<store<<" is an Automorphic number.";
return 0;
}

Write a code to find Find the ASCII value of a


character
C
C++

//C++ program to calcualte ASCII value of Character


#include<iostream>
using namespace std;

//main program
int main()
{
char val;
cout<<"Enter a character: ";
cin>>val;

//printing the ASCII value of input


//through typecasting

cout<<"The ASCII value of "<<val<<" is "<<(int)val;


return 0;
}

Write a code to Remove all characters from string


except alphabets
C
C++

#include <iostream>
using namespace std;
int main()
{
//Initializing variable.
char str[100];
int i, j;

//Accepting input.
cout<<"Enter a string : ";
gets(str);

//Iterating each character and removing non alphabetical characters.


for(i = 0; str[i] != '\0'; ++i)
{
while (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') )
{
for(j = i; str[j] != '\0'; ++j)
{
str[j] = str[j+1];
}
str[j] = '\0';
}
}
//Printing output.
cout<<"After removing non alphabetical characters the string is :";
puts(str);
return 0;
}
Write a code to find Fibonacci Series using Recursion
C
C++

//Fibonacci Series using Recursion


#include<bits/stdc++.h>
using namespace std;

int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n-1) + fibo(n-2);
}

int main ()
{
int n = 9;
cout << fibo(n);
getchar();
return 0;
}

You might also like