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
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. You can prepare for coding languages here:-
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.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Top 50 Coding Interview Questions
1. Write a code to reverse a number
#include<stdio.h> 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<bits/stdc++.h> 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))
(Use Coupon Code CT10 and get flat 10% off on your PrepInsta Prime Subscription.)
2. 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<bits/stdc++.h> 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()
3. 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<bits/stdc++.h> 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)
Use Coupon Code “CT10” and get flat 10% OFF on your PrepInsta Prime subscription.
4. Write code of Perfect number
#include<stdio.h> 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<bits/stdc++.h> 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”)
5. Write code to Check if two strings are Anagram or not
#include<stdio.h> 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’)
6. Write code Check if the given string is Palindrome or not
#include<stdio.h> #include <string.h> 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<bits/stdc++.h> 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')
7. Write code to Calculate frequency of characters in a string
#include<stdio.h> 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<bits/stdc++.h> 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')
8. Write code to check if two strings match where one string contains wildcard characters
#include<stdio.h> #include<string.h> 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<bits/stdc++.h> 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
9. 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<bits/stdc++.h> 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; }
10. 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++; } } }
11. 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; }
12. 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 = " ")
13. 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)
Use Coupon Code “CT10” and get flat 10% OFF on your PrepInsta Prime subscription.
14. 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(); } }
15. 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)
16. 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
17. 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)
18. 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))
19. 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)
20. 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")
21. 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))
22. 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; }
23. 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))
24. 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")
25. 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))
26. 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")
27. 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(); } }
28. 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)
29. 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)
Use Coupon Code “CT10” and get flat 10% OFF on your PrepInsta Prime subscription.
30. Write a code to Print the smallest element of the array
#include < stdio.h > int getSmallest(int arr[], int len) { // assign first array element as smallest int min = arr[0]; // linearly search for the smallest element for(int i=1; i < len; i++) { // if the current array element is smaller if (arr[i] < min) min = arr[i]; } return min; } int main() { int arr[] = {5, 8, 7, 2, 12, 4}; // get the length of the array int len = sizeof(arr)/sizeof(arr[0]); printf("The smallest : %d", getSmallest(arr, len)); }
#include< bits/stdc++.h> using namespace std; int main(){ int arr[] = { 34, 5, 89, 90, 56}; int n = sizeof(arr)/ sizeof(arr[0]); int mini = INT_MAX; for(int i=0; i< n; i++){ if(arr[i] < mini) mini = arr[i]; } cout<< mini; }
import java.util.Scanner; public class Main { public static void main(String args[]) { int arr[] = {12, 13, 1, 10, 34, 10}; int min = arr[0]; for(int i=0; iarr[i]) { min = arr[i]; } } System.out.print(min); } }
arr = [10, 89, 9, 56, 4, 80, 8] mini = arr[0] for i in range(len(arr)): if arr[i] < mini: mini = arr[i] print (mini)
31. Write a code to Reverse the element of the array
#include < stdio.h> void printReverse(int arr[], int len){ for(int i = len - 1; i >= 0; i--) printf("%d ", arr[i]); } int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int len = sizeof(arr)/sizeof(arr[0]); printf("Array in Reverse:\n"); printReverse(arr, len); return 0; }
#include< bits/stdc++.h> using namespace std; int main(){ int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr)/sizeof(arr[0]); for(int i=n-1; i>=0; i--) cout<< arr[i]<<" "; }
import java.util.Scanner; public class Main { public static void main(String args[]) { int arr[] = {10, 20, 30, 40, 50}; int n=arr.length; for(int i=n-1; i>=0; i--) System.out.print(arr[i]+" "); } }
def reverseList(A, start, end): while start < end: A[start], A[end] = A[end], A[start] start += 1 end -= 1 # Driver function to test above function A = [10, 20, 30, 40, 50] reverseList(A, 0, 4) print(A)
32. Write a code to Sort the element of the array
#include < stdio.h> void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int array[], int size) { int i, j, min_idx; // Loop to iterate on array for (i = 0; i < size-1; i++) { // Here we try to find the min element in array min_idx = i; for (j = i+1; j < size; j++) { if (array[j] < array[min_idx]) min_idx = j; } // Here we interchange the min element with first one swap(&array[min_idx], &array[i]); } } /* Display function to print values */ void display(int array[], int size) { int i; for (i=0; i < size; i++) { printf("%d ",array[i]); } printf("\n"); } // The main function to drive other functions int main() { int array[] = {50, 30, 10, 90, 80, 20, 40, 70}; int size = sizeof(array)/sizeof(array[0]); selectionSort(array, size); display(array, size); return 0; }
#include< bits/stdc++.h> using namespace std; void sorted(int arr[], int n){ for(int i=0; iarr[j]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(int i=0; i< n; i++) cout<< arr[i]<<" "; } int main(){ int arr[] = {10, 89, 67, 45, 83, 9, 12}; int n = sizeof(arr)/sizeof(arr[0]); sorted(arr, n); }
public class Main { public static void main(String[] args) { //Initialize array int [] arr = new int [] {10, 40, 30, 20}; int temp = 0; //Sort the array in ascending order for (int i = 0; i < arr.length; i++) { for (int j = i+1; j < arr.length; j++) { if(arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } //Displaying elements of array after sorting for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
# List of Integers numbers = [10, 30, 40, 20] # Sorting list of Integers numbers.sort() print(numbers)
33. Write a code to Sort the element of the array without sort method
#include < stdio.h> void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int array[], int size) { int i, j, min_idx; // Loop to iterate on array for (i = 0; i < size-1; i++) { // Here we try to find the min element in array min_idx = i; for (j = i+1; j < size; j++) { if (array[j] < array[min_idx]) min_idx = j; } // Here we interchange the min element with first one swap(&array[min_idx], &array[i]); } } /* Display function to print values */ void display(int array[], int size) { int i; for (i=0; i < size; i++) { printf("%d ",array[i]); } printf("\n"); } // The main function to drive other functions int main() { int array[] = {50, 30, 10, 90, 80, 20, 40, 70}; int size = sizeof(array)/sizeof(array[0]); selectionSort(array, size); display(array, size); return 0; }
#include< bits/stdc++.h> using namespace std; void sorted(int arr[], int n){ for(int i=0; iarr[j]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(int i=0; i< n; i++) cout<< arr[i]<<" "; } int main(){ int arr[] = {10, 89, 67, 45, 83, 9, 12}; int n = sizeof(arr)/sizeof(arr[0]); sorted(arr, n); }
public class Main { public static void main(String[] args) { //Initialize array int [] arr = new int [] {10, 40, 30, 20}; int temp = 0; //Sort the array in ascending order for (int i = 0; i < arr.length; i++) { for (int j = i+1; j < arr.length; j++) { if(arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } //Displaying elements of array after sorting for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
# List of Integers numbers = [10, 30, 40, 20] # Sorting list of Integers numbers.sort() print(numbers)
34. 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=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: "<
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)
35. Write a code to Remove space from a string
#include< stdio.h> using namespace std; // Function to remove all spaces from a given string void removeSpaces(char *str) { // To keep track of non-space character count int count = 0; // Traverse the provided string. If the current character is not a space, //move it to index 'count++'. for (int i = 0; str[i]; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is incremented str[count] = '\0'; } // Driver program to test above function int main() { char str[] = "P re p i n sta "; removeSpaces(str); printf("%s", str); return 0; }
#include < iostream> using namespace std; // Function to remove all spaces from a given string void removeSpaces(char *str) { // To keep track of non-space character count int count = 0; // Traverse the provided string. If the current character is not a space, //move it to index 'count++'. for (int i = 0; str[i]; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented str[count] = '\0'; } // Driver program to test above function int main() { char str[] = "P re p i n sta "; removeSpaces(str); cout << str; return 0; }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc =new Scanner(System.in); String s = "Prepinsta is best"; char[] c = s.toCharArray(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < c.length; i++) { if( (c[i] != ' ') && (c[i]!= '\t' )) { sb.append(c[i]); } } System.out.println("String after removing spaces : "+sb); } }
#take user input String = "PrepInsta is fabulous" #Use join function String = "".join(String.split()) #print String print("After removing spaces string is :",String)
36. Write a code to Count Inversion
#include < stdio.h > int _mergeSort(int arr[], int temp[], int left, int right); int merge(int arr[], int temp[], int left, int mid,int right); /* This function sorts the input array and returns the number of inversions in the array */ int mergeSort(int arr[], int array_size) { int temp[array_size]; return _mergeSort(arr, temp, 0, array_size - 1); } /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */ int _mergeSort(int arr[], int temp[], int left, int right) { int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left) / 2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count += _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } /* This funt merges two sorted arrays and returns inversion count in the arrays.*/ int merge(int arr[], int temp[], int left, int mid,int right) { int i, j, k; int inv_count = 0; i = left; /* i is index for left subarray*/ j = mid; /* j is index for right subarray*/ k = left; /* k is index for resultant merged subarray*/ while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; /* this is tricky -- see above explanation/diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Driver code int main() { int n ; scanf("%d", &n); int arr[n]; for(int i=0; i
#include < bits/stdc++.h> using namespace std; int _mergeSort(int arr[], int temp[], int left, int right); int merge(int arr[], int temp[], int left, int mid,int right); /* This function sorts the input array and returns the number of inversions in the array */ int mergeSort(int arr[], int array_size) { int temp[array_size]; return _mergeSort(arr, temp, 0, array_size - 1); } /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */ int _mergeSort(int arr[], int temp[], int left, int right) { int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left) / 2; /* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */ inv_count += _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } /* This funt merges two sorted arrays and returns inversion count in the arrays.*/ int merge(int arr[], int temp[], int left, int mid,int right) { int i, j, k; int inv_count = 0; i = left; /* i is index for left subarray*/ j = mid; /* j is index for right subarray*/ k = left; /* k is index for resultant merged subarray*/ while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; /* this is tricky -- see above explanation/diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Driver code int main() { int n ; cin>>n; int arr[n]; for(int i=0; i>arr[i]; int ans = mergeSort(arr, n); cout << " Number of inversions are " << ans; return 0; }
public class Main { static int arr[] = new int[]{1, 6, 4, 5}; static int getInvCount(int n) { int inv_count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] > arr[j]) inv_count++; return inv_count; } // Driver method to test the above function public static void main(String[] args) { System.out.println("Number of inversions are " + getInvCount(arr.length)); } }
def inversion(arr): ans = 0 for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[j] < arr[i]: ans += 1 return ans array = [6, 3, 5, 2, 7] print("There are", inversion(array), "possible inversion")
37. Write a code to find consecutive largest subsequence
#include < stdio.h> #include < stdlib.h> //call back function int compare(const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int findLongestConseqSeq(int arr[], const int n) { int length = 1; int longestConsecutiveSeq = 1; int i =0; //sort arr elements using qsort inbuilt function qsort( arr,n, sizeof(int), compare); for ( i = 0; i < n - 1; i++) { if(arr[i] == arr[i+1]) { continue; } else if (arr[i] + 1 == arr[i + 1]) { length++; } else { length = 1; } longestConsecutiveSeq = (longestConsecutiveSeq > length)? longestConsecutiveSeq: length; } return longestConsecutiveSeq; } int main() { int arr[] = {2,5,7,7,8,8,9,4,10,12,3,6}; const int N = sizeof(arr)/sizeof(arr[0]); const int longestConsecutiveSeq = findLongestConseqSeq(arr, N); printf("Longest Consecutive Sequence is %d",longestConsecutiveSeq); return 0; }
#include < bits/stdc++.h> using namespace std; // Returns length of the longest // contiguous subsequence int findLongestConseqSubseq(int arr[], int n) { int ans = 0, count = 0; // sort the array sort(arr, arr + n); vectorv; v.push_back(arr[0]); //insert repeated elements only once in the vector for (int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.push_back(arr[i]); } // find the maximum length // by traversing the array for (int i = 0; i < v.size(); i++) { if (i > 0 && v[i] == v[i - 1] + 1) count++; // reset the count else count = 1; // update the maximum ans = max(ans, count); } return ans; } // Driver code int main() { int arr[]={1, 3, 2, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Length of the Longest contiguous subsequence is "<< findLongestConseqSubseq(arr, n); return 0; }
import java.io.*; import java.util.*; public class Main { static int findLongestConseqSubseq(int arr[], int n) { // Sort the array Arrays.sort(arr); int ans = 0, count = 0; ArrayList v = new ArrayList(); v.add(10); // Insert repeated elements // only once in the vector for (int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.add(arr[i]); } // Find the maximum length // by traversing the array for (int i = 0; i < v.size(); i++) { // Check if the current element is // equal to previous element +1 if (i > 0 && v.get(i) == v.get(i - 1)) count++; else count = 1; // Update the maximum ans = Math.max(ans, count); } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.length; System.out.println( "Length of the Longest " + "contiguous subsequence is " + findLongestConseqSubseq(arr, n)); } }
def LongestConseqSubseq(arr, l): val = [] c = 0 for i in range(l): n = 1 while arr[i] + n in arr: c += 1 n += 1 val.append(c + 1) c = 0 return max(val) array = [7, 8, 1, 5, 4, 3] print("Longest Consecutive Subsequence :", LongestConseqSubseq(array, len(array)))
38: Write a Program to Find out the Sum of Digits of a Number.
#include int main () { int num, sum = 0; printf("Enter any num: "); scanf("%d",&num); //loop to find sum of digits while(num!=0){ sum += num % 10; num = num / 10; } //output printf("Sum: %d",sum); return 0; } // Time complexity : O(N) // Space complexity : O(1)
Find More Solutions at C Program to Find the Sum of Digits of a Number
//C++ Program //Sum of digits in a number #include using namespace std; int main () { int num, sum = 0; cout <<"Enter any num:"; cin >> num; //loop to find sum of digits while(num!=0){ sum += num % 10; num = num / 10; } //output cout <<"\nSum of digits : " << sum; return 0; } // Time complexity : O(N) // Space complexity : O(1) // where N is number of digits in num
Find More Solutions at C++ Program to Find the Sum of Digits of a Number
public class Main { public static void main (String[]args) { int num = 12345, sum = 0; //loop to find sum of digits while(num!=0){ sum += num % 10; num = num / 10; } //output System.out.println ("Sum of digits : " + sum); } }
Find More Solutions at JAVA Program to Find the Sum of Digits of a Number
num = input("Enter Number: ") sum = 0 for i in num: sum = sum + int(i) print(sum)
Find More Solutions at Python Program to Find the Sum of Digits of a Number
39: Write a Program to Find out the Power of a Number
// pow function is contained in math.h library #include<stdio.h> #include <math.h> int main() { double base = 2.3; double exp = 2.1; double result; // calculates the power result = pow(base, exp); // %lf used for double printf("%lf ^ %lf = %lf\n", base, exp, result); // following can be used for precision setting printf("%.1lf ^ %.1lf = %.2lf", base, exp, result); return 0; }
Find More Solutions at C Program to find out the Power of a Number
// This method handles all cases, // when exponent/bases are integers/decimals or positive/negative // pow function is contained in math.h library #include #include using namespace std; int main() { double base = 1.5; double expo1 = 2.5; double expo2 = -2.5; double res1, res2; // calculates the power res1 = pow(base, expo1); res2 = pow(base, expo2); cout << base << " ^ " << expo1 << " = " << res1 << endl; cout << base << " ^ " << expo2 << " = " << res2 << endl; return 0; }
Find More Solutions at C++ Program to Find out the Power of a Number
public class Main { public static void main(String[] args) { double base = 1.5; double expo1 = 2.5; double expo2 = -2.5; double res1, res2; // calculates the power res1 = Math.pow(base, expo1); res2 = Math.pow(base, expo2); System.out.println(base + " ^ " + expo1 + " = " + res1 ); System.out.println(base + " ^ " + expo2 + " = " + res2 ); } }
Find More Solutions at JAVA Program to Find out the Power of a Number
num, power = 3, 2 print(pow(num,power))
Find More Solutions at Python Program to Find out the Power of a Number
40: Write a Program to Find out the Sum of Digits of a Number.
#include int main () { int num, sum = 0; printf("Enter any num: "); scanf("%d",&num); //loop to find sum of digits while(num!=0){ sum += num % 10; num = num / 10; } //output printf("Sum: %d",sum); return 0; } // Time complexity : O(N) // Space complexity : O(1)Find More Solutions at C Program to Find the Sum of Digits of a Number
//C++ Program //Sum of digits in a number #include using namespace std; int main () { int num, sum = 0; cout <<"Enter any num:"; cin >> num; //loop to find sum of digits while(num!=0){ sum += num % 10; num = num / 10; } //output cout <<"\nSum of digits : " << sum; return 0; } // Time complexity : O(N) // Space complexity : O(1) // where N is number of digits in num
Find More Solutions at C++ Program to Find the Sum of Digits of a Number
public class Main { public static void main (String[]args) { int num = 12345, sum = 0; //loop to find sum of digits while(num!=0){ sum += num % 10; num = num / 10; } //output System.out.println ("Sum of digits : " + sum); } }
Find More Solutions at JAVA Program to Find the Sum of Digits of a Number
num = input("Enter Number: ") sum = 0 for i in num: sum = sum + int(i) print(sum)
Find More Solutions at Python Program to Find the Sum of Digits of a Number
41: Write a Program to Add two Fractions
#include<stdio.h> int main() { //for initialize variables int numerator1, denominator1, numerator2, denominator2, x, y, c, gcd_no; //To take user input of numerators and denominators printf("Enter the numerator for 1st number : "); scanf("%d",&numerator1); printf("Enter the denominator for 1st number : "); scanf("%d",&denominator1); printf("Enter the numerator for 2nd number : "); scanf("%d",&numerator2); printf("Enter the denominator for 2nd number : "); scanf("%d",&denominator2); //numerator x=(numerator1*denominator2)+(denominator1*numerator2); //denominator y=denominator1*denominator2; // Trick part. Reduce it to the simplest form by using gcd. for(c=1; c <= x && c <= y; ++c) { if(x%c==0 && y%c==0) gcd_no = c; } //To display fraction of givien numerators and denominators printf("(%d / %d) + (%d / %d) = (%d / %d)", numerator1, denominator1, numerator2, denominator2, x/gcd_no, y/gcd_no); return 0; }
Find More Solutions at C Program to add two fractions
#include<iostream> using namespace std; // GCD function int findGCD(int n1, int n2) { int gcd; for(int i=1; i <= n1 && i <= n2; i++) { if(n1%i==0 && n2%i==0) gcd = i; } return gcd; } // Main Program int main() { int num1,den1; //user input first fraction cout << "Enter numerator and denominator of first number : "; cin >> num1 >> den1; int num2,den2; //user input second fraction cout << "Enter numerator and denominator of second number: "; cin >> num2 >> den2; //finding lcm of the denominators int lcm = (den1*den2)/findGCD(den1,den2); //finding the sum of the numbers int sum=(num1*lcm/den1) + (num2*lcm/den2); //normalizing numerator and denominator of result int num3=sum/findGCD(sum,lcm); lcm=lcm/findGCD(sum,lcm); //printing output cout<<num1<<"/"<<den1<<" + "<<num2<<"/"<<den2<<" = "<<num3<<"/"<<lcm; return 0; }
Find More Solutions at C++ Program for Addition of two Fractions
//Java program to add two fractions import java.util.Scanner; public class Main { public static void main(String[] args) { //scanner class declaration Scanner sc = new Scanner(System.in); //input from the user System.out.print("Enter numerator for first fraction : "); int num1 = sc.nextInt(); System.out.print("Enter denominator for first fraction : "); int den1 = sc.nextInt(); System.out.print("Enter numerator for second fraction : "); int num2 = sc.nextInt(); System.out.print("Enter denominator for second fraction : "); int den2 = sc.nextInt(); int num, den, x; System.out.print("("+num1+" / "+den1+") + ("+num2+" / "+den2+") = "); //logic for calculating sum of two fractions if(den1 == den2) { num = num1 + num2 ; den = den1 ; } else{ num = (num1*den2) + (num2*den1); den = den1 * den2; } if(num > den) x = num; else x = den; for(int i = 1 ; i <= x ; i++) { if(num%i == 0 && den%i == 0) { num = num/i; den = den/i; } } //logic for getting simplified fraction int n = 1; int p = num; int q = den; if( num != den) { while(n != 0) { //storing remainder n = num % den; if(n != 0) { num = den; den = n; } } } System.out.println("("+p/den+" / "+q/den+")"); //closing scanner class(not compulsory, but good practice) sc.close(); } }
Find More Solutions at JAVA Program to Add two Fractions
def findGCD(n1, n2): gcd = 0 for i in range(1, int(min(n1, n2)) + 1): if n1 % i == 0 and n2 % i == 0: gcd = i return gcd # input first fraction num1, den1 = map(int, list(input("Enter numerator and denominator of first number : ").split(" "))) # input first fraction num2, den2 = map(int, list(input("Enter numerator and denominator of second number: ").split(" "))) lcm = (den1 * den2) // findGCD(den1, den2) sum = (num1 * lcm // den1) + (num2 * lcm // den2) num3 = sum // findGCD(sum, lcm) lcm = lcm // findGCD(sum, lcm) print(num1, "/", den1, " + ", num2, "/", den2, " = ", num3, "/", lcm)
Find More Solutions at Python Program to add two fractions
42: Write a Program to Find the Largest Element in an Array.
// C Program to find largest element in an array #include<stdio.h> int getLargest(int arr[], int len) { // assign first array element as largest int max = arr[0]; // linearly search for the largest element for(int i=1; i max) max = arr[i]; } return max; } int main() { int arr[] = {20, 5, 35, 40, 10, 50, 15}; // get the length of the array int len = sizeof(arr)/sizeof(arr[0]); printf("The Largest element is: %d", getLargest(arr, len)); } // Time complexity: O(N) // Space complexity: O(N)
Find More Solutions at C Program to Find the Largest Element in an Array
#include<bits/stdc++.h> using namespace std; int main(){ int arr[]={10, 89, 67, 56, 45, 78}; int n = sizeof(arr)/sizeof(arr[0]); int max_element = INT_MIN; for(int i=0; i<n; i++){ if(arr[i]>max_element) max_element = arr[i]; } cout<<max_element; }
Find More Solutions at C++ Program to Find the Largest Element in an Array
import java.util.Scanner; public class Main { public static void main(String args[]) { int arr[] = {12, 13, 1, 10, 34, 10}; int max = arr[0]; for(int i=0; i<arr.length; i++) { if(max < arr[i]) { max = arr[i]; } } System.out.print(max); } }
Find More Solutions at JAVA Program to Find the Largest Element in an Array
a = [10, 89, 9, 56, 4, 80, 8] max_element = a[0] for i in range(len(a)): if a[i] > max_element: max_element = a[i] print (max_element)
Find More Solutions at Python Program to Find the Largest Element in an Array
43: Write a Program to Find the Roots of a Quadratic Equation
#include <stdlib.h> #include <stdio.h> #include <stdio.h> void findRoots(int a, int b, int c) { if (a == 0) { printf("Invalid"); return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { printf("Roots are real and different \n"); printf("%f\n%f", (double)(-b + sqrt_val) / (2 * a),(double)(-b - sqrt_val) / (2 * a)); } else if (d == 0) { printf("Roots are real and same \n"); printf("%f", -(double)b / (2 * a)); } else // d < 0 { printf("Roots are complex \n"); printf("%f + i%f\n%f - i%f", -(double)b / (2 * a), sqrt_val/(2 * a), -(double)b / (2 * a), sqrt_val/(2 * a)); } } int main() { int a = 1, b = 4, c = 4; findRoots(a, b, c); return 0; }
Find More Solutions at C Program to Find the Roots of a Quadratic Equation
/* Write a program to find roots of a quadratic equation in C++*/ #include using namespace std; void findRoots(int a, int b, int c) { if (a == 0) { cout << "Invalid"; return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { cout << "Roots are real and different \n"; cout << (double)(-b + sqrt_val) / (2 * a) << "\n"<< (double)(-b - sqrt_val) / (2 * a); } else if (d == 0) { cout << "Roots are real and same \n"; cout << -(double)b / (2 * a); } else // d < 0 { cout << "Roots are complex \n"; cout << -(double)b / (2 * a) << " + i" << sqrt_val<< "\n" << -(double)b / (2 * a) << " - i" << sqrt_val; } } // Driver code int main() { int a = 1, b = 4, c = 4; findRoots(a, b, c); return 0; }
Find More Solutions at C++ Program to Find the Roots of a Quadratic Equation
import java.io.*; import static java.lang.Math.*; class Main{ static void findRoots(int a, int b, int c) { if (a == 0) { System.out.println("Invalid"); return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { System.out.println("Roots are real and different"); System.out.println((double)(-b + sqrt_val) / (2 * a) + "\n"+ (double)(-b - sqrt_val) / (2 * a)); } else if (d == 0) { System.out.println("Roots are real and same "); System.out.println(-(double)b / (2 * a) + "\n" + -(double)b / (2 * a)); } else // d < 0 { System.out.println("Roots are complex"); System.out.println(-(double)b / (2 * a) + " + i" + sqrt_val + "\n" + -(double)b / (2 * a) + " - i" + sqrt_val); } } // Driver code public static void main(String args[]) { int a = 1, b = 4, c = 4; // Function call findRoots(a, b, c); } }
Find More Solutions at JAVA Program to Find the Roots of a Quadratic Equation
# Write a program to find roots of a quadratic equation in Python import math def findRoots(a, b, c): if a == 0: print("Invalid") return -1 d = b * b - 4 * a * c sqrt_val = math.sqrt(abs(d)) if d > 0: print("Roots are real and different ") print((-b + sqrt_val)/(2 * a)) print((-b - sqrt_val)/(2 * a)) elif d == 0: print("Roots are real and same") print(-b / (2*a)) else: # d<0 print("Roots are complex") print(- b / (2*a), " + i", sqrt_val) print(- b / (2*a), " - i", sqrt_val) # Driver Program a = 1 b = 4 c = 4 # Function call findRoots(a, b, c)
Find More Solutions at Python Program to Find the Roots of a Quadratic
44: Write a Program to Find the Prime Factors of a Number.
#include<stdio.h> void primefactor(int num) { printf("Prime factors of the number : "); for (int i = 2; num > 1; i++) { while (num % i == 0) { printf("%d ", i); num = num / i; } } } int main() { int num; printf("Enter the positive integer: "); scanf("%d", &num); primefactor(num); return 0; }
Find More Solutions at C Program to Find the Prime Factors of a Number
// C++ program to print all prime factors #include using namespace std; void primeFactors(int n) { while (n % 2 == 0) { cout << 2 << " "; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n % i == 0) { cout << i << " "; n = n/i; } } if (n > 2) cout << n << " "; } // Driver code int main() { int n = 315; primeFactors(n); return 0; }
Find More Solutions at C++ Program to Find the Prime Factors of a Number
import java.io.*; import java.lang.Math; class Main { public static int isprime(int n){ for(int i = 2; i<=Math.sqrt(n); i++){ if(n%i==0) return 0; } return 1; } public static void primeFactors(int n) { for(int i = 2; i<= n; i++){ if(isprime(i)==1){ int x = n; while(x%i==0){ System.out.print(i + " "); x /= i; } } } } public static void main(String[] args) { int n = 90; primeFactors(n); } }
Find More Solutions at JAVA Program to Find the Prime Factor of a Number
def Prime_Factorial(n): if n < 4: return n arr = [] while n > 1: for i in range(2, int(2+n//2)): if i == (1 + n // 2): arr.append(n) n = n // n if n % i == 0: arr.append(i) n = n // i break return arr n = 210 print(Prime_Factorial(n))
Find More Solutions at Python Program to Find the Prime Factor of a Number
45: Write a Program to Convert Digits to Words.
#include <stdio.h> #include <string.h> #include <stdlib.h> void convert_to_words(char* num) { int len = strlen(num); /* Base cases */ if (len == 0) { fprintf(stderr, "empty string\n"); return; } if (len > 4) { fprintf(stderr, "Length more than 4 is not supported\n"); return; } char* single_digits[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; char* two_digits[]= { "", "ten", "eleven","twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; char* tens_multiple[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; char* tens_power[] = { "hundred", "thousand" }; printf("\n%s: ", num); if (len == 1) { printf("%s\n", single_digits[*num - '0']); return; } while (*num != '\0') { if (len >= 3) { if (*num - '0' != 0) { printf("%s ", single_digits[*num - '0']); printf("%s ", tens_power[len - 3]); } --len; } else { if (*num == '1') { int sum = *num - '0' + *(num + 1) - '0'; printf("%s\n", two_digits[sum]); return; } else if (*num == '2' && *(num + 1) == '0') { printf("twenty\n"); return; } else { int i = *num - '0'; printf("%s ", i ? tens_multiple[i] : ""); ++num; if (*num != '0') printf("%s ", single_digits[*num - '0']); } } ++num; } } int main(void) { convert_to_words("9459"); return 0; }
Find More Solutions at C Program to Convert Digits to Words
#include<bits/stdc++.h> using namespace std; void numToWords(string num){ int length_of_string = num.size(); if (length_of_string == 0){ cout<<"String is Empty"; return; } if (length_of_string > 4){ cout<<"Please enter the string with supported length"; return; } string ones_digits[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; string tens_digits[] = {"", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen","nineteen"}; string multiple_of_ten[] = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; string power_of_ten[] = {"hundred", "thousand"}; cout<<num<<":\n"; if (length_of_string == 1){ cout<<ones_digits[num[0] - '0']; //return; } int x=0; while (x < num.size()){ if(length_of_string >= 3){ if (num[x] - 48 != 0){ cout<<ones_digits[num[x] - 48]<<"\n"; cout<<power_of_ten[length_of_string - 3]<<"\n"; length_of_string--; } } else{ if (num[x] - 48 == 1){ int sum = (num[x] - 48 + num[x] - 48); cout<<tens_digits[sum]; // return; } else if(num[x] - 48 == 2 and num[x + 1] - 48 == 0){ cout<<"twenty"; //return; } else{ int i = num[x] - 48; if(i > 0){ cout<<multiple_of_ten[i]<<" "; } else{ cout<<" "; } x += 1; if(num[x] - 48 != 0){ cout<<ones_digits[num[x] - 48]; } } } x++; } } int main(){ numToWords("1121"); return 0; }
Find More Solutions at C++ Program to Convert Digits to Words
class Main { static void convert_to_words(char[] num) { int len = num.length; // Base cases if (len == 0) { System.out.println("empty string"); return; } if (len > 4) { System.out.println( "Length more than 4 is not supported"); return; } String[] single_digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; String[] two_digits = new String[] { "", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; String[] tens_multiple = new String[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; String[] tens_power = new String[] { "hundred", "thousand" }; System.out.print(String.valueOf(num) + ": "); if (len == 1) { System.out.println(single_digits[num[0] - '0']); return; } int x = 0; while (x < num.length) { if (len >= 3) { if (num[x] - '0' != 0) { System.out.print(single_digits[num[x] - '0'] + " "); System.out.print(tens_power[len - 3] + " "); } --len; } else { if (num[x] - '0' == 1) { int sum = num[x] - '0' + num[x + 1] - '0'; System.out.println(two_digits[sum]); return; } else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0) { System.out.println("twenty"); return; } else { int i = (num[x] - '0'); if (i > 0) System.out.print(tens_multiple[i] + " "); else System.out.print(""); ++x; if (num[x] - '0' != 0) System.out.println(single_digits[num[x] - '0']); } } ++x; } } // Driver Code public static void main(String[] args) { convert_to_words("1121".toCharArray()); } }
Find More Solutions at JAVA Program to Convert Digits to Words
from num2words import num2words # Most common usage. print(num2words(11098)) # can also specify this for -th format print(num2words(11098, to='ordinal'))
Find More Solutions at Python Program to Convert Digits to Words
46: Write a Program to Find the Factorial of a Number using Recursion.
#include<stdio.h> int getFactorial(int num) { if(num == 0) return 1; return num * getFactorial(num-1); } int main () { int num = 7; int fact = getFactorial(num); printf("Fact %d: %d",num, fact); }
Find More Solutions at C Program to Find the Factorial of a Number using Recursion
#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)
Find More Solutions at C++ Program to Find the Factorial of a Number using Recursion
class Main { // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } // Driver method public static void main(String[] args) { int num = 5; System.out.println("Factorial of " + num + " is " + factorial(5)); } }
Find More Solutions at JAVA Program to Find the Factorial of a Number using Recursion
def factorial(n): if n == 0: return 1 return n * factorial(n - 1) num = 5 print("Factorial of", num, "is", factorial(num))
Find More Solutions at Python Program to Find the Factorial of a Number usinf Recursion
47: Write a Program to Reverse an Array
#include <stdio.h> void printReverse(int arr[], int len){ for(int i = len - 1; i >= 0; i--) printf("%d ", arr[i]); } int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int len = sizeof(arr)/sizeof(arr[0]); printf("Array in Reverse:\n"); printReverse(arr, len); return 0; }Find More Solutions at C Program to Reverse an Array
>#include<bits/stdc++.h> using namespace std; int main(){ int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr)/sizeof(arr[0]); for(int i=n-1; i>=0; i--) cout<<arr[i]<<" "; }
Find More Solutions at C ++ Program to Reverse an Array
import java.util.Scanner; public class Main { public static void main(String args[]) { int arr[] = {10, 20, 30, 40, 50}; int n=arr.length; for(int i=n-1; i>=0; i--) System.out.print(arr[i]+" "); } }
Find More Solutions at JAVA Program to Reverse an Array
def reverseList(A, start, end): while start < end: A[start], A[end] = A[end], A[start] start += 1 end -= 1 # Driver function to test above function A = [10, 20, 30, 40, 50] reverseList(A, 0, 4) print(A)
Find More Solutions at Python Program to Reverse an Array
48. 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))
49: Write a Program to find out the Spiral Traversal of a Matrix.
#include <stdio.h> #define r 4 #define c 4 int main() { int a[4][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int i, left = 0, right = c-1, top = 0, bottom = r-1; while (left <= right && top <= bottom) { /* Print the first row from the remaining rows */ for (i = left; i <= right; ++i) { printf("%d ", a[top][i]); } top++; /* Print the last column from the remaining columns */ for (i = top; i <= bottom; ++i) { printf("%d ", a[i][right]); } right--; /* Print the last row from the remaining rows */ if (top <= bottom) { for (i = right; i >= left; --i) { printf("%d ", a[bottom][i]); } bottom--; } /* Print the first column from the remaining columns */ if (left <= right) { for (i = bottom; i >= top; --i) { printf("%d ", a[i][left]); } left++; } } return 0; }
Find More Solutions at C Program to Find the Spiral Traversal of a Matrix
#include <bits/stdc++.h> #define r 4 #define c 4 using namespace std; int main() { int a[4][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int i, left = 0, right = c-1, top = 0, bottom = r-1; while (left <= right && top <= bottom) { /* Print the first row from the remaining rows */ for (i = left; i <= right; ++i) { cout<<a[top][i]<<" "; } top++; /* Print the last column from the remaining columns */ for (i = top; i <= bottom; ++i) { cout<<a[i][right]<<" "; } right--; /* Print the last row from the remaining rows */ if (top <= bottom) { for (i = right; i >= left; --i) { cout<<a[bottom][i]<<" "; } bottom--; } /* Print the first column from the remaining columns */ if (left <= right) { for (i = bottom; i >= top; --i) { cout<<a[i][left]<<" "; } left++; } } return 0; }
Find More Solutions at C++ Program for Spiral Traversal of a Matrix
import java.util.*; class Main{ static int R = 4; static int C = 4; static void print(int arr[][], int i, int j, int m, int n) { if (i >= m || j >= n) { return; } for (int p = i; p < n; p++) { System.out.print(arr[i][p] + " "); } for (int p = i + 1; p < m; p++) { System.out.print(arr[p][n - 1] + " "); } if ((m - 1) != i) { for (int p = n - 2; p >= j; p--) { System.out.print(arr[m - 1][p] + " "); } } if ((n - 1) != j) { for (int p = m - 2; p > i; p--) { System.out.print(arr[p][j] + " "); } } print(arr, i + 1, j + 1, m - 1, n - 1); } public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; print(a, 0, 0, R, C); } }
Find More Solutions at JAVA Program for Spiral Traversal of a Matrix.
50. 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))
FAQs on Most Asked Coding Questions in Placement
Question 1: What are the basics of coding?
The basics of coding are Data Types, Flow controls (loops) and functional programming.
Question 2: Which company has the hardest coding interview questions?
Product Based Companies like Google, Microsoft, Amazon ask the hardest coding interview questions.
Question 3: What language is used in coding?
Coding languages mostly used in placement exams are Java, C, C++ and Python.
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment