2

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.

3
  • 3
    "Oh, wait! I have to count upto 4294967295 before i multiply" - That's weird :) Commented Nov 17, 2013 at 14:01
  • Do you indeed multiply a and b somewhere? Commented Nov 17, 2013 at 14:48
  • @ᴍarounᴍaroun This is a part of code where I was trying to demonstrate the usefulness of threads. Multiiplication has to wait for 9 seconds before it actually happens in this code. But if I use threads, multiplication gives instant result while the counting continues in background. Commented Jan 29, 2014 at 8:09

2 Answers 2

6

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);
 }
Sign up to request clarification or add additional context in comments.

6 Comments

Indeed. It's like writing for(i=1;i<4294967295;i++) { }.
@MarounMaroun; OK, tell me how you did that? I tried many times by using unicode 2191 but getting weird output.
That's a secret in my family for generations, can't tell you.. sorry.
@MarounMaroun; OK... OK you Iron Man , I will reveal your secret.
To be honest, I think that the empty for-loop is intended behaviour.
|
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.