











Most Asked Coding Questions In Placements
Top Coding Questions asked in Placements
Coding Questions are important in both written as well as Interview rounds. Questions provided on this page will help you in preparing for the coding rounds. Below you will find the most important codes in languages like C, C++, Java and Python.
Page Highlights
- About Coding Questions
- Introduction to Programming
- Most Asked Coding Questions


- About Coding Questions
- Introduction to Programming
- Most Asked Coding Questions
- Write a code to reverse a number
- Write the code to find the Fibonacci series upto the nth term.
- Write the code of Greatest Common Divisor
- Write a code for the Perfect number
- Write a code to check if two Strings are Anagram or not
- Write a code to check if the given string is a palindrome or not
- Write a code to calculate the frequency of characters in a string
- Write a code to check if two strings match, where one string contains wildcard characters.
- Write a code for bubble sort
- How is the merge sort algorithm implemented?
- Write to code to check whether a given year is leap year or not.
- Find non-repeating characters in a string
- Write a code to replace a substring in a string.
- Write a code for Heap sort.
- Write a code to replace each element in an array by its rank in the array
- Write a code to find circular rotation of an array by K positions.
- Write a code to find non repeating elements in an array.
- Write a code to check for the longest palindrome.
- Write a code to find the factorial of a number.
- Write the code to for Armstrong number
About Coding Questions
Coding Questions are very important, in both online assessments and technical interviews. Depending on the profile interviewers ask candidates conceptual questions about a program or can ask the candidate to write the whole code for any given question.
Introduction to Programming
There are primarily four programming languages on which interviewers can ask questions. These are:-
- C
- C++
- Java
- Python
Other than coding languages, the placement process also requires one to learn about DBMS and DSA.
Most Asked Coding Questions
Below we have given the most commonly asked coding questions in placement and interviews.
Top 20 Coding Interview Questions
Write a code to reverse a number
#include int main() { //Initialization of variables where rev='reverse=0' int number, rev = 0,store, left; //input a numbers for user printf("Enter the number\n"); scanf("%d", &number); store= number; //use this loop for check true condition while (number > 0) { //left is for remider are left left= number%10; //for reverse of no. rev = rev * 10 + left; //number /= 10; number=number/10; } //To show the user value printf("Given number = %d\n",store); //after reverse show numbers printf("Its reverse is = %d\n", rev); return 0; }
//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; }
import java.util.Scanner;
public class reverse_of_number
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
System.out.print("Reverse of "+number+" is ");
int reverse = 0;
String s = "";
while(number != 0)
{
int pick_last = number % 10;
//use function to convert pick_last from integer to string
s = s + Integer.toString(pick_last);
number = number / 10;
}
//display the reversed number
System.out.print(s);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}
num = int(input("Enter the Number:")) temp = num reverse = 0 while num > 0: remainder = num % 10 reverse = (reverse * 10) + remainder num = num // 10 print("The Given number is {} and Reverse is {}".format(temp, reverse))
Write the code to find the Fibonacci series upto the nth term.
#include<stdio.h> int main() { int n = 10; int a = 0, b = 1; // printing the 0th and 1st term printf("%d, %d",a,b); int nextTerm; // printing the rest of the terms here for(int i = 2; i < n; i++){ nextTerm = a + b; a = b; b = nextTerm; printf("%d, ",nextTerm); } return 0; }
#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; }
public class Main { public static void main (String[]args) { int num = 15; int a = 0, b = 1; // Here we are printing 0th and 1st terms System.out.print (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; System.out.print (nextTerm + " , "); } } }
num = int(input("Enter the Number:")) n1, n2 = 0, 1 print("Fibonacci Series:", n1, n2, end=" ") for i in range(2, num): n3 = n1 + n2 n1 = n2 n2 = n3 print(n3, end=" ") print()
Write code of Greatest Common Divisor
// The code used a recursive function to return gcd of p and q int gcd(int p, int q) { // checking divisibility by 0 if (p == 0) return q; if (q == 0) return p; // base case if (p == q) return p; // p is greater if (p > q) return gcd(p-q, q); else return gcd(p, q-p); } // Driver program to test above function int main() { int p = 98, q = 56; printf("GCD of %d and %d is %d ", p, q, gcd(p, q)); return 0; }
//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); }
import java.util.Scanner; public class gcd_or_hcf { public static void main(String[] args) { //scanner class declaration Scanner sc = new Scanner(System.in); //input from the user System.out.print("Enter the first number : "); int num1 = sc.nextInt(); //input from the user System.out.print("Enter the second number : "); int num2 = sc.nextInt(); int n = 1; System.out.print("HCF of "+num1+" and "+num2+" is "); if( num1 != num2) { while(n != 0) { //storing remainder n = num1 % num2; if(n != 0) { num1 = num2; num2 = n; } } //result System.out.println(num2); } else System.out.println("Wrong Input"); //closing scanner class(not compulsory, but good practice) sc.close(); } }
num1 = int(input("Enter First Number:")) num2 = int(input("Enter Second Number:")) def gcdFunction(num1, num2): if num1 > num2: small = num2 else: small = num1 for i in range(1, small+1): if (num1 % i == 0) and (num2 % i == 0): gcd = i print("GCD of two Number: {}".format(gcd)) gcdFunction(num1, num2)
Write code of Perfect number
#include
int main()
{
// Initialization of variables
int number,i=1,total=0;
// To take user input
printf("Enter a number: ");
scanf("%d",&number);
while(i<number)
{
if(number%i==0)
{
total=total+i;
i++;
}
}
//to condition is true
if(total==number)
//display
printf("%d is a perfect number",number);
//to condition is false
else
//display
printf("%d is not a perfect number",number);
return 0;
}
#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; }
import java.util.Scanner; public class perfect_number_or_not { public static void main(String[] args) { //scanner class declaration Scanner sc = new Scanner(System.in); //input from user System.out.print("Enter a number : "); int number = sc.nextInt(); //declare a variable to store sum of factors int sum = 0; for(int i = 1 ; i < number ; i++) { if(number % i == 0) sum = sum + i; } //comparing whether the sum is equal to the given number or not if(sum == number) System.out.println("Perfect Number"); else System.out.println("Not an Perfect Number"); //closing scanner class(not compulsory, but good practice) sc.close(); } }
n = int(input(“Enter any number: “)) sump= 0 for i in range(1, n): if(n % i == 0): sump= sump + i if (sump == n): print(“The number is a Perfect number”) else: print(“The number is not a Perfect number”)
Write code to Check if two strings are Anagram or not
#include int main() { //Initializing variables. char str[100]; int i; int freq[256] = {0}; //Accepting inputs. printf("Enter the string: "); gets(str); //Calculating frequency of each character. for(i = 0; str[i] != '\0'; i++) { freq[str[i]]++; } printf("The non repeating characters are: "); for(i = 0; i < 256; i++) { if(freq[i] == 1)//Finding uniques charcters and printing them. { printf(" %c ", i); } } return 0; }
#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; }
import java.util.Arrays; import java.util.Scanner; public class CheckIfTwoStringsAreAnagramAreNot { static boolean isAnagram(String str1 , String str2) { String s1 = str1.replaceAll("[\\s]", ""); String s2 = str2.replaceAll("[\\s]", ""); boolean status=true; if(s1.length()!=s2.length()) status = false; else { char[] a1 = s1.toLowerCase().toCharArray(); char[] a2 = s2.toLowerCase().toCharArray(); Arrays.sort(a1); Arrays.sort(a2); status = Arrays.equals(a1, a2); } return status; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter two String :"); String s1 = sc.next(); String s2 = sc.next(); boolean status = isAnagram(s1,s2); if(status) System.out.println(s1+" and "+s2+" are Anagram"); else System.out.println(s1+" and "+s2+" are not Anagram"); } }
#take user input String1 = input(‘Enter the 1st string :’) String2 = input(‘Enter the 2nd string :’) #check if length matches if len(String1) != len(String2): #if False print(‘Strings are not anagram’) else: #sorted function sort string by characters String1 = sorted(String1) String2 = sorted(String2) #check if now strings matches if String1 == String2: #if True print(‘Strings are anagram’) else: print(‘Strings are not anagram’)
Write code Check if the given string is Palindrome or not
#include #include int main() { //Initializing variable. char str[100]; int i,length=0,flag=0; //Accepting input. printf("Enter the string : "); 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) printf("String entered is palindrome"); else printf("String entered is not palindrome"); return 0; }
#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; }
import java.util.Scanner; public class StringIsAPalindromeOrNot { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("Enter string"); String s = sc.next(); String rev = ""; for (int i = s.length()-1; i >=0 ; i--) rev=rev+s.charAt(i); if(s.equals(rev)) System.out.println("String is palindrome"); else System.out.println("String is not palindrome"); } }
#take user input String1 = input('Enter the String :') #initialize string and save reverse of 1st string String2 = String1[::-1] #check if both matches if String1 == String2: print('String is palindromic') else: print('Strings is not palindromic')
Write code to Calculate frequency of characters in a string
#include int main() { //Initializing variables. char str[100]; int i; int freq[256] = {0}; //Accepting inputs. printf("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) { printf("The frequency of %c is %d\n", i, freq[i]); } } return 0; }
#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; }
import java.util.Scanner; public class FrequencyOfCharactersInAString { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.print("Enter String : "); String str = sc.nextLine(); int[] freq = new int[str.length()]; int i, j; //Converts given string into character array char string[] = str.toCharArray(); for(i = 0; i <str.length(); i++) { freq[i] = 1; for(j = i+1; j <str.length(); j++) { if(string[i] == string[j]) { freq[i]++; //Set string[j] to 0 to avoid printing visited character string[j] = '0'; } } } //Displays the each character and their corresponding frequency System.out.println("Characters and their corresponding frequencies"); for(i = 0; i <freq.length; i++) { if(string[i] != ' ' && string[i] != '0') System.out.println(string[i] + "-" + freq[i]); } } }
#take user input String = input('Enter the string :') #take character input Character = input('Enter character :') #initiaalize int variable to store frequency frequency = 0 #use count function to count frequency of character frequency = String.count(Character) #count function is case sencetive #so it print frequency of Character according to given Character print(str(frequency) + ' is the frequency of given character')
Write code to check if two strings match where one string contains wildcard characters
#include #include bool check(char *str1, char * str2) ;// declaration of the check() function int main() { char str1[100],str2[100]; printf("Enter first string with wild characters : "); gets(str1); printf("Enter second string without wild characters : "); gets(str2); test(str1,str2); return 0; } bool check(char *str1, char * str2) { // checking end of both the strings if (*str1 == '\0' && *str2 == '\0') return true; // comparing the characters of both the strings and wild characters(*) if (*str1 == '*' && *(str1+1) != '\0' && *str2 == '\0') return false; // checking wild characters(?) if (*str1 == '?' || *str1 == *str2) return check(str1+1, str2+1); if (*str1 == '*') return check(str1+1, str2) || check(str1, str2+1); return false; } // test() function for running test cases void test(char *str1, char *str2) { check(str1, str2)? puts(" Yes "): puts(" No "); }
#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."; }
def solve(a,b): n,m=len(a),len(b) if n==0 and m==0: return True if n > 1 and a[0] == '*' and m == 0: return False if (n > 1 and a[0] == '?') or (n != 0 and m !=0 and a[0] == b[0]): return solve(a[1:],b[1:]); if n !=0 and a[0] == '*': return solve(a[1:],b) or solve(a,b[1:]) return False str1="Prepins*a"
str2="Prepinsta"
print("First string with wild characters :" , str1)
print("Second string without wild characters ::" , str2)
print(solve(str1,str2))
Write a code for bubble sort
#include<stdio.h> /* Function to print array */ void display(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } // 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]); printf("Before bubble sort: \n"); display(array, size); int i, j, temp; for (i = 0; i < size-1; i++){ // Since, after each iteration righmost i elements are sorted for (j = 0; j < size-i-1; j++) if (array[j] > array[j+1]) { temp = array[j]; // swap the element array[j] = array[j+1]; array[j+1] = temp; } } printf("After bubble sort: \n"); display(array, size); return 0; }
#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; }
// Time Complexity : O(N^2) // Space Complexity : O(1) class Main { static void bubbleSort(int a[]) { int len = a.length; // calculating the length of array for (int i = 0; i < len-1; i++) for (int j = 0; j < len-i-1; j++) if (a[j] > a[j+1]) //comparing the pair of elements { // swapping a[j+1] and a[i] int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } /* Prints the array */ static void printArray(int a[]) { int len = a.length; for (int i = 0; i < len; i++) System.out.print(a[i] + " "); //printing the sorted array System.out.println(); } // Main method to test above public static void main(String args[]) { int arr[] = {64, 34, 25, 12, 22, 11, 90}; bubbleSort(arr);//calling the bubbleSort function System.out.println("Sorted array"); printArray(arr); //calling the printArray function } }
How is the merge sort algorithm implemented?
#include<stdio.h> void mergeSort(int[],int,int); void merge(int[],int,int,int); void display(int arr[], int size){ int i; for(i = 0; i < size; i++){ printf("%d ",arr[i]); } printf("\n"); } void main() { int a[10]= {11, 9, 6, 19, 33, 64, 15, 75, 67, 88}; int i; int size = sizeof(a)/sizeof(a[0]); display(a, size); mergeSort(a, 0, size-1); display(a, 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++; } }
#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++; } }
//Java Program for Merge Sort class Main { // this function display the array public static void display(int[] arr, int size) { for(int i = 0; i < size; i++) { System.out.print(arr[i] + " "); } System.out.println(); } // main function of the program public static void main(String[] args) { int[] a = {12, 8, 4, 14, 36, 64, 15, 72, 67, 84}; int size = a.length; display(a, size); mergeSort(a, 0, size - 1); display(a, size); } // this function apply merging and sorting in the array static 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 sub-arrays mergeSort(a, left, mid); mergeSort(a, mid + 1, right); merge(a, left, mid, right); } } // after sorting this function merge the array static 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 sub-arrays int L[] = new int[n1]; int R[] = new int[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 sub-array 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.
#include <stdio.h> int main () { int year; scanf("%d",&year); if(year % 400 == 0) printf("%d is a Leap Year",year); else if(year % 4 == 0 && year % 100 != 0) printf("%d is a Leap Year",year); else printf("%d is not a Leap Year",year); return 0; }
#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; }
// Leap year program in Java // If the year satisfies either of the conditions, it's considered a leap year - // 1. The year must be divisible by 400. // 2. The year must be divisible by 4 but not 100.public class Main { public static void main (String[]args) { int year = 2020; if (year % 400 == 0) System.out.println (year + " is a Leap Year"); else if (year % 4 == 0 && year % 100 != 0) System.out.println (year + " is a Leap Year"); else System.out.println (year + " is not a Leap Year"); } }
year = int(input("Enter Year:")) if (year%400 == 0) or (year%4==0 and year%100!=0): print("Leap Year") else: print("Not a Leap Year")
Find non-repeating characters in a string
#include<stdio.h> 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]]++; } printf("The non repeating characters are: "); for(i = 0; i < 256; i++) { if(freq[i] == 1)//Finding uniques charcters and printing them. { printf(" %c ", i); } } return 0; }
#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; }
import java.util.*; class Solution { public static void main (String[]args) { Scanner sc = new Scanner (System.in); System.out.println ("Enter the string"); String str = sc.next (); //Taking input as a string from the user int freq[] = new int[256]; //Calculating frequency of each character for (int i = 0; i < str.length (); i++) freq[str.charAt (i)]++; System.out.println ("The non repeating characters are : "); for (int i = 0; i < 256; i++) if (freq[i] == 1) //finding the character whose frequency is 1 System.out.print ((char) i + " "); } }
#take user input String = "prepinsta" for i in String: #initialize a count variable count = 0 for j in String: #check for repeated characters if i == j: count+=1 #if character is found more than 1 time #brerak the loop if count > 1: break #print for nonrepeating characters if count == 1: print(i,end = " ")
Write a code to replace a substring in a string.
#include<stdio.h> #include<string.h> int main() { char str[256] = "prepinsta", substr[128] = "insta", replace[128] = "ster ", output[256]; int i = 0, j = 0, flag = 0, start = 0; str[strlen(str) - 1] = '\0'; substr[strlen(substr) - 1] = '\0'; replace[strlen(replace) - 1] = '\0'; // check whether the substring to be replaced is present while (str[i] != '\0') { if (str[i] == substr[j]) { if (!flag) start = i; j++; if (substr[j] == '\0') break; flag = 1; } else { flag = start = j = 0; } i++; } if (substr[j] == '\0' && flag) { for (i = 0; i < start; i++) output[i] = str[i]; // replace substring with another string for (j = 0; j < strlen(replace); j++) { output[i] = replace[j]; i++; } // copy remaining portion of the input string "str" for (j = start + strlen(substr); j < strlen(str); j++) { output[i] = str[j]; i++; } // print the final string output[i] = '\0'; printf("Output: %s\n", output); } else { printf("%s is not a substring of %s\n", substr, str); } return 0; }
//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; }
//Replace Substring in a String Java code
import java.util.Scanner; public class ReplaceASubstringInAString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a String : "); String s1 = sc.nextLine(); System.out.print("Enter the String to be replaced : "); String oldString = sc.nextLine(); System.out.print("Enter the new String : "); String newString =sc.nextLine(); String replaceString = s1.replace(oldString, newString); System.out.println("New String is :"+replaceString); } }
string=input("Enter String :\n") str1=input("Enter substring which has to be replaced :\n") str2=input("Enter substring with which str1 has to be replaced :\n") string=string.replace(str1,str2) print("String after replacement") print(string)
Write a code for Heap sort.
#include<stdio.h> // including library files int temp; void heapify(int arr[], int size, int i)//declaring functions { int max = i; int left = 2*i + 1; int right = 2*i + 2; if (left < size && arr[left] >arr[max]) max= left; if (right < size && arr[right] > arr[max]) max= right; if (max!= i) { // performing sorting logic by using temporary variable temp = arr[i]; arr[i]= arr[max]; arr[max] = temp; heapify(arr, size, max); } } void heapSort(int arr[], int size)// providing definition to heap sort { int i; for (i = size / 2 - 1; i >= 0; i--) heapify(arr, size, i); for (i=size-1; i>=0; i--) { // swaping logic temp = arr[0]; arr[0]= arr[i]; arr[i] = temp; heapify(arr, i, 0); } } void main() // defining main() { int arr[] = {58, 134, 3, 67, 32, 89, 15, 10,78, 9}; // array initializing with their elements. int i; int size = sizeof(arr)/sizeof(arr[0]); heapSort(arr, size); printf("printing sorted elements\n"); // printing the sorted array for (i=0; i<size; ++i) printf("%d\n",arr[i]); }
#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); }
// Java program for implementation of Heap Sort public class PrepInsta { //Main() for the execution of the program public static void main(String args[]) { int a[] = {12, 11, 13, 5, 6, 7}; int len = a.length; PrepInsta ob = new PrepInsta(); ob.sort(a); System.out.println("Sorted array is"); printArray(a); } public void sort(int a[]) { int len = a.length; // Build heap (rearrange array) for (int i = len / 2 - 1; i >= 0; i--) heapify(a, len, i); // One by one extract an element from heap for (int i=len-1; i>=0; i--) { // Move current root to end int temp = a[0]; a[0] = a[i]; a[i] = temp; // call max heapify on the reduced heap heapify(a, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int a[], int len, int i) { int largest = i; // Initialize largest as root int l = 2*i + 1; // left = 2*i + 1 int r = 2*i + 2; // right = 2*i + 2 // If left child is larger than root if (l < len && a[l] > a[largest]) largest = l; // If right child is larger than largest so far if (r < len && a[r] > a[largest]) largest = r; // If largest is not root if (largest != i) { int swap = a[i]; a[i] = a[largest]; a[largest] = swap; // Recursively heapify the affected sub-tree heapify(a, len, largest); } } /* A utility function to print array of size n */ static void printArray(int a[]) { int len = a.length; for (int i=0; i<len; ++i) System.out.print(a[i]+" "); System.out.println(); } }
Write a code to replace each element in an array by its rank in the array
#include<stdio.h> 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 for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ int x = temp[i]; temp[i] = temp[j]; temp[j] = x; } } 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++) printf("%d ", arr[i]); }
#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]<<" "; }
import java.util.*; class Main { static void changeArr(int[] input) { // Copy input array into newArray int newArray[] = Arrays.copyOfRange(input, 0, input.length); // Sort newArray[] in ascending order Arrays.sort(newArray); for(int i=0; i< input.length; i++){ for(int j=0; j< input.length; j++){ if(newArray[j]==input[i]) { input[i] = j+1; break; } } } } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 100, 2, 70, 12 , 90}; // Function Call changeArr(arr); // Print the array elements System.out.println(Arrays.toString(arr)); } }
def changeArr(input1): newArray = input1.copy() newArray.sort() for i in range(len(input1)): for j in range(len(newArray)): if input1[i]==newArray[j]: input1[i] = j+1; break; # Driver Code arr = [100, 2, 70, 12 , 90] changeArr(arr) # Print the array elements print(arr)
Write a code to find circular rotation of an array by K positions.
#include<stdio.h> int main() { int size; printf("Size of array: "); scanf("%d",&size); int arr[size]; printf("Enter the elements "); for(int a=0;a<size;a++) scanf("%d",&arr[a]); int n; printf("Enter the index from where you want your array to rotate "); scanf("%d",&n); printf("Array: \n"); for (int a = 0; a < size; a++) { printf("%d ", arr[a]); } for(int a = 0; a < n; a++) { int b, temporary; temporary = arr[size-1]; for(b = size-1; b > 0; b--) { arr[b] = arr[b-1]; } arr[0] = temporary; } printf("\n"); printf("New Array: \n"); for(int a = 0; a< size; a++){ printf("%d ", arr[a]); } return 0; }
#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; }
class Main { /*Function to left rotate arr[] of size n by d*/ static void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n - 1] = temp; } /* utility function to print an array */ static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Driver program to test above functions public static void main(String[] args) { // RotateArray rotate = new RotateArray(); int arr[] = {1, 2, 3, 4, 5}; leftRotate(arr, 2, 5); printArray(arr, 5); } }
def rotateArray(arr, n, d): temp = [] i = 0 while (i < d): temp.append(arr[i]) i = i + 1 i = 0 while (d < n): arr[i] = arr[d] i = i + 1 d = d + 1 arr[:] = arr[: i] + temp return arr
Write a code to find non-repeating elements in an array.
#include<stdio.h> // Main function to run the program int main() { int arr[] = {21, 30, 10, 2, 10, 20, 30, 11}; int n = sizeof(arr)/sizeof(arr[0]); int visited[n]; for(int i=0; i<n; i++){ if(visited[i]==0){ int count = 1; for(int j=i+1; j<n; j++){ if(arr[i]==arr[j]){ count++; visited[j]=1; } } if(count==1) printf("%d "arr[i]); } } return 0; }
#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; }
import java.util.Arrays; class Main { public static void countFreq(int arr[], int n) { boolean visited[] = new boolean[n]; Arrays.fill(visited, false);
// Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } }
if(count==1)
System.out.println(arr[i]); }
} // Driver code public static void main(String []args) { int arr[] = new int[]{10, 30, 40, 20, 10, 20, 50, 10}; int n = arr.length; countFreq(arr, n); } }
# Python 3 program to count unique elements def count(arr, n): # Mark all array elements as not visited visited = [False for i in range(n)] # Traverse through array elements # and count frequencies for i in range(n): # Skip this element if already # processed if (visited[i] == True): continue # Count frequency count = 1 for j in range(i + 1, n, 1): if (arr[i] == arr[j]): visited[j] = True count += 1 if count == 1 : print(arr[i]); # Driver Code arr = [10, 30, 40, 20, 10, 20, 50, 10] n = len(arr) count(arr, n)
Write a code to check for the longest palindrome in an array.
#include<stdio.h> #include<limits.h> 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; printf("%d ",res); }
#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; }
import java.util.*; class Main { // Function to check if n is palindrome static boolean isPalindrome(int n) { // Find the appropriate divisor // to extract the leading digit int divisor = 1; while (n / divisor >= 10) divisor *= 10; while (n != 0) { int x = n / divisor; int y = n % 10; // If first and last digits are // not same then return false if (x != y) return false; // Removing the leading and trailing // digits from the number n = (n % divisor) / 10; // Reducing divisor by a factor // of 2 as 2 digits are dropped divisor = divisor / 100; } return true; } // Function to find the largest palindromic number static int largestPalindrome(int []A, int n) { int res = -1; for (int i = 0; i < n; i++) { // If a palindrome larger than the currentMax is found if (A[i] > res && isPalindrome(A[i])) res = A[i]; } // Return the largest palindromic number from the array return res; } // Driver program public static void main(String []args) { int []A = { 121, 2322, 54545, 999990 }; int n = A.length; // print required answer System.out.println(largestPalindrome(A, n)); } }
# Function to check if n is palindrome def isPalindrome(n): divisor = 1 while (int(n / divisor) >= 10): divisor *= 10 while (n != 0): leading = int(n / divisor) trailing = n % 10 if (leading != trailing): return False n = int((n % divisor) / 10) divisor = int(divisor / 100) return True # Function to find the largest palindromic element def largestPalindrome(arr, n): currentMax = -1 for i in range(0, n, 1): if (arr[i] > currentMax and isPalindrome(arr[i])): currentMax = arr[i] return currentMax # Driver Code arr = [1, 232, 5545455, 909090, 161] n = len(arr) # print required answer print(largestPalindrome(arr, n))
Write a code to find the factorial of a number.
#include<stdio.h> int main () { int num = 5, fact = 1; // Can't calculate factorial of a negative number if(num < 0) printf("Error"); else { for(int i = 1; i <= num; i++) fact = fact * i; } printf("Fact %d: %d",num, fact); } // Time complexity: O(N) // Space complexity: O(1)
#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)
//Java program to find factorial of a number import java.util.Scanner; public class LearnCoding { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number : "); int num = sc.nextInt(); if(num >= 0) { System.out.println(num + " Factorial: " + getFact(num)); } else System.out.println("Negative Number: No Factorial"); } private static int getFact(int num) { if(num == 1 || num == 0) return 1; return num * getFact(num-1); } }
num = 5 output = 1 for i in range(2,num+1): output*=i print(output)
Write the code to for Armstrong number
#include #include // 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; } int 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 () { int num, len; printf("Enter a number: "); scanf("%d",&num); // function to get order(length) len = order(num); // check if Armstrong if (armstrong(num, len)) printf("%d is Armstrong", num); else printf("%d is Not Armstrong", num); }
#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; }
public class Main { public static void main (String[]args) { int num = 407, len; // function to get order(length) len = order (num); // check if Armstrong if (armstrong (num, len)) System.out.println(num + " is armstrong"); else System.out.println(num + " is armstrong"); } static int order (int x) { int len = 0; while (x != 0 ) { len++; x = x / 10; } return len; } static boolean 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 + (int)Math.pow(digit, len); temp /= 10; }; return num == sum; } }
number = 371 num = number digit, sum = 0, 0 length = len(str(num)) for i in range(length): digit = int(num%10) num = num/10 sum += pow(digit,length) if sum==number: print("Armstrong") else: print("Not Armstrong")
Write a program to find the sum of Natural Numbers using Recursion.
#include<stdio.h> int getSum(int sum,int n) { if(n==0) return sum; return n+getSum(sum,n-1); } int main() { int n, sum = 0; scanf("%d",&n); printf("%d",getSum(sum, n)); return 0; } // Time complexity : O(n) // Space complexity : O(1) // Auxilary space complexity : O(N) // Due to function call stack
#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; }
public class Main { public static void main (String[]args) { int n = 10; int sum = getSum (n); System.out.println (sum); } static int getSum (int n) { if (n == 0) return n; return n + getSum (n - 1); } }
def getSum(num): if num == 1: return 1 return num + getSum(num-1) num = 5 print(getSum(num))
Write a program to add Two Matrices using Multi-dimensional Array.
#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.
#include Numbers(int n); int main() { int num; printf("Enter a positive integer: "); scanf("%d", &num); printf("Sum = %d", addNumbers(num)); return 0; } int addNumbers(int n) { if (n != 0) return n + addNumbers(n - 1); else return n; }
#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; }
public class Main { public static void main (String[]args) { int n = 10; int sum = getSum (n); System.out.println (sum); } static int getSum (int n) { if (n == 0) return n; return n + getSum (n - 1); } }
def recursum(number): if number == 0: return number return number + recursum(number-1) number, sum = 6,0 print(recursum(number))
Write code to check a String is palindrome or not?
#include#include // A function to check if a string str is palindrome voids isPalindrome(char str[]) { // Start from leftmost and rightmost corners of str int l = 0; int h = strlen(str) - 1; // Keep comparing characters while they are same while (h > l) { if (str[l++] != str[h--]) { printf("%s is Not Palindrome", str); return; } } printf("%s is palindrome", str); } // Driver program to test above function int main() { isPalindrome("abba"); isPalindrome("abbccbba"); isPalindrome("geeks"); return 0; }
#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; }
import java.util.Scanner; public class Palindrome{ public static void main(String args[]) { Scanner reader = new Scanner(System.in); System.out.println("Please enter a String"); String input = reader.nextLine(); System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input)); System.out.println("Please enter another String"); input = reader.nextLine(); System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input)); reader.close(); } public static boolean isPalindrome(String input) { if (input == null || input.isEmpty()) { return true; } char[] array = input.toCharArray(); StringBuilder sb = new StringBuilder(input.length()); for (int i = input.length() - 1; i >= 0; i--) { sb.append(array[i]); } String reverseOfString = sb.toString(); return input.equals(reverseOfString); } }
# function which return reverse of a string def isPalindrome(s): return s == s[::-1] # Driver code s = "malayalam" ans = isPalindrome(s) if ans: print("Yes") else: print("No")
Write a program for Binary to Decimal to conversion
#include<stdio.h> int main() { int num, binary_val, decimal_val = 0, base = 1, rem; printf("Insert a binary num (1s and 0s) \n"); scanf("%d", &num); /* maximum five digits */ binary_val = num; while (num > 0) { rem = num % 10; decimal_val = decimal_val + rem * base; //num/=10; num = num / 10 ; //base*=2; base = base * 2; } //display binary number printf("The Binary num is = %d \n", binary_val); //display decimal number printf("Its decimal equivalent is = %d \n", decimal_val); return 0; }
//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; }
//Java program to convert Binary number to decimal number import java.util.Scanner; public class Binary_To_Decimal { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a binary number : "); int binary = sc.nextInt(); //Declaring variable to store decimal number int decimal = 0; //Declaring variable to use in power int n = 0; //writing logic for the conversion while(binary > 0) { int temp = binary%10; decimal += temp*Math.pow(2, n); binary = binary/10; n++; } System.out.println("Decimal number : "+decimal); //closing scanner class(not compulsory, but good practice) sc.close(); } }
num = int(input("Enter number:")) binary_val = num decimal_val = 0 base = 1 while num > 0: rem = num % 10 decimal_val = decimal_val + rem * base num = num // 10 base = base * 2 print("Binary Number is {} and Decimal Number is {}".format(binary_val, decimal_val))
Write a program to check whether a character is a vowel or consonant
#include int main() { char c; int isLowerVowel, isUpperVowel; printf("Enter an alphabet: "); scanf("%c",&c); //To find the corrector is lowercase vowel isLowerVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); //To find the character is Upper case vowel isUpperVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); // compare to charector is Lowercase Vowel or Upper case Vowel if (isLowerVowel || isUpperVowel) printf("%c is a vowel", c); //to check character is alphabet or not elseif((c >= 'a' && c= 'A' && c <= 'Z')) prinf("\n not a alphabet\n"); else printf("%c is a consonant", c); return 0; }
//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; }
//JAVA Program to check whether the character entered by user is Vowel or Consonant. import java.util.Scanner; public class vowelorconsonant { //class declaration public static void main(String[] args) { //main method declaration Scanner sc=new Scanner(System.in); //scanner class object creation System.out.println(" Enter a character"); char c = sc.next().charAt(0); //taking a character c as input from user if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') //condition for the vowels System.out.println(" Vowel"); else if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) //condition for the consonants System.out.println(" Consonant"); else System.out.println(" Not an Alphabet"); sc.close() //closing scanner class(not mandatory but good practice) } //end of main method } //end of class
#get user input Char = input() #Check if the Char belong to set of Vowels if (Char == 'a' or Char == 'e' or Char == 'i' or Char == 'o' or Char == 'u'): #if true print("Character is Vowel") else: #if false print("Character is Consonant")
Write a code to find an Automorphic number
#include<stdio.h> int checkAutomorphic(int num) { int square = num * num; while (num > 0) { if (num % 10 != square % 10) return 0; // Reduce N and square num = num / 10; square = square / 10; } return 1; } int main() { //enter value int num; scanf("%d",&num); //checking condition if(checkAutomorphic(num)) printf("Automorphic"); else printf("Not Automorphic"); return 0; }
//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; }
//Java program to check whether a number is Automorphic number or not import java.util.Scanner; public class automorphic_number_or_not { public static void main(String[] args) { //scanner class declaration Scanner sc = new Scanner(System.in); //input from user System.out.print("Enter a number : "); int number = sc.nextInt(); //Convert the number to string String s1 = Integer.toString(number); //Calculate the length int l1 = s1.length(); int sq = number * number; String s2 = Integer.toString(sq); int l2 = s2.length(); //Create Substring String s3 = s2.substring(l2-l1); if(s1.equals(s3)) System.out.println("Automorphic Number"); else System.out.println("Not an Automorphic Number"); //closing scanner class(not compulsory, but good practice) sc.close(); } }
Write a code to find Find the ASCII value of a character
/* C Program to identify ASCII Value of a Character */ #include #include int main() { char a; printf("\n Kindly insert any character \n"); scanf("%c",&a); printf("\n The ASCII value of inserted character = %d",a); return 0; }
//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; }
//Java program to print ASCII values of a character import java.util.Scanner; class Main { public static void main(String[] args) { //scanner class object creation Scanner sc=new Scanner(System.in); //input from user System.out.print("Enter a Character: "); char c=sc.next().charAt(0); //typecasting from character type to integer type int i = c; //printing ASCII value of the character System.out.println("ASCII value of "+c+" is "+i); //closing scanner class(not compulsory, but good practice) sc.close(); } }
#user input Char = input('Enter the character :') #convert Char to Ascii value Asciival = ord(Char) #print Value print(Asciival)
Write a code to Remove all characters from string except alphabets
#include <stdio.h> int main() { //Initializing variable. char str[100]; int i, j; //Accepting input. printf(" 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. printf(" After removing non alphabetical characters the string is :"); puts(str); return 0; }
#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; }
import java.util.Scanner; class RemoveCharactersInAtringExceptAlphabets { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.print("Enter String : "); String s = sc.nextLine(); s=s.replaceAll("[^a-zA-Z]",""); System.out.println(s); } }
#take user input String1 = input('Enter the String :') #initialize empty String String2 = '' for i in String1: #check for alphabets if (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122): #concatenate to empty string String2+=i print('Alphabets in string are :' + String2)
Write a code to find Fibonacci Series using Recursion
//Fibonacci Series using Recursion #include int fibo(int n) { if (n <= 1) return n; return fibo(n-1) + fibo(n-2); }int main () { int n = 9; printf("%d", fib(n)); getchar(); return 0; }
//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; }
//Fibonacci Series using Recursion class fibonacci { static int fibo(int n) { if (n <= 1) return n; return fibo(n-1) + fibo(n-2); } public static void main (String args[]) { int n = 9; System.out.println(fibo(n)); } }
#Function for nth Fibonacci number def Fibo(n): if n<0: print("Incorrect input") #1st Fibonacci number is 0 elif n==0: return 0 #2nd Fibonacci number is 1 elif n==1: return 1 else: return Fibo(n-1)+Fibo(n-2) #Main Program print(Fibo(9))
Login/Signup to comment