(c language) Numeric Count Question (++) printf If you specify cnt++; outside the sentence, and printf("%d", cnt++), the result will be different.

Asked 1 years ago, Updated 1 years ago, 338 views

We are coding to count the number of lines and the corresponding numbers.

For example, if you enter 5, the calculation is

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

The coding that results in this way.

First, you specified the count variable as cnt.

However, if you specify cnt++; outside the printf sentence and printf("%d",cnt++), the result will be different.

I wonder why.

Below is the coding I did.

    int n,cnt=1;
    scanf_s("%d", &n);

    for (int a = 1; a <= n; a++) {
    for (int b = 1; b <= a; b++) {
        printf("%d",cnt++); //If you insert cnt++ here, it should be initialized to cnt=1.
    }                        // If you just put cnt++; above, it is cnt=0.
    printf("\n");
    }

But here,

    cnt++;
    printf("%d", cnt)

in the case of You need to initialize cnt to 0 to get the above results.

As above

    printf("%d ",cnt++);

In this way, cnt should be initialized to 1 to get the above result.

I wonder how there is a difference of 1.

c

2022-10-29 00:01

1 Answers

The ++ operator increases the variable value by 1 when used alone, but when used in other sentences, it affects the order of evaluation of sentences.

The ++ operator can be put before or after a variable, and the order of evaluation varies.

printf("%d ",cnt++);

One line of code above is treated the same as the two lines of code below in a typical compilation environment.

printf("%d ",cnt);
cnt++;

That is, after outputting the current cnt value on the screen, the cnt value increases by 1.

In the question, the printf("%d",cnt++);code also increased after the current cnt value was output, so you had to initialize cnt to 1 to output from 1.

On the other hand, in the question

cnt++;
printf("%d", cnt);

In this case, the cnt value should be increased by 1 and then the cnt should be output from 1, so the output value should be increased by 1 and then the output value should be 1, so the cnt had to be initialized to 0.

For your information, printf("%d ",cnt++); To avoid misunderstanding rather than writing like this, the two-line code below is better written.

printf("%d ",cnt);
cnt++;


2022-10-29 00:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.