Next page | Contents page |

Exercise 5 - for loops

(a) Modify our Squarer program so it outputs a table of squares of all the odd numbers from 1 to 49 inclusive.

(b) What, if anything, is wrong with each of the following? In each case say (i) whether it would compile, (ii) whether it would run, and (iii) whether it is likely to produce the intended result. If the answer to any of those is no, explain why.

  1. 	int i; for (i = 0; i < 10; i++);
    		  System.out.println (i);
    
  2. 	for (int i = 0; i < 10; i += 1);
    		System.out.println (i);
    
  3. 	for (int i = 0; i < 10; )
    	{ System.out.println (i); i++ }
    
  4. 	int i; /* followed by some code to set i, etc ... */
    	for ( ; i > 0; i--) System.out.println (i);;
    
  5. 	boolean checked; 
    	/* ... then some code to set the value of checked ... */
    	if (checked = true) process ();
    

This exercise includes some commonly-made mistakes which can be hard to spot when you make them. It should help you to avoid them in future.

Next page | Contents page |