Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Programming Interview Questions and Answers

Programming Interview Questions and Answers

“Programming Interview Questions and Answers”

Many top IT recruiters or MNCs hiring for Computer Engineering Graduates are now taking the support of programming questions in the interview to test the coding and programming skills of the candidate appearing.

Here we will share some frequently asked programming interview questions from interview point of view for programmers at different levels of experience but this is basically for people who have just graduated from college.

Click on the button below to have a look on Technical Interview Question and Answer.

programming interview questions and answers

More About Programming : Introduction

On this page we will be providing you all with the top and most asked programming interview questions.

Questions can be majorly answered in 4 languages but only depends on the interviewer if he/she allows answering in your preferred language. These languages are:-

  1. C
  2. C++
  3. JAVA
  4. Python

Companies like Amazon, Google, and Microsoft are always on the search to enroll and hire  programming and software development talent to join their companies.

To get placed in MNC’s like Amazon, Google and Microsoft you must have a deep knowledge on Programming. Go through the page in detailed to know more about Programming Interview Questions and Answers.

Keeping in mind your perspective, we have shortlisted few commonly asked programming interview questions and answers that are commonly asked in Interview Exams.

Commonly Asked Programming Interview Questions and Answers

Question: Write code to check a String is palindrome or not?

#include <stdio.h>
#include <string.h>

// A function to check if a string str is palindrome
void 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")

Question: Write a program for Binary to Decimal to conversion

/** C program to convert the given binary number into decimal**/
#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 <iostream>
#include <math.h>
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))

# This code is contributed by Shubhanshu Arya (Prepinsta Placement Cell Student) 

Question:  Check whether a character is a vowel or consonant :

#include <stdio.h>
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")

Question:  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();
}
}

Question:   Write a code to find Find the ASCII value of a character

/* C Program to identify ASCII Value of a Character */
#include<stdio.h>
#include<conio.h>  
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 identify ASCII Value of a Character */
#include<stdio.h>
#include<conio.h>  
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)

Question:   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)

Question:   Write a code

//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))

Most Asked Programming Interview Questions and Answers.

1. What is the behavioral difference when the header file is included in double-quotes (“”) and angular braces (<>)?

Answer:-

When the Header file is enclosed in double quotes (“ ”), the compiler looks for the header file in the working directory first. If the file isn’t located, it looks in the include directive. When the Header file is enclosed in angular braces (>), however, the compiler only looks for the header file in the working directory.

2. Describe the modifier in C? With an Example;

Answer:-

A modifier is a prefix to the basic data type which is used to indicate the modification for storage space allocation to a variable.

Example– In a 32-bit processor, storage space for the int data type is 4.When we use it with modifier the storage space change as follows:

  • Long int: Storage space is 8 bit
  • Short int: Storage space is 2 bit
3. Difference between Declaration and Definition of a variable.

Answer:-

The declaration of a variable is merely specifying the data type of a variable and the variable name.

As a result of the declaration, we tell the compiler to reserve the space for a variable in the memory according to the data type specified.

Example:
int Result;
char c;
int a,b,c;

All the above are valid declarations.

Also, note that as a result of the declaration, the value of the variable is undetermined.

Whereas, a definition is an implementation/instantiation of the declared variable where we tie up appropriate value to the declared variable so that the linker will be able to link references to the appropriate entities.

From the above Example,

Result = 10;

C = ‘A’;

These are valid definitions.

4. How do you define/declare constants in C++?

Answer:-

In C++, we can define our own constants using the #define preprocessor directive.

#define Identifier value

Example:

#include
#define PI 3.142
int main ()
{
                 float radius =5, area;
                 area = PI * r * r;
                 cout<<”Area of a Circle = “<<area;
}
Output: Area of a Circle = 78.55

As shown in the above example, once we define a constant using #define directive, we can use it throughout the program and substitute its value.

We can declare constants in C++ using the “const” keyword. This way is similar to that of declaring a variable, but with a const prefix.

Examples of declaring a constant

const int pi = 3.142;
const char c = “sth”;
const zipcode = 411014;

In the above examples, whenever the type of a constant is not specified, the C++ compiler defaults it to an integer type.

5. What is an Object?

Answer:-

An object is a representation of a class instance. The entity has a state and behaves in a certain way.

Whenever the JVM reads the “new()” keyword then it will create an instance of that class.

Example:

public class Addition{
public static void main(String[] args){
Addion add = new Addition();//Object creation
}
}

The above code creates the object for the Addition class.

6. What are the different file processing modes supported by Python?

Answer:-

Python provides three modes to open files. The read-only, write-only, read-write, and append mode.

‘r’ is used to open a file in read-only mode, ‘w’ is used to open a file in write-only mode, ‘rw’ is used to open in reading and write mode, ‘a’ is used to open a file in append mode. If the mode is not specified, by default file opens in read-only mode.

  • Read-only mode : Open a file for reading. It is the default mode.
  • Write-only mode: Open a file for writing. If the file contains data, data would be lost. Another new file is created.
  • Read-Write mode: Open a file for reading, write mode. It means updating mode.
  • Append mode: Open for writing, append to the end of the file, if the file exists.

7. Can I create a customized Head File in C language?

Answer:- 

It is possible to create a new header file.

Create a file with function prototypes that need to be used in the program. Include the file in the ‘#include’ section in its name.

8. Which statement is efficient and why? x=x+1; or x++; ?

Answer:- 

x++; is the most efficient statement as it just gives a single instruction to the compiler while the other is not.

9.  What are the limitations of scanf() and how can it be avoided?

Answer:- 

 The Limitations of scanf() are as follows:

  • scanf() cannot work with the string of characters.
  • It is not possible to enter a multiword string into a single variable using scanf().
  • To avoid this the gets( ) function is used.
  • It gets a string from the keyboard and is terminated when enter key is pressed.
  • Here the spaces and tabs are acceptable as part of the input string.

10. Differentiate between the macros and the functions.

Answer:- 

The differences between macros and functions can be explained as follows:

  • Macro call replaces the templates with the expansion in a literal way.
  • The Macro call makes the program run faster but also increases the program size.
  • Macro is simple and avoids errors related to the function calls.
  • In a function, call control is transferred to the function along with arguments.
  • It makes the functions small and compact.
  • Passing arguments and getting back the returned value takes time and makes the program run at a slower rate.

Few

Important Pages to check:

Click on the button provided to visit few more Technical Interview Pages commonly asked during Interview.