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%10);
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 ?
3
Answers
C != Python, you need to enclose all the statements into a
{}
block.is equivalent to
and you want
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:is parsed as:
To include multiple statements in a loop, you group them into a new compound statement using braces:
The code formed with
{ … }
is a single statement that is composed of any number of statements and declarations.To make this code snippet more readable
it may be equivalently rewritten like
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
This for loop
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
that is better again to rewrite for readability like
outputs the expression m % 10 then m after the for loop is equal to n + 1.