-5

Hello pro coders of stackoverflow community, I'm still a beginner and I need help understanding the problem below:

int main()
{
    int x=4,y=0;
    while(x>=0)
    {
        if(x==y)
            break;
        else
            printf("\n%d%d",x,y);
        x--;
        y++;
    }
}

How and why is the output 40 and 31, thanks in advance

  • Please post code as text, not a picture of text and **not** a link to a picture of text. Just copy and paste the code here so others can do the same to reproduce your problem. – dbush Mar 11 '19 at 18:06
  • Also, asking "why is this the output" is too broad. What exactly are you confused about? What do you expect the output to be and why? – dbush Mar 11 '19 at 18:07
  • okay thanks, got it now. only joined a few minutes ago no need to rip me apart :p – GlitchInTheMatrix Mar 11 '19 at 18:09
  • 1
    I would recommend reading [How To Ask](https://stackoverflow.com/help/how-to-ask) so you can ask better questions in the future. – Mercury Platinum Mar 11 '19 at 18:38
  • 2
    Actually questions on a simple program like this that could be answered by either using a debugger to examine the program flow and variables, or even by adding `printf("x=%d, y=%d\n", x, y);` at the beginning of the loop are considered invalid when very obvious to answer. – U. Windl Mar 11 '19 at 19:25

3 Answers3

3

X will start out at 4 and Y at 0. Since they are not equal the program will print those values. The second iteration has X at 3 and Y at 1. Again the program will print them. On the third iteration, both X and Y are 2, and so the program will break from the loop and won't print.

Jenks
  • 53
  • 8
1

To better understand why the program outputs something that you did not expect, try to find the reason by playing with printf and getting understanding of each of the value you would like to print.

For example here you can try the following:

int main()
{
    int x=4,y=0;
    while(x>=0)
    {
        if(x==y)
            break;
        else
            printf("x is: %d\n", x);
            printf("y is: %d\n", y);
        x--;
        y++;
    }
}

Hope it helps

Alexey N.
  • 13
  • 4
0

Your program only prints twice and loops three times.

On the first run, it prints 40 because X=4 and Y=0. Then X decrements (x--) and Y increments (y++). X is now 3 and Y is now 1.

On the second run, it prints 31 because X=3 and Y=1. Then X decrements again (x--) and Y increments again (y++). X is now 2 and Y is now 2.

On the third run, the program breaks because X=2 and Y=2.

clay
  • 1,757
  • 2
  • 20
  • 23