text:
8 ought to become Infinity
Let's take a look on a typical loop, which usually performs 8 iterations:
for (int x=0; x<8; ++x);

You have to make it infinite!

It's a popularity-contest for all languages that support such form of for loop. So solution with highest score (upvotes minus downvotes) wins.
If your language has the other form of for loop, but you are sure, you can make something cool with it, feel free to post the answer and mark it as noncompeting. I reserve the right to enlarge scope of available constructions and languages, but it will never be shrinked, so don't be afraid of dropping previously correct solutions.

What is solution?
Solution consists of two programs.
The first program is a clean program. It's the typical program in your language with the for loop making 8 iterations. It should be the normal program, any developer could write. No any special hacks for preparation purposes. For example:
int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

The second program is augmented. This program should contain all the code from clean program and some additional code. There are limited number of extension points, see complete rules section for details. An augmented program for the clean one above can be
inline bool operator < (const int &a, const int &b)
{
  return true;
}

int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

That's just an example (noncompilable in C++) to show an idea. The real correct augmented program have to be compilable, working and having infinite loop.
Complete rules
Both programs:

Any language with support of such for loops is ok.
The loop body has to be empty. More precisely, you can place some output or other code into the loop, but loop behavior should be the same in case of empty loop.

Clean program:

Loop uses integer or numeric counter and performs 8 iterations:
for (int          x=0; x<8; ++x);   // C, C++, C#
for (var          x=0; x<8; ++x);   // C#, Javascript
for (auto         x=0; x<8; ++x);   // C, C++
for (auto signed  x=0; x<8; ++x);   // C, C++
for (register int x=0; x<8; ++x);   // C, C++

User-defined types are disallowed.
Using of property (except of global variable) instead of loop variable is disallowed.
Declaration of variable can be inside or outside of the loop. Following code is ok:
int x;
for(x=0; x<8; ++x);

Either prefix or postfix increment can be used.
Loop limit 8 should be written as a constant literal without saving to named constant or variable. It's made to prevent solutions based on declaring variable or constant equal to 8, and then reassigning, overriding or shadowing it by the other value:
const double n = 8;

int main()
{
  const double n = 9007199254740992;
  for (double x=0; x<n; ++x);
  return 0;
}

Augmented program:

Must contain all the code from the clean one.
Should extend clean program in limited number of extension points.
Must execute same for loop as an infinite loop itself.
Placing of the loop into another infinite construction is not ok.
Runtime or compile-time patching of the code is allowed as long as textual representation of it is unchanged.
Placing the construction into a string and passing to eval is disallowed.

Extension points:

Anywhere outside of the fragment with clean code, including other files or other assemblies.
for statement (as single piece - for construction and its body) must be kept unchanged.
Variable declaration must be kept the same.
Any place between simple statements can be used as extension point.
If and only if variable was declared outside of the loop and without immediate assignment of the value, such assignment can be added.

/* extension point here */
int main()
/* extension point here */
{
  /* extension point here */
  int x /* extension point for assignment here */;
  /* extension point here */
  for (x=0; x<8; ++x);
  /* extension point here */
  return 0;
  /* extension point here */
}
/* extension point here */

int main()
{
  /* BEGIN: No changes allowed */ int x = 0; /* END */
  /* extension point here */
  /* BEGIN: No changes allowed */ for (x=0; x<8; ++x); /* END */
  return 0;
}

PS: If possible, please provide a link to online IDE.

@Oliver, as I know, "highest score (upvotes minus downvotes)" is exactly the defaults for [tag:popularity-contest], at least it is written in the tag description: "A popularity contest is a competition where the answer with the highest vote tally (upvotes minus downvotes) wins." But I can add it to the question explicitly.

@LuisMendo, I expect it to be ok for [tag:restricted-source]. By the way, the first sentence by your link: "Unless you're writing a language-specific challenge" - yes, I am. I'm limiting scope of the languages by this construction, I understand it and I'm making it on purpoise.

How about removing the language restriction, and replacing the for loop with something more general (and have the extension points only be before and after the clean code). Maybe something like print something 8 times for the clean task, and have the clean task go on forever, for the augmented task

@Maltysen, there is a lot of interesting solutions in languages with these construction. There are C and C++ (with absolutely different solutions), C#, Java, Javascript, php, Perl, Groovy. I'm sure there are much more. Anyway, I'm open to enlarge question and that's specified in rules. If you can make something iteresting in other language - post it. If it will have positive reation, rules can be enlarged.

Doing this as a [tag:popularity-contest] is a little awkward because there's no description of what criteria voters should choose when voting (making the victory condition subjective). I was working on a [tag:code-golf] solution on the basis that many people here find golf solutions interesting and thus it might be popular; that seems like it might be a workable victory condition for the challenge.

@ais523, no [tag:code-golf] doen't suit for this challenge as 1. Interesting solutions with reflection or code patching are not good for golfing, also they are much better in readable state then in golfed. 2. C/C++ solution will win in 13 chars. 3. The other very cool C++ only solution will have 16 chars.

@ais523, "there's no description of what criteria voters should choose when voting" let's take a look at [tag:popularity-contest] description: "Qualities which should be AVOIDED in popularity contests ... Rules what people should consider when voting. In the past this has consistently never worked out."

"integer or numeric counter" is a bit too vague. E.g. does it include java.lang.Integer? 2. This would better with a proper winning criterion.

Yes, it does. 2. What exactly winning creteria? PS: We can continue on meta.

"If and only if variable was declared outside of the loop and without immediate assignment of the value, such assignment can be added." So in Perl 5 this is good? Program 1: my$a;1;$a=8;1while$b<$a Program 2: my$a;1;$a=8;$a=Inf;1while$b<$a

@msh210, it was about loop variable, not about loop limit. loop limit is expected to be constant.

@Dennis, why close?

Because the challenge is too broad for our standards. In particular, If your language has the other form of for loop, but you are sure, you can make something cool with it, feel free to post the answer and mark it as noncompeting. I reserve the right to enlarge scope of available constructions and languages, but it will never be shrinked, so don't be afraid of dropping previously correct solutions. That paragraph entirely explains why it's too broad.

How do noncompiting answers affect how broad the question is? And why not to answer on meta?

Python3
Clean Program:
This is just a standard countdown while loop.
n = 8
while n != 0:
  n -= 1
print("done")

Augmented Program:
import ctypes

ctypes.cast(id(8), ctypes.POINTER(ctypes.c_int))[6] = 9

n = 8
while n != 0:
  n -= 1
print("done")

It uses the int cache to redefine 8 as 9 which effectively makes the n -= 1 a no-op, since 9-1 = 8 which just sets n back to 9 again, causing the infinite loop.
You can see the int cache in action online here  (though obviously without the infinite loop cuz its online).

Could you provide a link to onlinde IDE, please? http://ideone.com/aI3ZrI - seems not working there.

@Qwertiy, I tried running it in repl.it, but it just freezes, which is to be expected since it'll be an infinite loop. i know the int cache stuff works there, because that's where I experimented with how to set 8 to 9

Really works there. Strange that thay haven't time limit like ideone (5 sec). They show Python 3.5.2 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux

@Qwertiy link without the loop: https://repl.it/E4fx/0

That's interesting...

Is this really in Python3, or is this whole ctypes business a CPython-implementation-specifc detail?

@Cactus I think it's CPython specific.

Python 3
Clean Program:
The standard way to do something 8 times in python is:
for i in range(8):
    # Do something
    pass

Augmented Program:
However, if we override the range generator function to infinitely yield 1, it becomes an infinite loop...
def range(x):
    while 1: yield 1

for i in range(8):
    # Infinite loop
    pass

We can take this further and create a generator function which, rather than infinitely yielding 1, counts up forever:
def range(x):
    i = 0
    while 1: yield i; i+=1

for i in range(8):
    # Counting from 0 to infinity
    pass

Test on repl.it

Hide that in the middle of a huge module...

Perl
Clean
for($i=0; $i<8; $i++) { }

Augmented
*i=*|;
for($i=0; $i<8; $i++) { }

Ideone.

Oh, that's really clever. For anyone who doesn't know Perl: this is aliasing $i to become an alias for a special variable that's only capable of holding booleans, so once it reaches 1 it becomes immune to being incremented.

ES5+ (Javascript)
EDIT: Removed explicit variable declaration, as otherwise it was hoisted and a non-configurable window.x property was created (unless run line by line in the REPL console).
Explanation:
Makes advantage of the fact that any globally scoped variable is also a property of the window object, and redefines "window.x" property to have a constant value of 1.
Clean
for(x=0; x<8; x+=1) console.log(x);

Augmented
Object.defineProperty(window,'x',{value:1});
for(x=0; x<8; x+=1) console.log(x);

NOTE: To make this work in Node.js, just replace "window" with "global" (tested in Node.js 6.8.0)

By the way, it's ES5, isn't it?

Also it doen't work with var in Crome. But you can remove var from both programs - it'll be ok.

@Qwertiy this does work with "var" in Chrome for me (Linux/Version 52.0.2743.82 (64-bit))

By the way, it's ES5, isn't it?
True, will correct the title now

Also it doen't work with var in Crome.
Please make sure that you start out clean, i.e. "x" must not be defined, before you run this code, i.e. if you first "run" the clean code, you have to reload the page, before running the augmented version.

The problem is var hoists, so at the moment of using defineProperty it already exitst. But if you place these 2 lines in different scripts (by the way, it's allowed), it would work, as the property will be created first and the var then will be ignored. Proof: https://i.stack.imgur.com/lSwbE.png

@Yep, true, I just ran it line by line in Chrome, which is why it worked for me. I've removed an explicit variable declaration (I believe that is allowed according to your earlier comment).

Yes, both solutions are allowed: remove var or place 2 lines of code in different scripts. https://jsfiddle.net/19g110y1/ (safe to open as there is break after 16 iterations).

I think you could also replace window with this to make it isomorphic.

C
Clean program
int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

Augmented program
#define for(ever) while(1)

int main()
{
  for (int x=0; x<8; ++x);
  return 0;
}

Must execute same for loop as an infinite loop itself. Placing of the loop into another infinite construction is not ok.

@KarlNapf The "for" loop is not inside another infinite construction.

@KarlNapf I thought this answer was explicitly allowed by the rule: •Runtime or compile-time patching of the code is allowed as long as textual representation of it is unchanged.

It is the wording "Must execute same for loop" but yes this conflicts with the textual representation.

Java
Clean program:
public class Main {
    public static void main(String[] args) throws Exception {
        for (Integer i = 0; i < 8; i++);
    }
}

Augmented program:
import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] intcache = (Integer[]) c.get(cache);
        intcache[129] = intcache[128];

        for (Integer i = 0; i < 8; i++);
    }
}

Sets the Integer in the Integer cache that should contain 1 to 0, effectively making i++ do nothing (it sets i to the cached Integer that should contain 1, but since that Integer actually contains 0, nothing changes).

Beat me to it, this solution is identical to my own.

This isn't really an idiomatic Java for loop, which would probably use the unboxed int rather than the relatively heavyweight Integer.

C++
int main()
{
#define int bool
  for (int x=0; x<8; ++x);
  return 0;
}

bool can only be 0 or 1. Inspired by primo's Perl answer.

Python 3 (3.5.0)
Clean Program:
for i in range(8):
    print(i)

Augmented
import sys

from ctypes import *

code = sys._getframe().f_code.co_code

cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-4] = 113
cast(sys._getframe().f_code.co_code, POINTER(c_char*len(code))).contents[len(code)-3] = 160

for i in range(8):
    print(i)

This solution is unlike the others written in Python in that it actually changes the source code on the fly. All the stuff in the for loop can be changed to whatever code is wanted.
The code changes the second to last opcode to be 113 or more readably - JUMP_ABSOLUTE. It changes the operand to 160 - the instruction where the for loop begins, in effect creating a GOTO statement at the end of the program.
The augmented program prints the numbers 0..7 infinitely many times without stack-overflowing or similar.

PHP
I think this is following the extension point rules; I'm not totally clear on point 4. It's very similar to @primo's perl answer so I think it counts.
Clean
for(;$i<8;$i++);

Augmented
$i='a';
for(;$i<8;$i++);

PHP lets you increment certain strings, like so:
'a' -> 'b'
'b' -> 'c'
'z' -> 'aa'
'aa' -> 'ab'
'aab' -> 'aac'
etc

All of these strings evaluate to 0, so this will loop practically forever (barring somehow running out of memory).

That's in the spirit of the competition and very interesting. Actually there wasn't said anything about ommiting initial assignmnet, so that's some edge case. Actually it was expected that there is no extension point between assigning 0 and iterations. But I'm not going to disallow it now as I see some interesing edge case ways based on that and it's not easy to overuse.

@Qwertiy "so that's some edge case." PHP in a nutshell :)

Perl
Clean code
for ($x = 0; $x < 8; $x++) {}

Augmented code
sub TIESCALAR {bless []}
sub FETCH {}
sub STORE {}
tie $x, "";

for ($x = 0; $x < 8; $x++) {}

Most Perl variables are just variables. However, the language also has a tie feature, which allows you to effectively give variables getters and setters. In this program, I make the main package (whose name is the null string) into the equivalent of a class from an object-oriented language, whilst also having it be a program. That allows me to tie the for loop counter to the program itself. Implementing TIESCALAR allows tie to succeed; the return value of TIESCALAR is meant to be a reference to any internal state we need to keep around associated with the variable, but because we don't need any, we return an empty array reference as a placeholder. We then give the simplest possible implementations of the getter and setter; neither of them do anything, so attempts to assign to $x have no effect, and attempts to read it always return undef, which is numerically less than 8.

WinDbg
Clean
.for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { }

Augmented
aS < |;                                            * Create alias of < as |
.block {                                           * Explicit block so aliases are expanded
    .for (r$t0 = 0; @$t0 < 8; r$t0 = @$t0 + 1) { } * Condition is now @$t0 | 8, always true
}

This approach creates an alias for < as |, so when < is encountered in the code the alias is expanded to | and bitwise-or is done instead of less-than. In WinDbg all non-zero values are truthy so anything | 8 is always true.
Note: The .block is not actually needed if the aS and .for are actually entered as two different lines as shown here, it's only required when the aS and .for are on the same line.

Mathematica
Clean
For[x = 0, x < 8, ++x,]

Augmented
x /: (x = 0) := x = -Infinity;
For[x = 0, x < 8, ++x,]

Common Lisp
Clean code
(dotimes(i 8))

Augmented
(shadowing-import(defmacro :dotimes(&rest args)'(loop)))
(dotimes(i 8))

A macro named keyword:dotimes, a.k.a. :dotimes (see 11.1.2.3 The KEYWORD Package) is defined which expands as an infinite loop. The defmacro macro returns the name of the macro being defined, which can be fed to shadowing-import. Thus, this new dotimes symbols shadows the standard one (which should not be redefined or lexically bound to another macro in portable programs).
Augmented (2)
(set-macro-character #\8 (lambda (&rest args) '(loop)))
(dotimes(i 8))

When we read character 8, we replace it by (loop). That means that the above reads as (dotimes (i (loop))) and so the code never terminates  computating the upper-bound. This impacts all occurrences of 8, not only the one in the loop.
In other words, 8 really stands for infinity.
If you are curious, when the readtable is modified like above, then character 8 becomes "terminating", and detaches itself from other numbers/symbols currently being read:
(list 6789)

... reads as:
(list 67 (loop) 9)

You can run tests on Ideone: https://ideone.com/sR3AiU.

Ruby
Clean
This sort of for loop is not much used in Ruby, but a typical tutorial will tell you that this is the way to go about it:
for x in 1..8
  # Some code here
end

Augmented
The for loop just calls (1..8).each with the given block of code, so we change that method:
class Range
  def each
    i = first
    loop { yield i; i+= 1 }
  end
end

for x in 1..8
  # Some code here
end

Haskell
Clean version:
import Control.Monad (forM_)

main = forM_ [0..8] $ \i -> print i

Augmented version:
import Control.Monad (forM_)

data T = C

instance Num T where
    fromInteger _ = C

instance Enum T where
    enumFromTo _ _ = repeat C

instance Show T where
    show _ = "0"

default (T)

main = forM_ [0..8] $ \i -> print i

It's quite basic, really: we just define our own type T such that its enumFromTo instance is an infinite sequence, then use type defaulting so that the un-type-annotated values 0 and 8 are taken as type T.

Nice idea to change the default type for Haskell's overloaded numeric literals.

///
There are no explicit for loops in ///, but can be simulated (it's turing complete after all).
Clean:
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8

Augmented:
/0/0/
/1/0/
/2/1/
/3/2/
/4/3/
/5/4/
/6/5/
/7/6/
/8/7/
8

What's going on?
While the former program counts down from 8 to 0, the latter one's /0/0/ rule will replace 0 by 0 until eternity.

And I thought that you would actually do something like /0/1//1/2/.../7/8//8/8/8 to count up instead.

Javascript ES6
OK, here's a version that works using the ES6 for...of loop construct. I'll even give you a clean array so that we're sure there's no funny business:
Clean
for(a of [0,1,2,3,4,5,6,7]);

Of course, that doesn't stop someone from messing with the Array prototype...
Augmented
Array.prototype[Symbol.iterator]=function(){return {next: function(){return {done: false}}}}
for(a of [0,1,2,3,4,5,6,7]);

This works by over-writing the default iterator so that it never terminates, therefore locking everything into an infinite loop. The code doesn't even have a chance to run the stuff inside the loop.

"loop behavior should be the same in case of empty loop"

Darn, missed that - I'll have to figure something out.

As far as I can tell, it isn't possible to do what the challenge with a C-style for loop in Javascript unless you break a rule - either by having something inside it (like my solution) or by pre-massaging the loop declaration in your clean code (like with Cedric Reichenbach's).

Actually there are some ways. Way with global variable is already posted, bute there are some more, allowing var in the loop.

Like I said, as far as I can tell. I saw the global variable way after making that comment and kicked myself.

@PatrickRoberts, my comment was about an older version. Check edit history for more details.

@Qwertiy thanks for pointing that out, and yes for the older version I completely agree with your comments.

Brainfuck
I print a '0' each iteration, just to make it easy to count iterations.  But any code could be inserted there without changing how the loop works.
Clean
>> ++++++ [-<++++++++>] <<                   b = '0' (value to be printed each iteration)

>> ++++++++ [-<< ++++++++ ++++++++ >>] <<    for (a = a plus 128;
[                                              a;
++++++++ ++++++++                              a = a plus 16 (mod 256)) {
>.<                                              loop body (print b)
]                                            }

Try it online
The augmented version relies on the common Brainfuck implementation with 8 bit cells.  On these implementations, "increment" is actually "increment (mod 256)".  Thus to find a loop that will iterate exactly 8 times in the clean version and endlessly in the augmented version, we can simply find a solution to the following system of inequalities.

a + b*8 (mod 256) == 0          (for clean version)
c + a + b*n (mod 256) > 0 for all n (for augmented version)
a > 0

In this case, we let a = 128, b = 16, and c = 1.  Obviously 128 + 16 * 8 = 256 (and 256 (mod 256) = 0) and 128 > 0, and since b is even, c + a + b * n is odd for any odd a + c, and thus will never be an even multiple of 256 in such cases.  We select c = 1 for simplicity's sake.  Thus the only change we need is a single + at the beginning of the program.
Augmented
+                                            increment a (only change)
>> ++++++ [-<++++++++>] <<                   b = '0' (value to be printed each iteration)

>> ++++++++ [-<< ++++++++ ++++++++ >>] <<    for (a = a plus 128;
[                                              a;
++++++++ ++++++++                              a = a plus 16 (mod 256)) {
>.<                                              loop body (print b)
]                                            }

Try it online
I leave it to the OP to determine if this entry is competing.  Brainfuck doesn't have an explicit for loop, but the loop form I used is as close as you're likely to get.  ++++++++ is also as close to a literal 8 as you can get; I've included quite a few of those.
The clean version almost certainly constitutes a typical program written in this language, as even the shortest known Brainfuck Hello World depends on a modular recurrence relation to work.

Haskell
Clean
import Control.Monad (forM_)

main = forM_ [0..8] $ \i -> print i

Augmented
import Control.Monad (forM_)

import Prelude hiding (($))
import Control.Monad (when)

f $ x = f (\i -> x i >> when (i == 8) (f $ x))

main = forM_ [0..8] $ \i -> print i

Replaces the usual function application operator $ with one that repeats the loop again every time it finishes. Running the clean version prints 0 to 8 and then stops; the augmented version prints 0 to 8 and then 0 to 8 again, and so on.
I cheat a little, in that forM_ [0..8] $ \i -> print i isn't necessarily the "cleanest" way to write that loop in Haskell; many Haskellers would eta-reduce the loop body to get forM_ [0..8] print and then there's no $ to override. In my defense I copied the clean code from Cactus' answer, who didn't need that property, so at least one Haskell programmer actually wrote that code with no motivation to unnecessarily add the $!

C++
Uses 2 extension points:
struct True {
  True(int x){}
  bool operator<(const int&){
    return true;
  }
  void operator++(){}
};

int main()
{
#define int True
  for (int x=0; x<8; ++x);
  return 0;
}

Clean program is same as in the description.

Nice, but can be "optimized" :) There are some interesting builtins in C++ to make another answer.

Nim
The idiomatic version, using countup:
Clean
for i in countup(1, 8):
  # counting from 1 to 8, inclusive
  discard

Augmented
iterator countup(a: int, b: int): int =
  while true:
    yield 8

for i in countup(1, 8):
  # counting 8s forever
  discard

Simple, and very similar to the Python answer which redefines range. We redefine countup, the idiomatic Nim way of iterating from one int (inclusive) to another, to give 8s infinitely.
The more interesting version, using the range operator ..:
Clean
for i in 1..8:
  # counting from 1 to 8, inclusive
  discard

Augmented
iterator `..`(a: int, b: int): int =
  while true:
    yield 8

for i in 1..8:
  # counting 8s forever
  discard

Very similar to the previous solution, except we redefine the range operator .., which normally would give an array [1, 2, 3, 4, 5, 6, 7, 8], to the iterator from before.

GolfScript
Clean
0{.8<}{)}while;

Augmented
{.)}:8;
0{.8<}{)}while;

It assigns the function returning n+1 to the variable 8

C++
int main()
{
  int y;
#define int
#define x (y=7)
  for (int x=0; x<8; ++x);
  return 0;
}

Lets x evaluate to 7. Does not work in C because it requires an lvalue at assignement and increment.

tcl
Normal:
for {set i 0} {$i<8} {incr i} {}

Augmented:
proc incr x {}
for {set i 0} {$i<8} {incr i} {}

The idea is to redefine the incr command that is used to increment the variable i, to actually not increment!
Can be tested on: http://rextester.com/live/QSKZPQ49822

x86_64 Assembly
Clean program:
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall

The sort of loop any Assembly programmer would use, followed by an exit syscall so as not to enable adding a jmp loop_start instruction afterwards.
Augmented program:
global start
section .text
start:
mov rcx, -1
jmp loop_start
mov rcx, 8
loop_start:
sub rcx, 1
cmp rcx,0
jne loop_start
mov rax, 0x01
mov rdi, 0
syscall

Also, sorry if it's bad that the clean program doesn't have an entrypoint or a section .text

Won't it stop after integer overflow?

Oh, uh... maybe. But it will take a long time? I kind of forgot that that could happen, being mostly a high-level-language programmer

JavaScript
Clean:
for (var i = 0; !(i > Math.PI * 2.5); i++);

Augmented:
window.Math = {PI: NaN};
for (var i = 0; !(i > Math.PI * 2.5); i++);

Doesn't seem to be a typical loop...

Yeah, I kinda stretched the term typical... :/

C++
Clean Program
A nice, normal loop, iterating from numbers 0 to 7.
#include <iostream>

int main() {

  for (short i = 0; i < 8; i++) {
    // Print `i` with a newline.
    std::cout << i << std::endl;
  }

}

Augmented Program
The preprocessor of C++ is quite a dangerous feature...
#include <iostream>
#define short bool

int main() {

  for (short i = 0; i < 8; i++) {
    // Print `i` with a newline.
    std::cout << i << std::endl;
  }

}

The only line we had to add was #define short bool. This makes i a boolean instead of a short integer, and so the increment operator (i++) does nothing after i reaches 1. The output then looks like this:

0
1
1
1
1
1
...

http://codegolf.stackexchange.com/a/101226/32091


text:
Cracking in progress
Remember those brute-force programs to crack password that show every combination they are trying? More precisely, at one point, the n first characters are fixed (they have been guessed successfully), and every possible character for the remaining ones is being tested. You've probably seen some in movies, or in some software written by people that like fancy interfaces.
Sorry to disappoint, but we won't write a program to crack password, only one to reproduce the nice output.
Challenge
Given a string containing printable ascii characters but no newlines (ascii code 32 to 126 or matching the regex ^[ -~]{2,}$), print an output following this rules:

At time t=n seconds, the n first characters printed are the n first characters of the input string.
After the n fixed characters, you should append a string formed random character (chosen uniformly pseudo-randomly from the unicode range    to ~ (code 32 to 126)) to form a string of the length of the initial one.
You should output at least (more on that later) 20 lines every second: every one of them will have the same n first characters, but a different random end.

It's probably not very clear yet what you are supposed to do, so lets go through an example:
Example
I'll print only 5 different lines for every seconds instead of the 20 minimum just to make it more readable.
Consider the input abcde.
During the first second, a valid output can be something like (completely random):
dGuT4
S!jkN
"gQ>[
TU3!
*fAjV

Then, t=1, the first character of every following string will be a (the first character of the input):
a);jD
aHv^p
aqw5*
a|.?:
a{gbK

Now, t=2, the first two characters will be ab:
abTJ"
ab\ e
ab3T#
abYWS
ab"#<

Now, t=3, the first three characters will be abc :
abcvW
abc3G
abc(g
abc{@
abc@4

Now, t=4, the first four characters will be abcd :
abcdD
abcdv
abcdj
abcd$
abcd6

Finally, t=5, we print the input (only once):
abcde

A few precisions

You shouldn't bother too much with your language precision toward the seconds (ie. If your algorithm is correct but your system/language lacks precision then it's fine).
The first second can be shorter than one second (That is, if you launch you program during a second, the first second can be just the remaining time until the end of the current second). Or put differently, you don't have to wait for the start of a new second to start printing the outputs.
At least 20 lines per second: The more natural way would be an infinite loop with a special behaviour one every second (or a timeout, or whatever), so that will result in probably a few thousand lines per second (and that's perfectly fine!). But if you have another idea, feel free to use it as long as you print at least 20 lines per second.
The input will always be more than 2 characters long.
You can consider that the input won't be more that 30 characters long if it helps. (But if it works for longer ones, it's for the best)
The input format should be the most natural representation of a string in your language.
You are allowed to print a trailing newline.

Code example
If you still don't understand exactly what you have to do, you can run the following code in a linux terminal to see:
perl -F -aplE 'map{$t=time;print$s,map{chr 32+rand 94}@F until$t-time;$s.=shift@F}@F' <<< "Cracking in progress\!"

Winning criterion
This is code-golf, so shortest code in byte wins!

Thanks to Laikoni and Flp.Tkc for their suggestions and improvement in the sandbox.

Like this scene from the movie War Games?

Is it mandatory to separate the lines of output with \r (making them all replace each other onscreen like in the animation), or is \n acceptable?

@ais523 \n is perfectly acceptable. The version with \r is just here because it looks better, but you don't need those \r.

If the random generation happens to crack the password earlier is it alright to stop at that point?

@JonathanAllan Actually the random generation doesn't crack the password, but just outputs random characters. So no, you can't stop earlier.

What is the max. length of password?

@IporSircer you can consider that the maximum length of the input is 30 if it helps.

Shouldn't you include in the rules that the random characters should not be the actual character in that place ? Otherwise random strings can match the password given, but the search goes on, which movie buffs would rate as a glitch.

@Tom I don't mind glitches, so I'm going to say no. (it adds unnecessary complexity, it would invalidate most answers, etc.)

You can save 1 byte on your code by changing while($t==time) to until($t-time).  Also you spelled "Cracking" incorrectly in your argument.

@GabrielBenamy I didn't golf it too much on purpose so Perl golfers can participate too. Thanks for pointing out the bad spelling of "Cracking"

You need single quotes around the last input string because it has an exclamation mark, at least in bash.

+1 Reminds me of http://uplink.co.uk

@Dada does the last line printed need a \n at the end?

@Soapy you can print it, or not, it's up to you.

Pyth - 27 24 bytes
This actually looks pretty cool :D
WJ-lQKs.d1+<QKsmOr;\~J;Q

Try it online here (obviously not in real time, but if you scroll it down with a steady hand).

HTML/JavaScript, 170 168 167 bytes

setInterval('o.textContent=i.value.replace(/./g,(c,i)=>new Date-d>++i*1e3?c:String.fromCharCode(Math.random()*95+32))',d=50)
<input id=i oninput=d=Date.now()><pre id=o>

Edit: Saved 2 bytes thanks to @ETHproductions. Saved 1 byte thanks to @jrich.

Haven't tested this, but I believe setInterval will accept a string to be eval'd, which could potentially save a byte?setInterval('o.textContent...',d=50) saves the _=> and adds a pair of quotes

@jrich That was handy, as I'd forgotten to update my byte count!

Node, 145 142 bytes
for(s=process.argv[2],d=new Date;s[a=(new Date-d)/1e3|0]+console.log(s.replace(/./g,(c,i)=>i<a?c:String.fromCharCode(32+Math.random()*95))););

This seems a little long, and there's probably a little room for golfing. Note that the semicolon at the end is required; without it the program throws a syntax error because the for statement has no body.
Outputs way more than 20 lines per second; a little birdie told me that it's roughly 12 thousand. Here's how it looks in the ConEmu terminal emulator on my computer (recorded at 30 fps):

05AB1E, 26 bytes
I post this as a different answer with respect to the other 05AB1E answer since the approach is different
.põ¸ì¨vT·FyžQ.r¹gyg-£«}}¹»

.p                         Generate ordered prefix of input (e.g., ["a", "ab", "abc", "abcd", "abcde"] for "abcde")
  õ¸ì                      Prepend an empty string (e.g., result is ["", "a", "ab", ...])
     ¨                     Strip the last element (the same string as the input)
      v                    For each string in the array
       T·F                 For N in range(20)
          y                Push the current string
           žQ.r            Push all printable characters, shuffled
               ¹gyg-       Take the difference between the length of the input and the length of the current string -> x
                    £      Take the x first characters from the shuffled printable characters
                     «     Yield currentString + shuffledCharacters
                      }    End inner for
                       }   End outer for
                        ¹  Push input (last iteration)
                         » Join everything with newlines and implicitly display

Try it online!

Nice answer, +1 from me! NOTE: It can be 22 bytes with the newer builtins these days: η instead of .p; õš (where š is prepend as list) instead of õ¸ì (where ¸ì is wrap in list, and prepend); ₂ (where ₂ is 26 if no second input is given) instead of T· (which is push 10, and double); ] instead of }} (where ] closes all loops, if-else statements, etc. at the same time)

BASH, 99 93 92 91 88 bytes
with tr + head + urandom
while ((${#1}-n));do
echo "${1::n=SECONDS}`tr -dc \ -~</dev/ur*|head -c$[${#1}-n]`"
done

(thx. to @manatwork )

[ "$n" = ${#1} ] → ((n==${#1})); ${1:0:$n} → ${1::n}

@manatwork: whoa!

1 more: the space in front of input redirection < is not needed.

@manatwork ((n==${#1})) --> ((${#1}-n))

Either because you reversed the logic or because I banged my previous test, but ${1::n=SECONDS} seems to work now.

Hmmm...it does not seem to work  under Bash 4.4 on my system as whenever I run this through a function as G hello, I just get the errors tr: Illegal byte sequence and head: illegal byte count -- -56358 over and over.

@R.Kap: i'm afraid it's linux only, because it hardly depends on /dev/urandom.

05AB1E, 30 bytes
gFžcUNV[¹Y£žQ.r¹gY-£J,XžcÊ#}¹,

Uses the CP-1252 encoding. Try it online!
Please help me golf this down.

C, 182 176 128 126 125 bytes
Golfed:
i;s;n;x;g(char*c){time(&s);while(c[++x]);do{n=time(0)-s;for(i=0;i<x;i++)putchar(i<n?c[i]:32+rand()%95);puts("");}while(n<x);}

Ungolfed:
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int i,s,n,x;
void g(char* c) {
  time(&s); //Get the initial time
  while(c[++x]); // x = strlen(c) (happy about this one)
  do {
    n = time(0) - s; //seconds since beginning
    for(i = 0; i < x; i++)
      //after each second, print another char of the password
      putchar(i < n ? c[i] : 32 + rand() % 95);
    puts("");
  } while(n < x); //while we haven't printed the whole word
}

I've heard that it's possible to drop some standard #includes, but I couldn't get it to work on the MingW GCC compiler I just downloaded.  Also couldn't figure out how to #define b #include without using more space than it was worth.
I'm just an idiot, it works fine without them.

X=0 is not required instead declare it with others like this a,b,c,d; cuz all global variables declared like that are int and init by 0 also since you are returning nothing you should write it in main ()

Thanks, I didn't know about static scope initialization.  I did declare them like that, just with semi-colons instead of commas.  Also I didn't use main because I think then I'd need to take (int argc, char ** argv) and that's a ton of bytes.  I hope leaving it as a function is OK, although it takes input as a parameter and output to stdout which is slightly odd.

Use while(i++<x)  instead of for (...)

Really good idea, but i needs to be zero everytime the for loop runs again.

Then in the same for replace i <x with i++<x and remove i++

Then i will never be 0 inside the loop

Hmmm...then mayne insert i++ in putchar(...c [i++]...)

That's only conditionally executed

Oops my bad...insert i++ in i <n i guess that should be fine...

Let us continue this discussion in chat.

Java 7, 271 265 207 bytes
void c(String s)throws Exception{for(int i=0,j,l=s.length();i<=l*20;i++){String r=s.substring(0,i/20);Thread.sleep(45);for(;j++<l;r+=(char)(32+Math.random()*95);System.out.println(r);if(s.equals(r))return;}}

-58 bytes saved thanks to @OliverGrégoire. (Don't forget to upvote his even shorter Java 8 answer.)
Ungolfed:
void c(String s) throws Exception{
  for(int i = 0, j, l = s.length(); i <= l*20; i++){
    String r = s.substring(0, i/20);
    Thread.sleep(45);
    for( ; j++ < l; r += (char)(32+Math.random()*95));
    System.out.println(r);
    if(s.equals(r)){
      return;
    }
  }
}

Input: abcde
Output:

I'm not sure if you designed it purposefully to only print 20 lines per second, but if it helps your golfing, you only have to print at least 20 lines per second.  I don't know if changing the "20 lines per second" math to "change every second" math would help or not.

You don't need x: r+=(char)(33+Math.random()*94). Also Thread.sleep(9) to save a byte.

Also, r=s.substring(0,i/20) instead of the loop on j.

Given the significant changes I made, I decided to post my answer with those comments taken in account. Also, it's a Java 8 solution to go rather low in the byte count (Java-wise, ofc).

@OlivierGrégoire Thanks. And I've upvoted your answer. I haven't made all changes, only the r.substring(0,i/20) (pretty stupid of me), and the (char)(33+Math.random()*94) (nice trick from you).

Thanks. To be honest the (char)(...) part comes from this earlier puzzle which I reviewed yesterday as well.

R, 138 bytes
z=Sys.time;n=nchar(x<-scan(,""));s=z();t=0;while(t<=n){t=t+z()-s;cat(substr(x,1,f<-floor(t)),intToUtf8(sample(32:126,n-f,T)),"\n",sep="")}

Reads input from stdin.
Counted approximately 61 lines on my machine between each additional letter in the "password".

Haskell (GHC), 202 bytes
import System.Random
import Control.Concurrent
f s|l<-length s=mapM_(\n->putStr('\r':take n s)>>mapM(\_->toEnum<$>randomRIO(32,126))[1..l-n]>>=putStr>>threadDelay 50000)$[n|n<-[0..l-1],f<-[1..20]]++[l]

-5 bytes without fancy carriage return action

Looks good! But what's that > doing at the end of the output?

@Mast that's the prompt. Since the code doesn't print a newline at the end, the prompt goes there.

MATL, 26 bytes
`GZ`:)' ~'olGn4Mk-I$YrhD7M

Try it online!
Below is the real-time output from the offline compiler. Note that the animated GIF was recorded at 20 fps to keep its size small, but the actual speed is much greater.

How it works
           % Implicitly start timer
`          % Do...while
  G        %   Push input
  Z`       %   Push timer's current value, say t
  :)       %   Select the first t elements of the input, with t
           %   implicitly rounded down
  ' ~'     %   Push this string
  o        %   Convert to numbers, i.e. [32 126]
  l        %   Push 1
  Gn       %   Push input size, say n
  4Mk      %   Push floor(t), where t is the same value used above
  k        %   Subtract. Gives n-floor(t)
  I$Yr     %   Generate a row vector of n-floor(t) integers randomly
           %   chosen from 32 to 126
  h        %   Concatenate with the first characters of the input
  D        %   Display
  7M       %   Push the value n-floor(t) used above. This is used
           %   as loop condition: iz zero the loop is exited
           % Implicit end

This code is so happy. :)

@SethMichaelLarson That's because its quote marks are balanced, which doesn't usually happen :-)

Bash, 247 245 212 207 bytes
R()(echo $SECONDS);w=`R`;until [ "$a" = "$1" ];do for i in `seq 1 $[${#1}-${#a}]`;{ a+=`printf "\x$(printf %x $[$RANDOM%127+32])"`;};echo -e "$a\r";a=${1:0:q};((`R`-w>0))&&{ w=`R`;((q++));}||:;done;echo "$a"

Thanks a lot Bash for being so whitespace sensitive...
Anyways, output is given in real time on separate lines. Save as a .sh script and invoke with:
bash <File Name>.sh <Input>
For example, bash Cracking_In_Progress.sh okayerty results in the following output, recorded at 30 frames per second:

WinDbg, 400 391 bytes
.for(r$t1=@$t0;by(@$t1);r$t1=@$t1+1){};m@$t0 L@$t1-@$t0+1 @$t1+1;r$t4=2*@$t1+2-@$t0;r$t8=@$t4+f;r$t3=0;.for(r$t2=0;@$t2<@$t1-@$t0;da@$t0){.for(r$t7=@$t0+@$t2;by(@$t7);r$t7=@$t7+1;r$t8=@$t8+1){eb@$t7 by(@$t8)%5e+20};r$t9=0;.foreach(p {.echotime}){.if7==@$t9{ea@$t4"p";.if1>@$t3{r$t3=by(@$t4+7)}};r$t9=@$t9+1};j@$t3!=by(@$t4+7)'m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2;r$t2=@$t2+1;r$t3=by(@$t4+7)'}

-9 bytes by simplifying some math
This definitely does not seem to be the kind of thing WinDbg is intended to do. ;)
Input is taken by entering an ascii string at a memory location and setting that address to the pseudo-register $t0. Eg:
r$t0 = 2000000
eza @$t0 "abcde"

The prng I'm using is whatever the contents in memory, some bytes past the input string. Chrome.exe appears to fill the memory space after 0x2000000 with random-looking-enough bytes so I used a dump of chrome.exe. Unknown if this is uniform, but looks random-enough to me.
How it works:
.for(r$t1=@$t0; by(@$t1); r$t1=@$t1+1){};         * From $t0, increment $t1 until the byte
                                                  * at $t1 is 0 to find length of input
m@$t0 L@$t1-@$t0+1 @$t1+1;                        * Duplicate input (memory
                                                  * becomes: "input\0input\0")

r$t4=2*@$t1+2-@$t0;                               * Set $4 to the byte after \0 of the
                                                  * duplicated input
r$t8=@$t4+f;                                      * Set $t8 to $t4+15, this is the prng
r$t3=0;                                           * Init $t3=0, this will hold the time

.for(r$t2=0; @$t2<@$t1-@$t0; da@$t0){             * For $t2=0, loop until it's input length,
                                                  * printing the string at $t0 after each
                                                  * loop. $t0 is where the password crack
                                                  * progress is written.
    .for(r$t7=@$t0+@$t2; by(@$t7); r$t7=@$t7+1;   * Loop over each uncracked char
                                   r$t8=@$t8+1){  * also incrementing prng ($t8)
        eb@$t7 by(@$t8)%5e+20                     * Write a visible ascii char onto the
                                                  * uncracked char position based on the
                                                  * current byte of prng%0x5e+0x20 (prng%126+32)
    };

    r$t9=0;                                       * Set $t9=0 for updating current time
    .foreach(p {.echotime}){                      * For each (string) word in a statement
                                                  * like "Debugger (not debuggee) time: Mon
                                                  * Nov 21 18:23:08.433 2016 (UTC - 8:00)"
        .if7==@$t9{                               * If the 7th word, ie- the current time
            ea@$t4"p";                            * Write the time at $t4
            .if1>@$t3{                            * If $t3 has not been set yet
                r$t3=by(@$t4+7)                   * ...save the current second in $t3
            }
        };
        r$t9=@$t9+1                               * Increment $t9 until it's 7
    };

    j@$t3!=by(@$t4+7)'                            * If the current second has changed
        m@$t0+@$t4-@$t1+@$t2-1 L1 @$t0+@$t2;      * Copy the cracked char from dupe input
        r$t2=@$t2+1;                              * Increment $t2 (loop ends when this is input length)
        r$t3=by(@$t4+7)                           * Save the new current second
    '
}                                                 * Final crack is printed by for loop

Note: Some bytes could be golfed by using j instead of the .if's, but that causes it to run too slowly on my machine so it doesn't output at least 20 lines per second, so not saving those bytes.
Sample Output: http://pastebin.com/H4H74sAx

Python 3, 167 166 bytes
import time,random
t=time.time
p,s=input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)

Reads input from stdin. A 171-byte version runs under Python 2 (replaced input with raw_input):
import time,random
t=time.time
p,s=raw_input(),t()
while t()-s<len(p):print(p[:int(t()-s)]+''.join(chr(random.randint(32,126))for _ in range(len(p)-int(t()-s))))
print(p)

Ungolfed:
import random
import time

p = input()
start = time.time()
while time.time() - start < len(p):
    print(
        p[:int(time.time() - start)] +
        ''.join(chr(random.randint(32, 126)) for _ in range(len(p) - int(time.time()-start)))
    )
print(p)

Python3, 149 141 139 bytes
import time,random
i,x=input(),0;l=len(i)
while x<l:x=int(time.clock());print(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)))

Input from stdin.
Eyes version (157 bytes):
import time,random
p,i,x=print,input(),0;l=len(i)
while x<l:x=int(time.clock());p(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)),end="\r")
p(i)

I think you can save a few bytes by not "renaming" things that you only do once.  For instance you have t=time.clock, but you only use t once in the code.  Replacing it with just time.clock will save 3 bytes.  Same thing for print.

@nmjcman101 Oops, carry over from prev ver. Thanks!

Also your for _ in range(l-x) can be for _ in"a"*(l-x) for 2 bytes.

@nmjcman101 Nice! I must remember that one...

Try print(i[:x]+''.join(map(chr,random.sample(range(32,127),l-x)))) instead of print(i[:x]+"".join(chr(random.randint(32,126))for _ in"a"*(l-x)))

@x1Mike7x I really wish I could, because I saw the sample function when writing this, but the question says "chosen uniformly pseudo-randomly" and with sample the same letter cannot be chosen twice.

Node.js, 134 bytes
for(s=[...process.argv[2]],n=new(d=Date);s[m=(new d-n)/1e3|0]+console.log(s.map((a,i)=>i<m?a:Buffer([Math.random()*95+32])).join``););

Similar to @ETHproductions (borrowed some of his optimizations), but otherwise takes a different approach. Uses Node's Buffer to handle character generation instead of the lengthy String.fromCharCode, which has the side benefit of letting us use map without much string->array->string conversion overhead.

Nice, I should learn more about Buffer. Just so you know, reassigning Date to D doesn't save any bytes; I tried that myself.

Dyalog APL, 59 58 bytes
Solution
Requires ⎕IO←0 which is default on many systems.
⊢⊣≢{⍵{≢⎕←⍵↑⍺,⎕UCS 32+?⍵⍴95}⍣{t≤2⊃⎕AI}⍺⊣t←1E3+2⊃⎕AI}¨⍳∘≢↑¨⊂

Display
By adjusting the window to two lines, we get the illusion of an in-place transformation:

Explanation
This is an anonymous function train which takes the password as right argument.
⊢⊣ return the password and dismiss the result of
≢{...}¨  the below function, with the length of the password as left argument, applied to each of
 2⊃⎕AI current up-time (lit. third element of Account Information)
 1E3+ add a second
 t← assign that to t
 ⊣ dismiss that
 ⍵{...}⍣{t≤2⊃⎕AI}⍺ apply the following function (with sub-string as ⍺ and password length as ⍵) repeatedly until the up-time reaches t
  ⍵⍴95 95 repeated as many times as there are characters in the password
  ? random integer 0...94
  32+ add 32 (thus yielding ⍵ random integers in the range 32...126)
  ⎕UCS convert to Unicode character
  ⍺, prepend the currently processed sub-string
  ⍵↑ take only as many character as there are in the password
  ⎕← output that on a separate line
  ≢ return the length of the outputted string (= the length of the password)
⍳∘≢ 0 ... length-1
↑¨each taking characters from
⊂ the password

Java, 159 bytes
s->{for(int i=0,j,l=s.length();i<=l*99;i++){String r=s.substring(0,j=i/20);Thread.sleep(9);for(;j++<l;r+=(char)(32+Math.random()*95));System.out.println(r);}}

Same algorithm as Kevin Cruijssen's answer, only totally optimized for Java 8.
Ungolfed:
public class Tmp {

  interface X {

    void f(String s) throws Exception;
  }
  static X f = s -> {
    for (int i = 0, j, l = s.length(); i <= l * 20; i++) {
      String r = s.substring(0, j = i / 20);
      Thread.sleep(48);
      for (; j++ < l; r += (char) (32 + Math.random() * 94));
      System.out.println(r);
    }
  };

  public static void main(String[] args) throws Exception {
    f.f("abcde");
  }
}

C#, 203 197 195 190 bytes
Golfed:
void F(string s){int l=s.Length,t=0;var w=Stopwatch.StartNew();do{if(w.Elapsed.Seconds>t)t++;Console.WriteLine($"{s.Substring(0,t)}{Path.GetRandomFileName().Substring(0,l-t)}");}while(t<l);}

Ungolfed:
    void F(string s)
    {
        int l = s.Length, t = 0;
        var w = Stopwatch.StartNew();

        do
        {
            if (w.Elapsed.Seconds > t)
                t++;

            Console.WriteLine($"{s.Substring(0, t)}{Path.GetRandomFileName().Substring(0, l - t)}");
        } while (t < l);
    }

l stores input length.
StopWatch and Path.GetRandomFileName() are parts of .NET framework.
EDIT1: Implicit Stopwatch declaration.
EDIT2: l initialization merged with declaration.
EDIT3: Thanks, @Chris.

You can use the static method Stopwatch.StartNew() to save newing up the stopwatch, and explicitly starting it

@Chris, I didn't know about that method, thx.

t++ can be inserted somewhere in if ()

@MukulKumar Could you provide more details, please?

Use if (w.Elapsed.Seconds > t++) and remove t++;

But wait, that may lead to some problems but still please check if this works....

Each if execution involves t incrementation. Loop executes only 5 times and exits.

ForceLang, 322 309 bytes
def s set
s g goto
s W io.writeln
s k io.readln()
s T timer.new()
def a T.poll()
label 1
s P math.floor a.mult 1e-6
if P=k.len
 W k
 exit()
s j 0
s t ""
if P=0
g 4
label 3
s v k.charAt j
s t t+v
s j 1+j
if j-P
g 3
label 4
if j=k.len
 W t
 g 1
s r 94.mult random.rand()
s v string.char 32+r
s t t+v
s j 1+j
g 4

Could you add a link for the programming language you used?

@SolomonUcko Here you go.

Scala, 259 254 248 233 232 231 227 225 bytes
import scala.concurrent.duration._;(b:String)=>{val d=b.length.seconds.fromNow;while(d.hasTimeLeft)println(b.zipWithIndex.map{case(f,g)=>if(g<b.length-d.timeLeft.toSeconds-1)f else(32+math.random*94)toChar}mkString);print(b)}

Ungolfed:
import scala.concurrent.duration._;

(b:String) => {
    val d = b.length.seconds.fromNow;
    while(d.hasTimeLeft)
        println(
            b.zipWithIndex.map{
                case(f,g) =>
                    if(g<b.length-d.timeLeft.toSeconds-1)
                        f
                    else
                        (32+math.random*94)toChar}
            mkString
        );

    print(b)
}

C++ (gcc), 280 278 bytes
#include<iostream>
#include<chrono>
#include<cstdlib>
#include<thread>
int i,n,t,q;void f(std::string s){for(t=s.size(),n=0;n<=t;n++)for(q=n<t?20:1;q--;std::this_thread::sleep_for(std::chrono::milliseconds(50)))for(std::cout<<"\n"<<s.substr(0,i=n);i++<t;)putchar(32+rand()%84);}

Try it online!
It just prints 20 random strings waiting for 50 std::chrono::milliseconds between each other (thus outputting exactly 20 lines per second) and then proceeds to the next "cracking" step.

Go, 244 bytes
import(."fmt"
."math/rand"
."time")
func a(s string){Seed(Now().Unix())
for i:=0;i<len(s);i++{t:=Now().Truncate(Second).Add(Second)
for Now().Before(t){q:=[]rune(s)
for p:=len(q)-1;p>=i;p--{q[p]=rune(32+Intn(95))}
Println(string(q))}}
Print(s)}

Try it online! (truncates the result so it doesn't show every instance)
This is my first Golang answer \o/

(Filmed @ 30fps)
How:
func a(s string) {                      //function a
Seed(Now().Unix())                      //Create a seed for the pRNG
for i := 0; i < len(s); i++ {           //set helper var i (this is the number of characters we'll keep)
t := Now().Truncate(Second).Add(Second) //set helper var t = 1 second from now
for Now().Before(t) {                   //while inside that 1 second window
q := []rune(s)                          //put each character in a rune slice and assign that to q
for p := len(q) - 1; p >= i; p-- {      //loops through the rune slice
q[p] = rune(32 + Intn(95))              //replace the character in position p with a random code point in [32,126]
}
Println(string(q))                      //print the rune slice as a string
}
}
Print(s)                                //finally, print the original string
}

PHP, 222 bytes
$a=$argv[1];$c=range(32,126);$t=time();$s=$t;$e=$t+strlen($a);while(time()<=$e){$l=time();$p=$l-$s;$x=substr($a,0,$p);$k=$e-$l;$r='';for($i=$k;$i>0;$i--)$r.=chr($c[rand(0,94)]);$o=$x.$r;echo"$o\n";if($o==$a&&$l==$e)break;}

Ungolfed
<?php
$input = $argv[1];
$chars = range(32, 126); // count() is 95

$startTime = time();
$endTime = time() + strlen($input);

while (time() <= $endTime) {
    $plaintextAmountToPrint = time() - $startTime;

    $plain = substr($input, 0, $plaintextAmountToPrint);

    $cryptAmountToPrint = $endTime - time();

    $crypt = '';

    for ($i = $cryptAmountToPrint; $i > 0; $i--)
        $crypt .= chr($chars[rand(0, 94)]);

    $output = $plain . $crypt;

    echo $output . "\n";

    if ($output == $input && time() == $endTime)
        break;
}

(i know the video is crap)

This could be golfed a lot more. For example, instead of $c=range(32,127) and then $r=chr($c[rand(0,94)]), why not just $r=chr(rand(0,94)+32) ?

Good point. It's my first golf :P

<?$l=strlen($a=$argv[1]);$e=$l+$s=time();while(time()<=$e&&$o!=$a){$o=substr($a,0,time()-$s);while(strlen($o)<$l)$o.=chr(rand(0,94)+32);echo "$o\n";} is 149 bytes, and I'm sure it can be golfed further

Cool, you should post that man.

Just edit your answer, you're allowed to change and improve it.

Can't get it to work man.

Seems like copy-pasting what I posted adds characters in, oddly. Not sure why.

Kotlin, 188 bytes
Golfed
val x=readLine()!!;val n=System::currentTimeMillis;val t=n();do{val s=(n()-t)/1000;x.mapIndexed{i,c->print(if(i<s)c else((Math.random()*(126-32))+32).toChar())};println()}while(s<x.length)

Ungolfed
val input = readLine()!!
val time = System::currentTimeMillis
val startTime = time()
do {
    val crackIndex = (time() - startTime) / 1000
    input.mapIndexed{ i, letter ->
        print(
            if (i < crackIndex) letter else ((Math.random()*(126-32))+32).toChar()
        )
    }
    println()
} while(crackIndex < input.length)

Renaming System.currentTimeMillis saved quite a few bytes!

Tcl, 295 bytes
First golf for me in Tcl. Not a very golfable language, since everything is treated as strings here so whitespace is usually a must...
set l [string length $argv];set s [clock seconds];set r -1;while {$r<$l-1} {puts -nonewline [string range $argv 0 $r];set k $l;while {[set k [expr $k-1]]>$r} {puts -nonewline [format %c [expr int(rand()*95+32)]]};puts "";if {[expr [clock seconds]-$s]>[expr $r+1]} {set r [expr $r+1]}};puts $argv

Ungolfed:
set l [string length $argv]
set s [clock seconds]
set r -1
while {$r < $l-1} {                                      # loop on time
  puts -nonewline [string range $argv 0 $r]
  set k $l
  while {[set k [expr $k-1]] > $r} {                     # loop on "unfound" chars
    puts -nonewline [format %c [expr int(rand()*95+32)]]
  }
  puts ""
  if {[expr [clock seconds]-$s] > [expr $r+1]} {         # advance time
    set r [expr $r+1]
  }
}
puts $argv

Why don't you store the output on a variable then join them all, to avoid -nonewline on the puts parameter?

I think you don't need the two expr at the end; one is enough, and you can also avoid the spaces around  >

Thanks @sergiol, There are no spaces around >, look at the condensed version. Please advise how to use one expr at the end, I can't see it.

demo of my two suggestions.

You can also replace set r [expr $r+1] by incr r

And I think there is space for golfing it more.

[set k [expr $k-1]]can be [incr k -1]. And every < can be <, no spaces required.

new demo

Good to know about incr :-) I will try to golf it some more when I have time...

QBIC, 92  88 bytes
I've cracked it!
t=20;_LA|[a*t-t|B=$left$|(A,b/t)[a|B=B+$CHR$|(_r94|+32)]?$left$|(B,a)~b%t=0|$sleep 1|}?A

This relies on QBasic's SLEEP function using the code literal $sleep 1|, and on QBasic's LEFT$ function because I haven't implemented that function in QBIC yet...
Managed to scrape a few bytes by substituting all the 20's for t and setting that to 20. Also, streamlined a call to random and a FOR loop.
Explanation:
' Get cmd line param with 'password' and the length of that string, set t to 20
t=20;_LA|

' loop from 1 (implicitly) to (#chars-1) * 20 cracks per char
[a*-t|

'have our crack-display start with the first N chars of
'the password, where N is the number of seconds passed
B=$left$|(A,b/t)

' loop to add the 'crack-visual'
' It's too long, but we'll trim it down to the original length
[a|B=B+$CHR$|(_r92|+34)]?$left$|(B,a)

' if we've done 20 cracks, sleep for 1 second
~b%20=0|$sleep 1|}

' We've cracked it!
?A

Output (a piece of the middle section on 'helloworld')
hewnoluZfs
heb!mrc2g@
hee+yh"5ut
he0?V+O)Uu
heqf(#M/BM
hez|DGX%a8
he<_n[6-.+
helkxQ#g%,
hel&^A9$I8
hel43{b5]t
helszK50%F
hel`kdy ;b
hel Vr6Z}s
helLIR7*7o

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Fewest disk writes to defrag multiple files
Introduction
A disk is a linear container with blocks indexed 0 through size-1.
A file is a named list of block indexes used by that file.
An example filesystem is expressed like this:
15 ALPHA=3,5 BETA=11,10,7

"The disk has 15 blocks, the first block of file ALPHA is the disk block at index 3..."
The disk map could be drawn like this:
Block Index  00  01  02  03  04  05  06  07  08  09  10  11  12  13  14
Contents    |   |   |   |A0 |   |A1 |   |B2 |   |   |B1 |B0 |   |   |   |

A disk is considered defragged when all of the files within it are stored contiguously.
YOUR GOAL:
Emit a shortest sequence of legal moves which will defrag a given disk.
Legal Moves
A move contains three pieces of information: the name of a file, an index of the block in the file to be moved, and the index of the disk block it moves to.
For example
ALPHA:1>4

"Move block 1 of the file ALPHA to block 4 of the disk."
After this move, the example file system is now this
15 ALPHA=3,4 BETA=11,10,7

Block Index  00  01  02  03  04  05  06  07  08  09  10  11  12  13  14
Contents    |   |   |   |A0 |A1 |   |   |B2 |   |   |B1 |B0 |   |   |   |

The previously-inhabited disk block is implicitly cleared. Equivalently, you can view this as swapping two blocks on the disk but one of the blocks in the swap must be empty.
Data may not be destroyed. Files cannot share blocks at any stage and movements must be within range of the disk. The following moves are illegal: ALPHA:0>10 (owned by BETA), ALPHA:3>0 (no such block in ALPHA), ALPHA:0>-1 (no such disk index), ALPHA:0>15 (disk index too big)
Example 1
Solving the above example in full.
ALPHA:0>4
BETA:0>9
BETA:2>11

Files do not have to be adjacent in the solution, just continuous within themselves.
Example 2
Here is a more constrained case
Input:
10 A=1,2,3 B=6,7,8 C=4,5,0

Output:
B:2>9
B:1>8
B:0>7
C:2>6

The progression of this filesystem is:
Block Index  00  01  02  03  04  05  06  07  08  09
Contents    |C2 |A0 |A1 |A2 |C0 |C1 |BO |B1 |B2 |   |
            |C2 |A0 |A1 |A2 |C0 |C1 |BO |B1 |   |B2 |
            |C2 |A0 |A1 |A2 |C0 |C1 |BO |   |B1 |B2 |
            |C2 |A0 |A1 |A2 |C0 |C1 |   |B0 |B1 |B2 |
            |   |A0 |A1 |A2 |C0 |C1 |C2 |B0 |B1 |B2 |

An alternative way to defrag this would by to C:2>9 then bring A down a step, then bring C down a step, then do C:2>5 but this would not be a legal solution because it contains more moves than the alternative.
Representation
You can use any representation for the input as long as it is reasonably close to a basic string. Depending on your language, the input to the first example might be notated as
"15 ALPHA=3,5 BETA=11,10,7"
[15," ","ALPHA","=",3,",",5," ","BETA","=",11,",",10,",",7]
(15,(("ALPHA",(3,5)),("BETA",(11,10,7))))
etc

Similarly, the output can be whatever is convenient for your language as log as it is printed, human-readable, and represents an ordered list of legal moves, each move being described by 1)file-name, 2)file-block-index, 3)new-disk-block-index
"ALPHA:1>6 BETA:2>9"
(0=>(0=>"ALPHA",1=>"1",2=>"6"), 1=>(0=>"BETA",1=>"2",2=>"9"))
["ALPHA",1,6,"BETA",2,9]
etc

Requirements
Your code must accept any size disk, and any number and size of files.
Inputs which do not describe legal initial filesystem states can lead to undefined behaviour.
Your code must produce a shortest moves solution, for any well-defined input.
All moves you produce must be legal; the filesystem must be in a valid state after applying each step you produce.
Your code must terminate for all valid inputs, i.e. it should never get stuck in a loop, the filesystem should be in a distinctly new state after each move is applied.
Where there exists more than one shortest solution, any can be selected as valid.
Shortest code wins. Please post at least one new nontrivial example input and its output with your code.

How would we find how long the "shortest sequence" is for an arbitrary disk? (Asking because if answer A says the shortest is 6 moves and answer B says the shortest is 5, does answer A then become disqualified?)

Breadth-first-search can provide a reference solution if needed.

This would probably work better as an [atomic-code-golf] challenge. You'll get more answers that way. Instead of shortest code, the winner would be the answer with the fewest disk writes.

Python 3, 295 bytes
S,F=eval(input());d=[0]*S;E=enumerate
for n,P in F:
 for j,p in E(P):d[int(p)]=n,j
Z=[(d,())]
while Z:d,p=Z.pop(0);any(e and(e[0],e[1]+1)in d and(S<j+2or(e[0],e[1]+1)!=d[j+1])for j,e in E(d))or print(p).q;{d[j]or exec("D=d[:];D[j]=e;D[k]=0;Z+=(D,p+(e,j)),")for j,_ in E(d)for k,e in E(d)if d[k]}

Try it online!

Another test case
Input:
   7 ALEF=6,4,0 BET=5,1 GIMEL=3

Initial disk state:
   A2 B1 __ G0 A1 B0 A0

Solution:
   ALEF:2>2
   ALEF:0>0
   BET:1>6
   ALEF:1>1

Visualized solution:
   A2 B1 __ G0 A1 B0 A0
   __ B1 A2 G0 A1 B0 A0
   A0 B1 A2 G0 A1 B0 __
   A0 __ A2 G0 A1 B0 B1
   A0 A1 A2 G0 __ B0 B1

Ungolfed version.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/