0

I have this simple problem:

# include <stdio.h>
int main(){
    unsigned a, b, x, y, temp;  
    a=100;
    b=30;
    
    x=a*b;
    printf("%u", x);
    while(b) temp=a%b, a=b, b=temp; // try to comment this line
    y=b;
    x/=y;
    printf("%u", x);
    return 0;
}

If I put this code into main.c it returns "Program finished with exit code 0", and there will be no printf, else if I comment the while loop I will get the printfs.

Can you explain why the while loop influences the program this way? What actually I should achieve with this problem is the division by 0 at the final line x/=y;.

Good Luck
  • 113
  • 6
  • 5
    If *ever* there were a candidate for running in a *debugger* step-by-step, this is it. You'd find out very quickly that `temp = a % b, a = b, b = temp;` is not doing what you think it is. Every single on of those commas should be `;` and all of that should be enclosed in a pair of `{ }`. See [What does the comma operator do?](https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do). Fair warning, the only way that while-loop terminates is when `b` is zero, which you then, indirectly through `y`, use as the divisor in `x/=y`. That's going to trip a div-by-zero error. – WhozCraig May 05 '22 at 16:59
  • @WhozCraig I think in this case the while loop body is quite equivalent to if it was written `{ ... ; ...; ... }` manner. Am I missing something? – Eugene Sh. May 05 '22 at 17:06
  • @EugeneSh. Each one of those is a sequence point on the comma, so yea, it should work, it's just hideous. The explosion from the div-zero is what is killing the output (which would be picked up by the debugger the OP isn't using). – WhozCraig May 05 '22 at 17:09
  • You need to learn to name your variables sensibly, too. For such a small program to be so arcane takes real skill. – Lee Taylor May 05 '22 at 17:13
  • @WhozCraig do you think that `x/=y` line is ever reached? Why don't I get div by zero error message in this case? – Good Luck May 06 '22 at 05:24
  • 1
    It is absolutely reached. It is what is terminating your program. *Run your code in a debugger*. If you don't know how to, *learn*. You'll spend half you're engineering life staring at a debugger and scratching your head (I'm *not* exaggerating). the sooner you learn to use one effectively the better, and this program is *ideal* to do so. – WhozCraig May 06 '22 at 05:52

1 Answers1

0

Put fflush(stdout); after each printf() call.

When the division by 0 is occured, the program will abort without flushing contents in output buffer.