kchetan
kchetan

Reputation: 5468

Printf blocked by for loop

I'm an armature programmer, and I wrote a code to calculate the time taken by a for statement to execute. The code is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>

int main()
{
    unsigned long long int i;
    int a,b;
    struct timeval st,end;

    printf("\nEnter two numbers to multiply");
    scanf("%d",&a);
    scanf("%d",&b);
    printf("\nOh, wait! I have to count upto 4294967295 before i multiply");
    gettimeofday(&st,NULL);
    for(i=1;i<4294967295;i++);
        printf("count : %lld",i);
    gettimeofday(&end,NULL);
    printf("Time elapsed: %lu:%lu\n",end.tv_sec-st.tv_sec,end.tv_usec-st.tv_usec);
    printf("\n");
    return 0;
}

The for loop takes ~13 seconds to finish. However the printf statement is executed only after for loop completes execution. Why is this happeneing.

Upvotes: 2

Views: 249

Answers (2)

haccks
haccks

Reputation: 106122

Remove ; from the end of for loop.

 for(i=1;i<4294967295;i++);  
                          ↑ Remove this semicolon.  

It should be

 for(i=1;i<4294967295;i++)
 {
      printf("count : %lld",i);
 }

Upvotes: 6

ljgw
ljgw

Reputation: 2771

The standard output stream is not always directly flushed (i.e. written to your screen),

try

fflush(stdout);

just after the line you want printed.

Upvotes: 1

Related Questions