Table of contents
1.
Introduction
2.
Questions in C 
2.1.
C
2.2.
C
2.3.
C
2.4.
C
2.5.
C
3.
Questions in C++ 
3.1.
C++
3.2.
C++
3.3.
C++
3.4.
C++
3.5.
C++
4.
Questions in Java
4.1.
Java
4.2.
Java
4.3.
Java
4.4.
Java
4.5.
Java
5.
Questions in Python
5.1.
Python
5.2.
Python
5.3.
Python
5.4.
Python
5.5.
Python
6.
Frequently Asked Questions
6.1.
What is the left shift operator?
6.2.
How do you dereference a pointer?
6.3.
What is the right shift operator?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

What will be the output of the following code?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Output-based questions can be a useful tool for interviewers and employers to assess a candidate's programming skills, attention to detail, and problem-solving abilities.

If you have given any coding test, you must have seen such types of questions in your test. Hence, solving them in a short span of time makes your concept more clear. 

Candidates who can think critically and creatively may be better equipped to solve complex problems in their roles.

What will be the output of the following code?

So, in this article, we will be discussing such types of questions to give you a glimpse into how the questions can be asked. 

Let us start. 

Questions in C 

1. What will be the output of the following code in C? 

  • C

C

void main()
{
 int a = 1, b=2, c=3;
 char d = 0;
 if(a,b,c,d)
 {
   printf("EXAM");
 }
}
You can also try this code with Online C Compiler
Run Code


Ans - No Output


Explanation 

The comma operator is used in the if statement condition (a,b,c,d), which is why your program produces no output.

In C, the comma operator evaluates each of its operands (from left to right) and discards all but the last expression, which becomes the result of the entire expression.

In our case, it is d. As a result, the condition in the if statement is effectively the same as 

if(d) {...}

Since the value of d is set to 0, the if condition takes it as false (0), hence the program will not execute the if statement. 

As a result, no output will be printed on the screen. 
 

2. What will be the output of the following code in C? 

  • C

C

void fn() 
{
int a = 10;
static int b = 20;
printf("a = %d b = %d\n", ++a, ++b);
}

int main()
{
fn();
fn();
return 0;
}
You can also try this code with Online C Compiler
Run Code


Ans

a = 11 b = 21

a = 11 b = 22


Explanation 

In this program, inside the fn(), there are two variables one is local, and the other is static. As soon as the function call is made, the cursor will move to the implementation of the fn(). 

In the first call of fn() => The ++ operator increments the values of a and b by 1 before they are printed. 

So the first printf() call will print a = 11 and b = 21. 

Since the variables are declared inside the function, after each invocation to fn(), the values will be reset to the original values. That is the case with variable a, but not with variable b because it is declared static. So its value persists between function calls.  

The value of b in the second call to fn() is 21 (the value it was incremented to in the first call).

The second printf() call will print a = 11 and b = 22 because a is incremented again, but b retains its value of 21 from the previous call.

Therefore, the output of the program is a = 11 b = 21 followed by a = 11 b = 22.
 

3. What will be the output of the following code in C? 

  • C

C

#include <stdio.h>
int main()
{

 int i = 2, * j;
 j = & i;
 printf("%d", i ** j * i + * j);

 return 0;
}
You can also try this code with Online C Compiler
Run Code


Ans -  10 


Explanation 

Let us understand step-wise: 

Inside the main function, there are two variables declared: one is of integer type, and the other is of pointer type. 

i is assigned to 2, and j is assigned with the address of i. 

pointer

The following expression is being executed in the print statement: 

i ** j * i + * j

i ** j : Since j is a pointer variable, the * operator dereferences it to get the value stored in the memory location pointed to by j. So *j has the value 2.

The expression i * * j multiplies i by the value pointed to by j. 

Since j points to i, this is equivalent to i * i, which evaluates to 4

i ** j * i + * j evaluation

4. What will be the output of the following code in C? 

  • C

C

struct
{
 int si;
 double d;
 float cp;
} s;
void main ()
{
 printf ("%d, %d, %d",  sizeof (s.si), sizeof (s.d), sizeof (s.cp));
}
You can also try this code with Online C Compiler
Run Code


Ans - 4, 8, 4


Explanation 

The printf() function call uses the sizeof operator to get the size in bytes of each member of the s struct.

The sizeof operator returns the size in bytes of its operand. The size of an int is usually 4 bytes, the size of a double is usually 8 bytes, and the size of a float is usually 4 bytes.

Therefore, the output of the program is  4, 8, 4.
 

5. What will be the output of the following code in C? 

How many times will "Coding Ninjas" print? 

  • C

C

int main() 
{

 int x;

 for(x=-1; x<=10; x++)
 
 {
   if(x < 5)
     continue;

   else
     break;
   
   printf("Coding Ninjas");
 }
 
 return 0;
}
You can also try this code with Online C Compiler
Run Code


Ans - 0 times

Explanation 

If you notice, the cursor will not move to the print statement because of the conditions written above. The x variable starts with -1 and increments with 1 each time.

if(x < 5)

      continue;

It means the further statement will not get executed. As soon as the x variable becomes> 5, the next statement, i.e, 

    else,

      break;

terminates the loop, and hence no output will be printed. 

Also see,  Install Homebrew

Questions in C++ 

6. What will be the output of the following code in C++? 

  • C++

C++

#include<iostream>
int main()
{
  std::cout << "\"HelloWorld \"";
  return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Ans - "HelloWorld "


Explanation

The statement std::cout << "\"HelloWorld \""; prints the string "HelloWorld " to the console, with double quotes around it.

The backslash character (\) is used to escape the double quotes so that they are treated as part of the string and not as a syntax error.

7. What will be the output of the following code in C++? 

  • C++

C++

#include<iostream>
using namespace std;
int main()
{
  int x = 16;
  x = x >> 4;
  cout << x;
  return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Ans - 1


Explanation

The statement int x = 16; initializes the integer variable x with the value 16.

The statement x = x >> 4; performs a bitwise right shift operation on the value of x by 4 bits (i.e., it divides x by 2^4, which is equal to 16). 

The result of this operation is 1.
 

8. What will be the output of the following code in C++? 

  • C++

C++

#include<iostream>
using namespace std;
int main(){
  int a = 154;
  if(a & 0x01) {
     cout<<” Welcome to Coding Ninjas\n";
  }
  return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Ans - No output


Explanation

This code declares and initializes the integer variable a to 154. It then uses the bitwise AND operator & and the hexadecimal number 0x01(which is equivalent to the decimal number 1), to test the least significant bit of a.

If the least significant bit of a is 1 (i.e., a & 0x01 returns a non-zero value), then the if block will get executed. 

Nothing is output to the console if the least significant bit of an is 0 (i.e., a & 0x01 evaluates to 0).

Because the least significant bit of 154 is 0, the code will return 0 rather than output anything to the console.

9. What will be the output of the following code in C++? 

  • C++

C++

int main () {
  int a = 5768;
  int x = 10;
  int n;
 
  if(true) {
     n = x % 8 == 0 ? 8 : a % 8;
  } else {
     n = 0;
  }
 
  cout << n;
  return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Ans - 0 


Explanation 

If x % 8 is 0, the condition is true, and n is assigned the value 8; otherwise, a % 8 is assigned to n. 

In this case, 10%8 results in 2, which violates the condition. 

evaluation

Hence the output will be 0. 

10. What will be the output of the following code in C++? 

  • C++

C++

#include <iostream>
int main(int argc, const char * argv[]) {
   int a[] = {1, 2, 3, 4, 5, 6};
   std::cout << (1 + 3)[a] - a[0] + (a + 1)[2];
}
You can also try this code with Online C++ Compiler
Run Code


Ans - 8


Explanation

Let's break down the expression step by step:

(1 + 3)[a] is equivalent to a[4], because 1 + 3 is equal to 4, and a[4] is the fifth element of the array a, since array indices in C++ are 0-based.

a[0] is equal to 1, because it's the first element of the array.

(a + 1)[2] is equivalent to a[3], because a + 1 points to the second element of the array, and adding 2 to it gives a pointer to the fourth element, which is equivalent to a[3].

Putting it all together, the expression evaluates to:

a[4] - 1 + a[3]

which is equivalent to:

5 - 1 + 4

which evaluates to 8.
Therefore, the program will output 8.

 

Read about Bitwise Operators in C here.

Questions in Java

11. What will be the output of the following code in Java? 

  • Java

Java

import java.util.*;

   class Collection_iterators
   {
       public static void main(String args[])
       {
           LinkedList list = new LinkedList();
           
           list.add(new Integer(2));
           list.add(new Integer(8));
           list.add(new Integer(5));
           list.add(new Integer(1));
           
           Iterator i = list.iterator();
          
            Collections.reverse(list);

Collections.sort(list);
          
            while(i.hasNext())
            System.out.print(i.next() + " ");
       }
   }
You can also try this code with Online Java Compiler
Run Code


Ans - 1 2 5 8


Explanation 

A new LinkedList object called list is created, and four Integer objects are added to the list. 

The list now looks like this:

linkedlist

Next, Collections.reverse(list) is called. So, the list now looks like this: 

linkedlist

Finally, the Collections.sort(list) is called. The list will now be sorted in ascending order: 

linkedlist

12. What will be the output of the following code in Java? 

  • Java

Java

public class Base
{
   private int data;

   public Base()
   {
       data = 5;
   }

   public int getData()
   {
       return this.data;
   }
}

class Derived extends Base
{
   private int data;
   public Derived()
   {
       data = 6;
   }
   private int getData()
   {
       return data;
   }

   public static void main(String[] args)
   {
       Derived myData = new Derived();
       System.out.println(myData.getData());
   }
}
You can also try this code with Online Java Compiler
Run Code


Ans - 6


Explanation 

The Derived class extends the Base class, which means it inherits all the fields and methods of the Base class.  In this case, Base has a private field data that is set to 5 in its constructor and it also has a public method getData() that returns the value of data.

The Derived class has its own private field data, which is set to 6. It also has a private method getData() that returns the value of the data field it is referencing.

In the main method, when myData.getData() is called, the getData() method of the Derived class is called instead of the getData() method of the Base class. 

It is because of the private field that cannot be accessed outside of the Derived class. 

This method returns the value of the data field of the Derived class, which is 6. Therefore, the output of the code is 6.

13. What will be the output of the following code in Java? 

  • Java

Java

class overload 
  {
       int x;
double y;
       void add(int a , int b)
       {
           x = a + b;
       }
       void add(double c , double d)
       {
           y = c + d;
       }
       overload()
       {
           this.x = 0;
           this.y = 0;
       }       
   }   
   class Overload_methods
   {
       public static void main(String args[])
       {
           overload obj = new overload();  
           int a = 2;
           double b = 3.2;
           obj.add(a, a);
           obj.add(b, b);
           
           System.out.println(obj.x + " " + obj.y);    
       }
  }
You can also try this code with Online Java Compiler
Run Code


Ans - 4, 6.4


Explanation 

The add method of the overload class is called twice with different parameters:

  • The add method with integer parameters is called the first time, with an as both parameters. This changes x to 4 (i.e. 2 + 2).
     
  • The add method with double parameters is called again the second time, with b as both parameters. This makes y equal to 6.4 (3.2 + 3.2).
     

14. What will be the output of the following code in Java? 

  • Java

Java

class HelloWorld {
 public static void main(String[] args) {
   int[] arr1 = {1,2,3};
   int[] arr2 = {1,2,3};
   System.out.println(arr1 == arr2);
   System.out.println(Arrays.equals(arr1, arr2));
 }
}
You can also try this code with Online Java Compiler
Run Code


Ans

False

true


Explanation 

Arr1 == arr2 compares the object references of arr1 and arr2.

The output will be false because they are two different objects in memory.

Arrays.equals(arr1, arr2) compares the contents of the two arrays. 

The output will be true because the two arrays have the same elements in the same order.
 

15. What will be the output of the following code in Java? 

  • Java

Java

class HelloWorld {
 public static void main(String[] args) {
   
   int a = 5, b = 10;
   a = a ^ b ^ (b = a);
   
   System.out.println(a + " " + b);
 }
}
You can also try this code with Online Java Compiler
Run Code


Ans - 10 5


Explanation 

In the above code snippet, the bitwise exclusive XOR operator (^) is used to swap the values of the variables a and b without using a temporary variable.

a = a ^ b ^ (b = a)

Let us understand the above expression in detail: 

  • The initial values of a and b are 5 and 10, respectively.
     
  • The expression a ^ b evaluates to 15.
a ^ b evaluates to 15
  • The expression b = a assigns the value of a (which is currently 5) to b.
     

a ^ b evaluates to 15

  • Now, the final evaluation will be set to a. 

a ^ b evaluates to 15XOR operation

 

Therefore, the output is 10 5.

Questions in Python

16. What will be the output of the following code in Python? 

  • Python

Python

s1 = {1, 2, 3, 4, 5}
s2 = {2, 4, 6}
print(s1 ^ s2)
You can also try this code with Online Python Compiler
Run Code


Ans - 1 3 5 6


Explanation

The ^ operator is used to find the symmetric difference between two sets. 

The symmetric difference between two sets is a set of elements that are in 

either of the sets, but not in their intersection.

In the given code, s1 is a set containing the elements {1, 2, 3, 4, 5} 

and s2 is a set containing the elements {2, 4, 6}. Therefore, the 

symmetric difference between s1 and s2 can be computed are as follows:

s1 ^ s2 = (s1 - s2) | (s2 - s1)

        = ({1, 3, 5} | {6}) 

        = {1, 3, 5, 6}
 

17. What will be the output of the following code in Python? 

  • Python

Python

def foo(x):
   x[0] = ['def']
   x[1] = ['abc']
   return id(x)
q = ['abc', 'def']

print(id(q) == foo(q))
You can also try this code with Online Python Compiler
Run Code


Ans - True


Explanation

Here we have defined a function foo() that accepts a list x as an argument. 

Inside the function, x is modified by assigning ['def'] at index 0 and ['abc'] at index 1. 

And the memory address of the list x is returned using the built-in id() function.

Outside the foo(), there is a list q with elements 'abc' and 'def'

Then the memory address of the list q using id() function is compared with the foo(q).

foo(q) == id(q). 

Since, they have the same elements, hence the output will be true. 
 

18. What will be the output of the following code in Python? 

  • Python

Python

a = 3
b = 1
print(a, b)
a, b = b, a
print(a, b)
You can also try this code with Online Python Compiler
Run Code


Ans –  3 1

1 3


Explanation 

A is assigned with value 3 and b is assigned with 1. The first print() statement displays the value of a and b that is 3 1.

The expression b, a = a, b swaps the values of a and b by pushing them into a tuple (a,b), then unpacking them into a new tuple(b,a) and unpacking them finally into a and b. Now the value of a is 1 and b is 3. 

The second print statement displays the new value of a and b, that is 1 3. 
 

19. What will be the output of the following code in Python? 

  • Python

Python

def foo():
   try:
       return 1
   finally:
       return 2
k = foo()
print(k)
You can also try this code with Online Python Compiler
Run Code


Ans - 2


Explanation

Here inside the foo(), if the try block is executed then 1 will be returned. And, as we all know, the finally block will always get executed. 

So, when the function foo is called, 2 will be returned due to the functionality of finally block.  The return statement of finally will override the return statement of the try block.
 

20. What will be the output of the following code in Python? 

  • Python

Python

count = 0
while(True):
  if count % 3 == 0:
      print(count, end = " ")
  if(count > 15):
      break;
  count += 1
You can also try this code with Online Python Compiler
Run Code


Ans – 0 3 6 9 12 15


Explanation

In this code, the count is initialised with 0. Inside the while loop, if the count is a multiple of 3 it will print the count, and if the count is greater than 15, then the loop will terminate. Parallely, the count is incrementing by 1. 

Hence, the output is 0 3 6 9 12 15. All are multiples of 3, and as soon as it goes beyond 15, the break statement will get executed. 

Frequently Asked Questions

What is the left shift operator?

The left shift operator (represented by <<) shifts the bits of an integer to the left by a specified number of positions, filling the empty positions on the right with 0.

How do you dereference a pointer?

To dereference a pointer means to access the value stored at the memory location pointed to by the pointer. This can be done by using the asterisk (*) operator, for example: int x = *ptr;

What is the right shift operator?

The right shift operator (represented by >>) shifts the bits of an integer to the right by a specified number of positions, filling the empty positions on the left with 0 or 1, depending on the sign of the original number.

Conclusion

This article discusses predicting output-based questions provided in multiple languages in detail. 

Output-based questions can test basic programming concepts such as syntax, data types, and control structures. These questions can quickly assess whether a candidate has a solid foundation in programming. 

If you found this blog interesting and insightful, you can go through many guided paths that can help you understand the programming languages in an easier way: 

You can also refer to our Guided Path on Coding Ninjas Studio to upskill yourself in domains like Data Structures and AlgorithmsCompetitive ProgrammingAptitude, and many more! Refer to the interview bundle if you want to prepare for placement interviews. Check out interview experiences to understand various companies' interview questions.

Give your career an edge over others by considering our premium courses!

Live masterclass