Skip to content
GATEiit

GATE CSE 2019 Q62: Number of times sum is printed in a float halving loop

Syllabus topic: Programming in C

Question

Consider the following C program:

#include <stdio.h>
int main(){
   float sum = 0.0, j = 1.0, i = 2.0;
   while (i/j > 0.0625){
         j = j + j;
         sum = sum + i/j;
         printf("%f\n", sum);
   }
   return 0;
}

The number of times the variable sum will be printed, when the above program is executed, is ________.

Try it: numerical answer: type the value

Numerical answer. No negative marking.
Show answer and explanation

Answer: 5 (official GATE 2019 final answer key)

Concept used: Each iteration doubles j, so i/j halves; the body runs once for each value of i/j (checked before doubling) that is strictly greater than 0.0625, and these powers of two are exact in float.

Concept notes

Loading notes…

First step: List the values of i/j tested by the while condition: 2, 1, 0.5, …, and count how many are strictly greater than 0.0625.

Full step-by-step solution

Loading…

Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.

More questions on Programming in C

Every PYQ on this topic →

Share this question

WhatsAppDownload image

Source: official GATE 2019 CS question paper and final answer key, organised by IIT Madras. Question paper · Answer key