Explaining output from a C program

I am not being able to explain the output from the program below. It seems to be highly compiler dependent.

gcc 4.7.2 --> Random output on each run
gcc 4.8.2 --> 0.00

#include <stdio.h>

int main()
int z;
int i = 4;
int x = 6;
z = x / i;
printf(“z=%.2f\n”, z);
return 0;

You should take z in float data type which would round off x/i to nearest integer which is 1.00.
Happy coding!!!


look at this link

1 Like

its quite simple
since z=x/i which means z=6/4, therefor remainder will be 0, therefore z=0
since u have used printf(“z=%.2f\n”, z);
z=%.2f this means it show z value and decimal point upto 2 digits…

if u use %.5f that means it will show decimal point upto 5 digits…

therefore output will be z=0.00

bro i know that it is not a modulus operator but compiler will give output z=0.00 as deafult. even if u use % then also output will be same… the reason behind is u r using ‘int’ instead of that use ‘float’ then it will give 1.00 output

i dont need any online compiler… if u want u can try yourself (holmessherlock)…

what are the output difference you get on executing from both this compilers?

Actually I tried four compilers, Ideone and Codepad outputs are linked in my original post. Also, please find the other two in the same line. I’m sorry for not being able to format properly in this editor. It seems to strip off all newlines.

It’s not about correcting the code snippet. It’s a tricky question appearing on an interview website.

gcc 4.8.2 produces 0.00. But there are other outputs. Please have a look at the second line of my original post.

It’s not a modulus operator.

Please re-read.

yeah i don’t know a lot about gcc 4.7.2 but i think program should execute something like this z=4/6 = 0(integer division)
then when it is printed to 2 precision output would be 0.00 what exactly did they ask in the question ?

I think (read it as I firmly believe) that 6/4 produces 1 in Integer division.

Dude, please take the pain of copy pasting the code to any online compiler.

Anyway, I have done the tough job on your behalf.

sorry read it wrong. i tried it in vc++ seems like when using %.2f and using an integer as second parameter would print 0.00

check my answer.

That’s the problem. It turns out to be highly compiler dependent while it must not be.