0

In a for loop, if i am adding new line then it is printing at each iteration, And if i am just giving comma, means i want to print count down in one line, then it is waiting for completion of for loop. Which part i am missing?

Following code will print the latest count down after every iteration completed (because of '\n')

#include <stdio.h>

int main () {
    int x;
    for (x =0; x< 10; x++) {
        printf("%d\n", x);
        sleep(1);
    }
    printf("Fire!\n");
    return 1;
}

Following code will not print the latest count down, but will print when everything is done (may be because of ',')

#include <stdio.h>

int main () {
    int x;
    for (x =0; x< 10; x++) {
        printf("%d, ", x);
        sleep(1);
    }
    printf("Fire!\n");
    return 1;
}
Vishwadeep Singh
  • 1,025
  • 13
  • 35

2 Answers2

2

You can flush the stdout buffer explicitly:

for (x =0; x< 10; x++) {
    printf("%d, ", x);
    fflush(stdout);
    sleep(1);
}
Yu Hao
  • 111,229
  • 40
  • 211
  • 267
2

Your guess in the comment is correct, it's because output is buffered. If you want the output immediately then you have to flush the buffers with the fflush function after printf.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550