user7468879
user7468879

Reputation:

Misunderstanding in basic for loop (C)

I have been going through some exercises from a recommended book I found on this website. I came across this following basic piece of code, which I could not fully understand.

#include <stdio.h>

int main(void)
{

int i;

for (i = 10; i >= 1; i /= 2)
    printf("%d ", i++);

return 0;
}

This is my reasoning behind this program fragment:

  1. Variable i is initialised to 10.
  2. i is tested to see if greater or equal to 1, (which is always the case).
  3. The third expression reads: i = i / 2, thus i is divided by 2 and its value stored in i.
  4. In the printf statement i is incremented after each printf statement.

I simply cannot understand why the output of this program is:

1 1 1 1 1 1 1 1 ...

I get that the condition statement is always true, however shouldn't the first values be:

5 3 2 1 1 1 1 1?

Basically I cannot seem to understand why the value of i is straight away being stored as 1. Any corrections regarding my reasoning and/or insight on the matter will be appreciated. Please do excuse the basic nature of this question.

Upvotes: 0

Views: 96

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114518

As @abelenky pointed out, the correct output is 10 5 3 2 1 1 1 .... The only mistake you made in your reasoning is that the statement i /= 2 gets evaluated after the body of the for loop, before testing the condition again. Another way to write the same loop would therefore be

for(i = 10; i >= 1; i = (i + 1) / 2)
    printf ("%d ", i);

If you are running on Windows, try paging the output through more: myprog | more. This should allow you to see the beginning of the output of this infinite loop. On a linux machine, you could acheive the same result using more or less: myprog | less. Thanks to @EugeneSh for making the suggestion that this could be the issue.

Another way that I have found to view the initial output for programs like this is to hit Ctrl+C immediately after starting the program with Enter. This is not a "standard" method and may require very quick reflexes to get any results for a quick loop like yours.

A final suggestion is to limit the output you produce from the program directly:

int i, count;
for(i = 10, count = 0; i >= 1 && count < 100; i /= 2, count++)
    printf("%d ", i++);

This will add a counter that will stop your output after 100 numbers have been printed and allow you to see the first numbers.

Upvotes: 3

Pimich
Pimich

Reputation: 121

On the second line, you have 'i++'. Thus at each iteration of the loop, it will also increment i by 1.

So supposing i = 1 when you start the loop. First it will be divided by 2 (i /= 2). Since i is an integer, it will become 0. Then, on the second line, you have 'i++', thus incrementing i.

So by the end of the loop iteration, i will be back to being equal to 1 (thus making this loop infinite).

Upvotes: 0

Related Questions