-1

I want to make a func similar to a printf but that make the text appears slowly, by using a double for, one to print a char and one to take time:

    char phrase[30]={"Printf random"};
    for(int a=0;a<=30;a++){
        printf("%c",phrase[a]);
        for(int t=0;t<=1000000;t++){
            int f;
            f++;
        }
    }

but when I run, at first, it take some seconds (for the second for), and then it print all the phrase.

Why doesn't it enter the second for every time the firs one does? Maybe once the program calculates the second for the first time, it don't take time to calculate it again? how can i fix it?

Sourav Ghosh
  • 127,934
  • 16
  • 167
  • 234
Judal
  • 3
  • 2

2 Answers2

0

First of all, in your code, by saying

 for(int a=0;a<=30;a++){    

you're off-by-one and it invokes undefined behavior. It should be

 for(int a=0;a<30;a++){

That said, you need to flush the output buffer to actually send the buffer content to the associated file. Otherwise, the standard output actually being line-buffered, it will not flush the content automatically. All the content will be stored in the buffer and when the program is about to get finished, all the open buffers will be flushed and then the whole content will appear altogether.

Sourav Ghosh
  • 127,934
  • 16
  • 167
  • 234
  • 1
    He certainly only wants to print the actual characters, not the nul padding, so the loop control should probably be `for (int a = 0; phrase[a]; a++) ...` – M Oehm Feb 18 '16 at 10:26
-1

The int f should be before the second for loop. You are creating a new variable f each time in the loop and incrementing the new variable.

In you case, it works as there are no other variables in the loop. Therefore, each time in the loop, the variable f will be created in the same memory location, and have the old value.

This might not work if you have a complex loop with multiple if conditions.

Also, as mentioned by others, you need to flush your outputs.

Rishikesh Raje
  • 8,410
  • 2
  • 14
  • 30