veltaandrg / JavaExercises

0 stars 0 forks source link

Long loops #2

Open RodionGork opened 9 years ago

RodionGork commented 9 years ago

Write a for-loop with a large number of simple iterations, like this:

    int a = 0;
    for (int i = 0; i < 100000000; i++) {
        a += i;
    }
    System.out.println(a);

Check how long it is executed on the usual computer. Remember how many simple iterations are done per seconds (roughly, of course).

Now imagine the loop with seemingly stupid condition i > i + 1, like this:

    int i = 0;
    while (true) {
        if (i > i + 1) {
            break;
        }
        i++;
    }
    System.out.println(i);

How long it will take to finish (roughly)?
What number would be printed at the end?
How long it will take if we change the type of i to long (probably you will not be able to check this by direct experiment so you need to be cunning enough).