Project ForgeSign up free
Programming in C
Programming Fundamentals
GATE 2018
Hard

Consider the following C code. Assume that unsigned long int type length is 64 bits.

unsigned long int fun(unsigned long int n){
  unsigned long int i, j=0, sum=0;
  for (i=n; i>1; i=i/2) j++;
  for ( ; j>1; j=j/2) sum++;
  return(sum);
}

The value returned when we call fun with the input 2⁴⁰ is

  • A4
  • 5
  • C6
  • D40

Explanation

First loop halves i from 2⁴⁰ down through 2¹ (stopping once i≤1), executing once for each of i=2⁴⁰,2³⁹,...,2¹ — that's 40 iterations, so j=40. Second loop halves j from 40 down while j>1: 40→20→10→5→2→1, executing 5 times (for j=40,20,10,5,2), so sum=5.

Source: GATE CS 2018 (2018)

This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.

Start revising free