Thread: loops dont print on each indivual interation?

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    5

    loops dont print on each indivual interation?

    Maybe this just shows how unexperienced i am with C ( very unexperienced)
    but im used to java where i could print something in each iteration of a loop. I was trying to get a load bar for a big calculation involving a loop running a billion times, since the loop was taking 20 seconds or so, but if i tried to print something in the loop at certain intervals, it didnt print anything until the loop was completely finished, and then printed EVERYTHING at once. Is this how it is in C? or am i doing something wrong.

    This code is just a rushed example of what im talking about. with a star being printed at certain times during the entire life of the loop

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
       unsigned long i;
       unsigned long m = 1000000000;
       for(i = 0; i < m; i++)
       {
          if(i == (m*.2) || i == (m*.3) || i == (m*.4) || i == (m*.8))
          {
             printf(" * ");
          }
       }
       return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    if(i == (m*.2) || i == (m*.3) || i == (m*.4) || i == (m*.8))
    You are comparing an integer type (i) with a float type (m * .2) for equality which is always a bad idea due to the imprecision of floating point numbers.
    Your m-values are also constant so move them out of the loop.
    stdout is usually buffered and only printed if the buffer is full or you print a newline. Use fflush(stdout) to force the output after every printf()-call without newlines.

    All in all I suggest something like:
    Code:
    #include <stdio.h>
     
    int main(void)
    {
       unsigned long i, m = 1000000000;
       unsigned long m1 = m * .2, m2 = m * .3, m3 = m * .4, m4 = m * .8;
    
       for(i = 0; i < m; i++)
          if(i == m1 || i == m2 || i == m3 || i == m4)
          {
             printf(" * ");
             fflush(stdout);
          }
    
       putchar('\n');  
       return 0;
    }
    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loops not working and dont know what to do
    By ziggy786 in forum C Programming
    Replies: 7
    Last Post: 12-31-2012, 03:41 PM
  2. Write programs to print the following shapes using loops?
    By Jamal Albarea in forum C Programming
    Replies: 2
    Last Post: 10-06-2012, 02:07 AM
  3. Replies: 15
    Last Post: 06-13-2012, 12:34 PM
  4. if you dont like linux threads, dont read...
    By ... in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 02-03-2003, 11:26 AM
  5. ? about breaking up a string into indivual chars
    By Stringz in forum C Programming
    Replies: 3
    Last Post: 09-22-2001, 06:24 PM