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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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
google hit: https://sites.google.com/a/campioncollege.com/it_eveningschoool/problem-solving-and-programming/desk-check-guide
you tube example https://www.youtube.com/watch?v=KpbvuAJG_xc
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:
1
2
3
4
5
6
7
8
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:
1
2
3
4
5
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:
1
2
3
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.