Output of Code is 114 I can't figure out why

108 views Asked by At

I'm new to programming and I'm learning about loops and if-else statements. For the code below, I need an explanation about why the final output is 114 when I run it in VSCode. I know that for the third iteration, since i=2, 2%2 is false, so it goes to the else section. one * two is supposed to be equal to 112. How did this become 114?? I know that total+= one*two is supposed to be total = total + one*two right? That's the definition of += operator. I just can't figure out why the output is 114 here. ChatGPT cant even answer.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define SZ 3 

int main(void)
{
    int i, one = 0, two = 0, total = 0;

    printf("Enter two whole numbers separated by a space: "); // user enters 56 2
    total = scanf("%d %d", &one, &two);

    for (i = 0; i < SZ; i++)
    {
        if (i % two) 
        {
            total = two + one / total;
        }
        else
        {
            total += one * two;
        }
    }

    printf("total is equal to %d\n", total);

    return 0;
}

I expected the code to get the output of 116 but it always gets the 114 answer. I've already corrected the condition.

2

There are 2 answers

3
BeemerBox On

It is the order of math operations. C++ follows the standard math operations that you would see in math.

total = two + one / total;

should be..

total = (two + one) / total;
4
Charley On

Let's consider the calculation of the program:

  1. As explained here (thanks to @John Omielan's comment), since we have total = scanf("%d %d", &one, &two);, and the input is 56 2, the initial value of one, two and total is 56, 2, 2.
  2. When i is 0, the program runs the else section, one * two equals to 112, so total is increased by 112, and now it's 2 + 112 = 114.
  3. When i is 1, the program runs the if section, two + one / total is 2 + 56 / 114. First, notice that operator/ is prior than operator+ in C, so it will be first calculated. Second, if the two numbers of the / calculation is both integers, the fractional part would be abandoned, so the result of 56 / 114 is 0. Then, the result of 2 + 56 / 114 is 2 + 0, and that's 2, so the value of total is now 2.
  4. When i is 2, the program runs the else section, one * two equals to 112, so total is increased by 112, because it was 2 before the addition, it should be 2 + 112 = 114 now.

In an conclusion, the key point is that because it was 2 before the addition, it should be 2 + 112 = 114 now, and don't forget that if you use operator+=, the program increases the variable by the value after the operater, but not just setting the variable to the value after the operator.