### simple exam questions about loops catch me out, any help

Have you ever had an exam question where a few nested for loops print their numbers and a new line in a certain succession and you get asked what the output might be? I get these wrong often simply for losing my train of thought and I have to do my exam on paper!

any tips on how to work out questions like the following with pen and paper...

so for example a question might be:

What is the output of

 ``123456789101112131415`` `````` for (int x = 0; x < 20; x++){ for (int y = 0 ; y < x : y++){ for(int z = x ; z < y ; z ++){ print("devonrevenge is awesome"+"/n"); } print ( x + y); } } ``````

I know these are easy but my head just loses focus while imagining the output, any ideas for a system to work this out with pen and paper?
Last edited on
Look up desk checking
In your example you would have columns for x,y,z and output (and line number)
I often simplify loops and replace them it with pseudocode:
Iteration one:
 ``12345678`` ``````for (int x = 0; x < 20; x++) { for (int y = 0 ; y < x : y++) { for(int z = x ; z < y ; z ++){ print("devonrevenge is awesome"+"/n"); } //Will never be executed print ( x + y); } }``````
Iteration 2:
 ``12345`` ``````for (int x = 0; x < 20; x++) { for (int y = 0 ; y < x : y++) { print ( x + y); //y is in range 0..x on each iteration of outer loop } }``````
Iteration 3:
 ``123`` ``````for (int x = 0; x < 20; x++) { print( x + [0..x) ); }``````
Last edited on
I wonder if a good optimizer would pick up on that.
 I wonder if a good optimizer would pick up on that.
Dead code elimination? Yes. It does a pretty good job on that.
Topic archived. No new replies allowed.