Coding Interview Questions for Freshers

Coding Interview Questions For Freshers

“Coding Interview Questions for Freshers”

Coding is the most primary and essential topic in  interview for top IT Company. For many years the coding has become an integral part of written placement exams and also face-to-face interviews to check the technical competencies of the student appearing.

Coding can be asked in 2 ways-

  • Oral manner- To  know the concept of the question and the steps that how ill you solve a particular problem.
  • Write and explain the whole code

Kindly Go through the full page for the same.

coding interview questions for freshers

Coding Domains

As a newcomer, answering technical questions head-on can be nerve-wracking, so to help you out, we’ve compiled a list of the most often asked Coding Interview Questions For Freshers. Coding can be asked in primarily four different languages. These are:-

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

Some companies can allow you to choose your preferred language and then ask you questions in that language. Some people do not agree.

It is not that you have to know all four languages.

But to clear a face-to-face interview you should know at least two coding languages. Don’t worry we are here to help you out in this and to provide you commonly asked Codin  Interview Questions For Freshers.

Most Viewed Questions

Coding Interview Questions For Freshers : In C

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

Answer:-

When the Header file is included within double quotes (“ ”), the compiler searches first in the working directory for the particular header file.

If not found, then it searches the file in the include path.

But when the Header file is included within angular braces (<>), the compiler only searches in the working directory for the particular header file.

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

Answer:-

A modifier is a prefix to a basic data form that indicates a storage space allocation update 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. Describe the newline escape sequence with a sample program?

Answer:-

The Newline escape sequence is represented by \n.

This indicates the point that the new line starts to the compiler and the output is created accordingly.

The following sample program demonstrates the use of the newline escape sequence.

/*
* C Program to print string
*/
#include 
#include 


int main(){
      printf("String 01 ");
      printf("String 02 ");
      printf("String 03 \n");


      printf("String 01 \n");
      printf("String 02 \n");
      return 0;
}
4. Write a C Program to Find the Sum of Natural Numbers using Recursion.

Answer:-

#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;

}

OUTPUT

Enter a positive integer: 20
Sum = 210

5. Write a C Program to Add Two Matrices Using Multi-dimensional Arrays

Answer:-

#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;
}

OUTPUT

Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:
Enter element a11: 2
Enter element a12 : 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23  : 3
Enter elements of 2nd matrix:
Enter element a11 : -4
Enter element a12: 5
Enter element a13 : 3
Enter element a21: 5
Enter element a22: 6
Enter element a23 : 3

Sum of two matrices:
-2    8     7

10    8     6

Interview Coding Questions for C++ language

1. 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 above Example,

Result = 10;

C = ‘A’;

These are valid definitions.

2. 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.

3. Explain Pass by Value and Pass by Reference.

Answer:-

While passing parameters to the function using “Pass by Value”, we pass a copy of the parameters to the function.

Hence, whatever modifications are made to the parameters in the called function are not passed back to the calling function.

Thus the variables in the calling function remain unchanged.

void printFunc(int a,int b,int c)
{
                  a *=2;
                  b *=2;
                  c *=2;
}

int main()

{

                 int x = 1,y=3,z=4;
                 printFunc(x,y,z);
                 cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
}

Output:

x=1
y=3
z=4

As seen above, although the parameters were changed in the called function, their values were not reflected in the calling function as they were passed by value.

However, if we want to get the changed values from the function back to the calling function, then we use the “Pass by Reference” technique.

To demonstrate this we modify the above program as follows:
void printFunc(int& a,int& b,int& c)
{
                              a *=2;
                              b *=2;
                              c *=2;
}
  int main()
{
                  int x = 1,y=3,z=4;
                  printFunc(x,y,z);
                   cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
}

Output:
x=2
y=6
z=8

As shown above, the modifications done to the parameters in the called functions are passed to the calling function when we use the “Pass by reference” technique.

This is because using this technique we do not pass a copy of the parameters but we actually pass the variable’s reference itself

4. What are virtual functions – Write an example?

Solution:-

Virtual functions are used with inheritance, they are called according to the type of the object pointed or referred to, not according to the type of pointer or reference.

In other words, virtual functions are resolved late, at runtime.

Virtual keyword is used to make a function virtual.

Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions)
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.

For example, in the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived class, because bp points to an object of Derived class.

#include
using namespace std;

class Base {
public:
virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base {
public:
void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp = new Derived; bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}

Output:

In Derived
5. Explain what are Operators and explain with an example?

Solution:-

Operators are specific operands in C++ that are used to perform specific operations to obtain a result.

The different types of operators available for C++ are Assignment Operator, Compound Assignment Operator, Arithmetic Operator, Increment Operator, and so on.

For example arithmetic operators, you want to add two values a+b

 
#include
Using namespace std;

main ()
{
int a= 21 ;
int b= 10 ;
int c;
c= a + b;
cout << "Line 1- Value of c is : " << c << endl ;
return 0;
}

It will give the output as 31 when you run the command

Coding Interview Questions : JAVA

1. What is a Class?

Answer:-

A Class is where all Java code is specified. There are factors and strategies in it.
Variables are attributes that characterize a class’s state.
Methods are where the specific business logic must be implemented. It consists of a series of statements (or) instructions that must be followed in order to meet the specific requirement.

Example:
public class Addition{ //Class name declaration
int a = 5; //Variable declaration
int b= 5;
public void add(){ //Method declaration
int c = a+b;
}
}

2. What is an Object?

Answer:-

An instance of a class is called an object. The object has a state and behavior.

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.

3. What is Inheritance? Explain with an example code.

Answer:-

Inheritance means one class can extend to another class. So that the codes can be reused from one class to another class.

The existing class is known as the Superclass whereas the derived class is known as a subclass.

Example:

Super class:
public class Manupulation(){
}
Sub class:
public class Addition extends Manipulation(){
}

Inheritance is applicable for public and protected members only. Private members can’t be inherited.

4. Write a Java Program to reverse a string without using String inbuilt function reverse().

Answer:-

There are several ways with which you can reverse your string if you are allowed to use the other string inbuilt functions.

In this method, we are initializing a string variable called str with the value of your given string.

Then, we are converting that string into a character array with the toCharArray() function. Thereafter, we are using for loop to iterate between each character in reverse order and printing each character.

public class FinalReverseWithoutUsingInbuiltFunction {
    public static void main(String[] args) {
        String str = "Saket Saurav";
        char chars[] = str.toCharArray(); // converted to character array and printed in reverse order
        for(int i= chars.length-1; i>=0; i--) {
   System.out.print(chars[i]);
    }
  }
}

Output:

varuaS tekaS

5. Write a Java program to print the Fibonacci series up to a given number or create a simple Java program to calculate Fibonacci number

Answer:-

import java.util.Scanner;

/**
 * Java program to calculate and print Fibonacci number using both recursion
 * and Iteration.
 * Fibonacci number is sum of previous two Fibonacci numbers fn= fn-1+ fn-2
 * first 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
 *
 * @author Javin
 */
public class FibonacciCalculator {

    public static void main(String args[]) {
    
       //input to print Fibonacci series upto how many numbers
        System.out.println("Enter number upto which Fibonacci series to print: ");
        int number = new Scanner(System.in).nextInt();
      
        System.out.println("Fibonacci series upto " + number +" numbers : ");
        //printing Fibonacci series upto number
        for(int i=1; i<=number; i++){
            System.out.print(fibonacci2(i) +" ");
        }
  
    
    } 
  

    /*
     * Java program for Fibonacci number using recursion.
     * This program uses tail recursion to calculate Fibonacci number 
     * for a given number
     * @return Fibonacci number
     */
    public static int fibonacci(int number){
        if(number == 1 || number == 2){
            return 1;
        }
      
        return fibonacci(number-1) + fibonacci(number -2); //tail recursion
    }
  


    /*
     * Java program to calculate Fibonacci number using loop or Iteration.
     * @return Fibonacci number
     */
    public static int fibonacci2(int number){
        if(number == 1 || number == 2){
            return 1;
        }
        int fibo1=1, fibo2=1, fibonacci=1;
        for(int i= 3; i<= number; i++){
           
            //Fibonacci number is sum of previous two Fibonacci number
            fibonacci = fibo1 + fibo2;             
            fibo1 = fibo2;
            fibo2 = fibonacci;
          
        }
        return fibonacci; //Fibonacci number
      
    }   
  
}
Output:
Enter number upto which Fibonacci series to print:
12
Fibonacci series upto 12 numbers :
1 1 2 3 5 8 13 21 34 55 89 144

Interview Coding Questions for Python language

1. How to overload constructors or methods in Python?

Answer:-

_init__ () is the first method of a class.

Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object. We can’t overload constructors or methods in Python.

It shows an error if we try to overload.

class student:

def __init__(self,name):

self.name = name

def __init__(self, name, email):

self.name = name

self.email = email

# This line will generate an error

#st = student(“rahul”)

# This line will call the second constructor

st = student(“rahul”[email protected])

print(st.name)

Output:

rahul
2. Give an example of shuffle() method?

Answer:-

This method shuffles the given string or an array.

It randomizes the items in the array. This method is present in the random module. So, we need to import it and then we can call the function. It shuffles elements each time when the function calls and produces different output.

import random
list = [12,25,15,65,58,14,5,]; print(list) random.shuffle(list) print (“Reshuffled list : \n”,  list)
[12, 25, 15, 65, 58, 14, 5] 
Reshuffled list :
 [58, 15, 5, 65, 12, 14, 25] 

3. 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.
4. Write a Python program to interchange first and last elements in a list.

Answer:-

Input : [12, 35, 9, 56, 24]

Output : [24, 35, 9, 56, 12]

Input : [1, 2, 3]

Output : [3, 2, 1]

def swapList(newList): 
size = len(newList) 

# Swapping 
temp = newList[0] 
newList[0] = newList[size - 1] 
newList[size - 1] = temp 

return newList newList = [12, 35, 9, 56, 24] 

print(swapList(newList)) 

OUTPUT:-
[24, 35, 9, 56, 12]


5. Python program to print even length words in a string.

Answer:-

Input: s = "This is a python language"
Output: This
        is
        python
        language 

Input: s = "i am muskan"
Output: am
        muskan


# even length words in a string

def printWords(s):

# split the string
s = s.split(' ')

# iterate in words of string
for word in s:

# if length is even
if len(word)%2==0:
print(word)

# Driver Code
s = "i am muskan"
printWords(s)

OUTPUT:
am
muskan