-3

I'm someone who started learning programming recently I'd like to ask Why the output isn't X = 6 X = 10

#include <stdio.h>

int main ()
{
    int x = 1;
    int y = 1;
    x = y++ * 5;
    printf("\nthe value of x is %d", x);

    y = 1;
    x = ++y * 5;
    printf("\nthe value of x is %d", x);
    return 0;
}

I tried changing values put it didn't help when I use y++ it doesn't increase And the output is x = 5 when using y++ shouldn't the output be x = 6

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • 1
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Filburt Aug 28 '23 at 16:29
  • 1
    Read your learning materials about pre-increment and post-increment operators. Add lines like `printf("\nthe value of y is %d", y);`. Note that normally you print a newline *after* your output, i.e. `printf("The value of y is %d\n", y);`. – Bodo Aug 28 '23 at 16:31
  • *And the output is x = 5 when using y++ shouldn't the output be x = 6* How can multiplying any integer value by the the `int` value 5 (`... * 5`) ever result in 6?? – Andrew Henle Aug 28 '23 at 16:33
  • 3
    Postincrement: `x = y++ * 5;` multiplies 1 × 5 and then increments `y` to `2`. Preincrement: `x = ++y * 5;` first increments `y` to `2` and then 2 × 5 = 10. – Weather Vane Aug 28 '23 at 16:33

1 Answers1

3

When you put the increment operator after the variable, it will add to that value after you use it. Whereas when you put it before, it will increment the value, then use the value of the variable in the line of code.

Refer to the following. Assume x = 1 and y = 1 for each block of code.

For y++:

x = y++ * 5;
// Is equivalent to:
x = y * 5; // x = 5
y = y + 1; // y = 2

For ++y:

x = ++y * 5;
// Is equivalent to:
y = y + 1; // y = 2
x = y * 5; // x = 10
Mitchell T
  • 106
  • 5