Home > OS >  Why do I get a different result when I add an assignment statement?
Why do I get a different result when I add an assignment statement?

Time:11-11

Below is my code.
Work on Debian/testing ,use gcc version 11.2.0 (Debian 11.2.0-10).

#include <stdio.h>

int main(void)
{
    int i, n, m;

    printf("Input a number:");
    scanf("%d", &n);

    for (m = 1; m <= n; m  )
        i = m%10;
        printf("%d", i);
        //printf("%d", m);

    return 0;
}

I input 25 to n.


if i use

for (m = 1; m <= n; m  )
        i = m%10;
        printf("%d", i);

The result is 5.


If I use

for (m = 1; m <= n; m  )
        printf("%d", m%10);

The result is 1234567890123456789012345.


If I use

for (m = 1; m <= n; m  )
    i = m%10;
    printf("%d", m%10);

The result is 6.


What is the difference between them ?

CodePudding user response:

C != Python, you need to enclose all the statements into a {} block.

for (m = 1; m <= n; m  )
        i = m%10;
        printf("%d", i);

is equivalent to

for (m = 1; m <= n; m  )
{
    i = m%10;
}
printf("%d", i); // 25 % 10 = 5

and you want

for (m = 1; m <= n; m  )
{
    i = m%10;
    printf("%d", i);
}

CodePudding user response:

C does not use tabs or other indentation to group statements. Each loop, such as for (m = 1; m <= n; m ), includes exactly one statement. So this code:

    for (m = 1; m <= n; m  )
            i = m%10;
            printf("%d", i);

is parsed as:

    // A loop with one statement.
    for (m = 1; m <= n; m  )
        i = m%10;

    // A separate statement.
    printf("%d", i);

To include multiple statements in a loop, you group them into a new compound statement using braces:

    for (m = 1; m <= n; m  )
    {
        i = m%10;
        printf("%d", i);
    }

The code formed with { … } is a single statement that is composed of any number of statements and declarations.

CodePudding user response:

To make this code snippet more readable

for (m = 1; m <= n; m  )
        i = m%10;
        printf("%d", i);

it may be equivalently rewritten like

for (m = 1; m <= n; m  )
        i = m%10;
printf("%d", i);

So the call of printf after the for loop outputs the last value stored in the variable i when m is equal to n that is 5.

If you wanted to include the statement with the call of printf in the body of the for loop you could use the compound statement like

for (m = 1; m <= n; m  )
{
        i = m%10;
        printf("%d", i);
}

This for loop

for (m = 1; m <= n; m  )
        printf("%d", m%10);

execute the statement with the call of printf in each iteration of the loop for the variable m in the range [1, n].

This code snippet

for (m = 1; m <= n; m  )
    i = m%10;
    printf("%d", m%10);

that is better again to rewrite for readability like

for (m = 1; m <= n; m  )
    i = m%10;
printf("%d", m%10);

outputs the expression m % 10 then m after the for loop is equal to n 1.

  •  Tags:  
  • c
  • Related