Programming Interview Questions and Answers

By | May 28, 2020
Programming Interview Questions

Are you preparing for upcoming programming interviews? Here we have compiled a list of general programming interview questions and answers which will help you to prepare for coming job interviews.

Every year thousands of Computer Science graduates face the technical interviews organized by the IT companies for the role of Sr. or Jr. developers. Every big company like Amazon, Google, Facebook, Netflix, etc. who is hiring developers, make sure that the developer who has appeared for the interview stands on the expectation of the interviewer and the interviewer to make sure that the developer has the knowledge of programming from basics to advance. Programming interviews are designed to test the developer’s data structure, algorithms, logic, and problem-solving skills rather than developer knowledge on a specific programming language.

Vamware

50 Top Programming Interview Questions

Here in this article, we have mentioned top programming interview questions and answers, which give you a broad idea, what type of interview questions you could expect from the interviewer.

Question: Name the most common errors that can occur during the execution of a program?

Answer: 

  • Logical Error: If there is a mistake in the program source code, it could lead to a logical error. If there is a logical error in the program, then the output of the program could show unexpected behavior, or it could also crash the program itself. For instance, if we use the if (x=1) instead of if (x==1), this could raise a logical error.
  • Runtime Error: This error occurs during the runtime; it is also known as a compile-time error; the logic error is an example of runtime error.
  • Syntax Error: This error occurs if there is a mistake while writing code, for instance, if the developer forgets to put the semicolon at the end of the statement or the developer forgot to close any bracket.

Question: What is the difference between a Syntax error and Semantic error?

Answer: A syntax error occurs if there is a grammatical mistake in the code, which means if the code does not follow the writing rule of the program, then there would be a syntax error. If there is a syntax error in the program, the code will not compile.

Syntax Error Example:

for(int i=0; i< 10; i++)
{ 
    cout<<i;
    cout<<endl;
// syntax error because there is no closing curly brackets

The semantic error occurs during the execution of the code and after the code compilation. If the program returns an unexpected output, this means there is a semantic error in the code. incorrect variable types or sizes, non-existent variables, subscripts out of range, and the like, are some examples of semantic errors.

Semantic Error Example:

void fun (int a)

   {  a=b;  
   }
// We have not defined b

Question: How do you define an algorithm?

Answer: An Algorithm is a finite set of steps or instructions which can be used to solve a problem. An algorithm should be clear, efficient, unambiguous, and finite.

Question: What is a low-level programming language?

Answer: Low-level programming does not require any translator such as compiler or interpreter, and its code can be directly executed by the system processor. Machine code or binary code is an example of low-level programming.

Question: What is a high-level programming language?

Answer: A High-Level programming language is a human-readable language and does require a translator such as a compiler or an interpreter before the system processor could execute it.

Question: What are keywords?

Answer: Keywords are the reserved words used in the programming languages to perform a specific task, each programming language has a set of reserved keywords, for instance, C++ has 64 keywords, java has 51 keywords and python has 33.

Question: What are the loops?

Answer: Loop is a basic structure present in every high-level programming language which is used to repeat a defined set of statement again and again till the condition become False. There are three major types of Loops used in programming languages.

  • For Loop

Example:

for(int i=0; i<10; i++)
{   
    cout<<i;
    cout<<endl;
}
  • While Loop
int i=0; 
while( i < 10) {
      cout <<i;
      cout<<endl;
      a++;
   }
  • Do While Loop
int i = 0;
do {
  cout << i << "\n";
  i++;
}
while (i < 10);

Question: What is an Array?

Answer: An Array is a collection of similar elements where each element stored sequentially. Array use indexing to access its every element, and the indexing starts from 0 to n-1, where n is the total number of elements present in the array.

Question: What is Debugging?

Answer: It is a process of removing all the error and exceptions that occurred in the program during compile or runtime.

Question: What is the difference between break and continue statement?

Answer:

break continue
It ends or terminates the complete loop. It skips only one iteration.
It throws us out of the loop We will remain in the loop till the loop condition become false
It can be used when we have a specific condition from the loop, and we do not want more iteration. It used when we want to skip some specific conditions inside the loop,
It can be used with switch statements It can not be used with switch statements

Question: What are identifiers?

Answer: Identifiers are the names given by the programmer to a program element such as variable name, class name, function name, etc. According to all the high-level programming languages, there are some common set of rules to which need to follow by the programmer while naming any program element.

Question: Can we use a keyword as an Identifier?

Answer: No, we cannot use a keyword as an identifier; if we try to do so, then the compiler will throw a syntax error.

Question: What will happen if we use a break statement inside a nested loop?

Answer: If we use the break statement inside a nested loop, then the break statement breaks out us only from that loop where it is initialized. for instance, if we have a child loop inside a parent loop, and there is a break statement inside the child loop, if the compiler executes the break statement, then we would be thrown out from the child loop, but we remain in the parent loop. The outer loop will not be affected by the break statement if the break statement is inside the inner loop.

Question: What is a data structure?

Answer: Data Structure refers to a way or technique which is used to organize collective data in a specific manner. There are various data structures in the programming world, and each has its significance and operations.

To know more about Data Structure, Just read here.

Question: What is a linear and non-linear Data structure?

Answer: If all the elements in a data structure are organized sequentially than it would be considered as a linear data structure. Arrays, Linked list, queue, are the examples of Linear Data structure.

Linear Data Structure

In the non-linear data structure, all the elements are not organized sequentially. Graphs and trees are examples of non-linear data structures.

Non- Linear Data Structure

Question: When do we use for loop, and when do we use the while loop?

Answer: If we are sure about the number of times we want to execute a particular set of code, then only we use them for a loop.

If the number of executions of a set of code is not certain, then we use the while loop.

Question: Why to use Do While loop if we have While Loop?

Answer: When we want to execute a set of code at least one time, even the condition is False at the initial state, then we use the Do While loop.

Question: If the condition is False at the initial state, even so, Do While executes, but While not Why?

Answer: The Do-While first executes the code then checks the condition, but While the first check the condition, then execute the code; that’s why if the condition is False at initial state to Do While executing its code, but While do not.

Question: What is a Compiler?

Answer: A compiler is a computer program that acts as a translator, and its main job to convert one programming language to another. In programming languages, the compiler converts the High-Level programming language code to byte code or machine language.

Question: What is a Subroutine?

Answer: A subroutine is a sequential set of program instruction which is used to perform a specific task. In programming languages, we defined subroutines as procedures, functions, methods, or a subprogram. We can define a subroutine in the program itself or separately in a library.

Question: What is modeling languages?

Answer: It is a made-up language that is used to represent a piece of information, algorithm, or knowledge of a structure. We can either use the graphical or textual notation to represent a modeling language. The flowchart is a perfect example of modeling languages.

Question: What is the flow chart?

Answer: A flowchart is a graphical and pictorial representation of the program control flow. It is one of the modeling languages examples which is used to describe the algorithm of a particular program or syntax.

Example:

Flow Chart Example

Question: Give some examples of Modeling Languages.

Answer:

  • Business Process Modeling Notation
  • EXPRESS
  • Extended Enterprise Modeling Language
  • Flowchart
  • Fundamental Modeling Concepts
  • Jackson Structured Programming
  • Unified Modeling Language
  • Alloy (specification language
  • Systems Modeling Language

Question: What is maintaining and updating a program?

Answer: After the process of program planning, development, testing, and deployment, the maintenance of the program begins, in this process, we upgrade the program with new hardware and software, and try to improve the program with new features and eliminate the previous minor problems.

Question: What is a library?

Answer: A library is a collection of files that contain precompiled code such as routines, functions, methods, classes, etc. Every high-level programming language has many open source libraries that can be installed from the internet and plugged in our code.

Question: What is Documentation?

Answer: A Documentation could be a descriptive guide of a program, program algorithm, library, programming language, framework, coding method, testing, etc. In simple term, documentation of anything is a written report which provides all the public information and working function of the released project.

Question: What is the beta version of a software?

Answer: A beta version generally refers to an unstable version of the software which is still in the testing and up-gradation process. Companies release beta versions so they could get feedback from its customer on the release of its new features.

Question: How does a program get executed?

Answer: The computer understands only machine language so before the execution the compiler converts the human-written code into machine language, then the operating system transfer that machine code from the secondary memory to the primary memory(RAM), because the processors who execute the instructions are linked to the main memory.

Question: Why do we use the comment in a program?

Answer: A comment is used to specify the additional information about the code, the compiler or interpreter does not read the comment that’s why they do not get compiled or executed when we run our program.

Question: What do you understand by the DRY principle?

Answer: DRY stands for Don’t Repeat Yourself, and there are many programming languages, libraries, and frameworks which work on this principle. DRY states that there is no need to repeat code in a program, write it once, and use it anywhere throughout the program. DRY principle increases the code reusability and eliminates the repetition.

Question: What are constants in programming, and how many types of constants are there?

Answer: A value which can neither be changed during the execution of a program nor by the computer itself that value is known as constant, for instance, character ‘B’ is a constant value with an ASCII code 66.

There are two types of constants:

  • Numeric Constants
  • Character Constants

Numeric Constants:

Any digit or a sequence of digits in programming is a numeric constant, and there are different types of numeric constants too such as Decimal, Octal, etc.

Example: 

a= 10   // here a is variable and 10 is numeric constant.

Character Constant:

Any alphanumeric single, which is inside a single or double quotation it is a character constant. If there is a sequence of character, it would be a string character constant.

Example:

chr = 'a'   // here chr is variable and 'a' is charactere constant.
string = "Hello" // string is variable and "Hello" is string constant

Question: What are arithmetic operators, and on which data type can they operate?

Answer: Arithmetic operators are used to performing the mathematical arithmetic operation on numeric data types such as integers, float, double, etc.

Question: Where we use the relational operators and what value they return?

Answer: Relational operators are used to comparing two values, and they always return a Boolean value, either True or False.

Question: What is machine code?

Answer: A set of instruction which does not require any translator, and directly processed by the microprocessor. The Machine code generally presents in the binary form and consider as low-level code.

Question: What is software testing?

Answer: Software testing is a process in which the developed software goes through some testing criteria before it gets deployed. While testing software, many criteria test the reliability, efficiency, and interactivity of the software.

Question: What is bubble sort, and what’s its time complexity?

Answer: Bubble sort is a sorting algorithm, in which we repeatedly swap the adjacent elements if they are in the wrong order.

The time complexity of Bubble sort is O(n2)

Question: List the significant Sorting Algorithms with their time complexities.

Answer:

Algorithm Time Complexity
  Best Average Worst
Selection Sort Ω(n^2) θ(n^2) O(n^2)
Bubble Sort Ω(n) θ(n^2) O(n^2)
Insertion Sort Ω(n) θ(n^2) O(n^2)
Heap Sort Ω(n log(n)) θ(n log(n)) O(n log(n))
Quick Sort Ω(n log(n)) θ(n log(n)) O(n^2)
Merge Sort Ω(n log(n)) θ(n log(n)) O(n log(n))
Bucket Sort Ω(n+k) θ(n+k) O(n^2)
Radix Sort Ω(nk) θ(nk) O(nk)

Question: Write a function that can count the occurrence of a given character in a String.

Answer:

int count_character(string s, char chr)
{
    // Count variable
    int count = 0;
    for (int i=0;i<s.length();i++)
        // checking character in string
        if (s[i] == chr)
            count++;
    return count;
}

Question: Write an Algorithm for Counting Sort.

Answer:

Counting_Sort(array, size)    // counting sort function which accept an array and its size
maxi <- max(array)   //the largest element from the array
count[size]   // initialize an array count which all elements are zero

for j 0 to size
            find the total count of each unique element and store the count at jth index in count array
for i 0 to maxi
            find the cumulative sum and store it in count array itself
for j <- size down to 1
            restore the elements to array decrease count of each element restored by 1

Question: Write the logic which can remove the duplicate element from a sorted array, and the time complexity of the program should be O(N), where N is the total number of elements present in the array.

Answer:

if (n==0 || n==1) // check for the base case if the size of array is 1 or 0
        return n;
 else
 {
     int temp[n];   // create a temporary array temp which size is similar to original array array
    // Start traversing elements
    int j = 0;
    for (int i=0; i<n-1; i++)
         // this If statement make sure that only unique elements of the array arr
         // store in temporary array temp
        if (arr[i] != arr[i+1])
            temp[j++] = arr[i];

    // Store the last element as whether
    // it is unique or repeated, it hasn't
    // stored previously
    temp[j++] = arr[n-1];

    // Modify original array
    for (int i=0; i<j; i++)
        arr[i] = temp[i];
    }

Question: Write a function that can reverse an array in place, and the time complexity of the program should be O(N).

Answer:

 void Array_Reverse(int arr[], int front, int back)

{
    int temp;
    while (front < back)
    {
        // swapping the back element of the array with the front elements
       //with each iteration till the front < back
        temp = arr[front]; 
        arr[front] = arr[back];
        arr[back] = temp;
        front++;
        back--;
    } 
}

Question: How to swap two numbers without using a third variable?

Answer:

int a, b;
a= 30;
b=40;


a= a+b;   // now a = 70
b= a-b;   // now b =30
a= a-b;    // now a =40

Question: What is the difference between Stable and Unstable sorting algorithms?

Answer:

The sorting algorithm will be termed as a stable sorting algorithm if the algorithm maintains the relative order of elements even after the sorting. If the algorithm changes the relative order of the elements, then it would be considered as an unstable sorting algorithm.

Question: Add two numbers without using arithmetic + operator.

Answer:

int Addition(int a, int b) 
{ 
    while (b != 0) 
    { 
        int carry = a & b; 
        a = a ^ b; 
        b = carry << 1; 
    } 
    return a; 
}

Question: How do you check if two rectangles overlap with each other?

Answer: We can represent a rectangle by two coordinates top left(ln) and bottom right(rn).

Rectangle 1 with coordinates point l1, and r2,

Rectangle 2 with coordinates point l2 and r2

bool Overlap(Point l1, Point r1, Point l2, Point r2)
{
    // If one rectangle is on left side of other
    if (l1.x >= r2.x || l2.x >= r1.x)
        return false;
    // If one rectangle is above other
    if (l1.y <= r2.y || l2.y <= r1.y)
        return false;
    return true;
}

Question: Differentiate between Linked-List and Array.

Answer:

Array Linked List
The array contains elements of similar data type Linked List contains heterogeneous elements
Array use indexing, which makes it easy to access every element. Linked List does not have indexing to access the elements of a linked list; we have to traverse from its initial node.
Insertion and Deletion operation in an Array is costly. It is very easy to insert and remove nodes from a linked list.
Array Occupy a contiguous memory. Linked list nodes occupy random free memory locations.
The array comes with a fixed size. The linked list is very flexible, and its size can be increase and decrease quickly.

Question: What is the efficient way to insert a new node in the middle of a linked list?

Answer: We can use the tortoise and hare algorithm; in which we use two pointers. One is fast. Another is slow. The quick pointer moves two steps at a time while the slow pointer moves 1, so at the time the quick tip is at the end of the linked list the slow pointer would be in the middle, and using the slow pointer we will insert the new node in the linked list.

Question: Use any programming language and print the reverse of a string using recursion.

Answer:

#python

def reverse(string):
    if len(string) == 0:
        return
    temp = string[0]
    reverse(string[1:])  #recursion
    print(temp, end='')

string = "TechGeekBuzz"
reverse(string)

Question: You have given a linked list now to create a function that could tell whether the given linked list contains a cycle or not.

Answer:

Procedure: Traverse through the list nodes one by one and keep putting the address of each node in a data structure, while traversing through the list if you hit a node which points to a NULL or NONE value then return false else if you run a node which points to a visited node whose address is present in the data structure then return True.

Python:

def Contain_Cycle(head):
    ds = set()
    temp = head
    while (temp):
    
        if (temp in ds): #if the node is present in the data structure
            return True

        ds.add(temp)
        temp = temp.next
    return False

Question: What are the major points we need to take care of when we implement a BST(Binary Search Tree)?

Answer:

  • The left subtree key node value must be less than its parent node.
  • The right subtree key node value must be higher than its parent node.
  • The left and right subtree each must also be a binary search tree.
  • There must be no duplicate nodes.

Question: What do you understand by the Binary tree traversal?

Answer:

Unlike other data structures, we have various methods to traverse through binary tree nodes. There are three major traversal Algorithms we can follow to traverse through each node of a binary tree.

  • Inorder traversal (Left Root Right)
  • preorder traversal(Root Left-Right)
  • postorder traversal(Left-Right Root)

Question: Give the algorithm for Inorder traversal.

Answer:

  • First, traverse the left subtree(recursively).
  • Visit and print the root node.
  • Traverse through right Subtree(recursively)

Question: What is the algorithm for Inorder Tree Traversal without Recursion?

Answer:

  • Create stack S.
  • Create a temp node from the root node, such as temp = root.
  • Push the temp node to the stack S and change the temp node with the left node of the temp such as temp = temp-> left_node_of_temp
  • Set an IF statement, If the temp is NULL or NONE and Stack S is not empty then:
    • pop the item from the stack
    • print the pop item and set the temp node as the popped right node such as temp = popped_item->right
    • Now Push the temp node to the stack S and change the temp node with the left node of the temp such as temp = temp-> left_node_of_temp
  • If the temp is NULL and the stack is empty then we are done.

Conclusion

Here all the questions we have mentioned are the primary and top programming interview questions and answers. We hope you go through these questions first before you go for the interview. During the interview, your necessary programming skills would be tested more than your advance knowledge in a specific aspect of programming, so you should have a good understanding of Programming, data structure, and algorithms.

You may be also interested in:

Leave a Reply

Your email address will not be published. Required fields are marked *