0

I've got some code here:

int n = 0;
for(n = 1;n<4;n++)
printf("%d",n);
return 0;

Why does it return '123' instead of just '3'?

I tried to Google for this issue, but I couldn't find anything useful.

cocomac
  • 518
  • 3
  • 9
  • 21
randanee
  • 21
  • 2
  • 3
    The loop iteration contains one statement (even though not indented). The first loop prints `1`. The second loop prints `2`. The third loop prints `3`. You left no gap in between. BTW it isn't 'returning' what you think. `printf` returns the number of characters output. – Weather Vane Feb 08 '23 at 19:25
  • @randanee Why would you expect code which starts at n = 1, and iterates by 1 to n = 4, while printing on each iteration where n < 4, to only print once? – Douglas B Feb 08 '23 at 19:36
  • ... as in `int retval = printf("randanee"); printf("\n%d\n", retval);` which should output your name and `8`. – Weather Vane Feb 08 '23 at 19:50

1 Answers1

5

After asking my question, I think I see what you are getting at.

What you have with

    int n = 0;
    for(n = 1;n<4;n++)
        printf("%d",n);
    return 0;

is functionally the same as

    int n = 0;
    for(n = 1;n<4;n++)
    {
        printf("%d",n);
    }
    return 0;

Since the for loop expects a statement, either a block of statements enclosed in braces, or a single one terminated with a semicolon as you have in your example. If you wanted it to just print 3 and for whatever reason wanted to use a loop just in increment a number, you would want to provide it with an empty statement as such:

    int n = 0;
    for(n = 1;n<3;n++);
    printf("%d",n);
    return 0;

or

    int n = 0;
    for(n = 1;n<3;n++){}
    printf("%d",n);
    return 0;

Both of which will only print 3.

Please note that because the variable n gets incremented and then checked, using your original bounds n < 4, the loop would end when n = 4 and thus 4 would be printed. I changed this in my last two examples. Also note the incorrect use of the term return, as some comments pointed out.

Douglas B
  • 585
  • 2
  • 13
  • @cocomac I rejected the suggested edit because the indentation was intentional; that code came from inside a main() function and was thus indented as it would be in actual code, which I hoped to express through the indentation. I searched quickly but was unable to immediately find any guidance on if it is standard to indent snippets when outside of their full compliable code, and stylistically, I prefer it this way. If you have any official guidance on that, please link it to me and I will happily make the change if it would be more in compliance with SO guidelines or norms. Thanks! – Douglas B Feb 08 '23 at 22:59