Purpose: Writing programs that use loops, selection and variables.
Goal: Complete as many of the exercise questions as you can. If you are keeping up, you need to do at least the core and robot questions. The additional questions are more challenging and are designed to stretch the more confident programmers. Don't worry if you can't do them now, but be prepared to come back and try them later on.
Feedback: It is important that you get feedback on your exercise answers so that you know they are correct, that you are not making common mistakes, that the program code is properly presented and that you are confident you have solved the problem properly. To do this, get your answers reviewed by a lab demonstrator during lab sessions.
NOTE: You must keep all exercise answers as they form a record of your progress. After the exams you may be required to hand-in all exercises and coursework answers, as part of the course assessment process.
These exercises require you to write programs that use loops, selection and variables.
Java has three kinds of loop:
a) The while loop
while (boolean-exp)
{
// Loop body
}
The loop body can be executed zero or more times. "boolean-exp" means an expression that evaluates to a boolean value (true or false). When you write a loop you provide a boolean expression appropriate to the loop you are trying to write.
b) The do-while loop
do
{
// Loop body
} while (boolean-exp) ;
The loop body can be executed one or more times. Do loops are used relatively infrequently but do provide a neater solution in situations where the statements in the loop body have to be executed at least once.
c) The for-loop
for ( init-exp ; test-exp ; exp)
{
// Loop body
}
The loop body can be executed zero or more times. For loops are typically used for counting. "init-exp" is an expression evaluated before the loop body is first executed and usually initialises a counter variable. "test-exp" is a boolean expression that is used to decide whether the loop body should be executed. If "test-exp" is true the body is executed, otherwise the loop terminates. "test-exp" is evaluated before the start of every execution of the loop body, not just once. "exp" is an expression evaluated after the loop body has been executed but before "test-exp" is evaluated again. "exp" is used to increment the loop counter.
All the loops have a body bracketed by braces (curley brackets) - make sure you always include the braces. Loop bodies can contain any statement sequence, including nested loops.
Remember that most loops, and certainly those needed by these exercises, must have a properly determined termination condition. This means that one or more statements in the loop body should have some affect on the boolean expression controlling the loop execution. In particular, the expression should evaluate to false within a reasonable number of executions of the loop body.
Selection is provided by the if statement:
if (boolean-exp)
{
// Statements executed if boolean-exp is true
}
This allows the conditional execution of a statement sequence. A variation is the if-else statement:
if (boolean-exp)
{
// Statements executed if boolean-exp is true
}
else
{
// Statements executed if boolean-exp is false
}
This allows a choice between two different statement sequences.
Boolean expressions are created using relational and boolean operators. Relational operators are used to compare values such as integers:
a < b |
less than |
a > b |
greater than |
a == b |
equal to |
a <= b |
less than or equal to |
a >= b |
greater than or equal to |
Boolean operators combine boolean expressions:
a && b |
and |
a || b |
or |
!a |
negation (not) |
Operators can be combined to create more complex boolean expressions:
a < 0 && b > 2
but you need to make sure that the operators are evaluated in the correct order. If in any doubt bracket the sub-expressions:
(a < 0) && (b > 2)
Variables allow values to be stored and manipulated. Variables must be declared and initialised before being used:
int x = 0 ; double b = 1.234 ;
A variable declaration must include a type, while the variable name should reflect the use of the variable (so one letter variable names such as those above are not ideal! Having said that, loop counter variables are often given a single character name.) A variable name must start with a letter (a-z), followed by any combination of letters and numbers. Punctuation symbols, expect for underscore, are not allowed, and there cannot be spaces in a name. By convention, variable names should start with a lowercase letter.
Integer variables (type int) can be incremented (increased by one) using the operator ++ and decremented (decreased by one) using --:
x++ ; // increment x y-- ; // decrement y
For more detail about loops, the if statement, expressions, operators and variables see chapters 2, 28 and 29 in the text book.
The following are examples of questions and answers, to show how the Java syntax works, and to illustrate the kinds of programs you should be writing. Pay very careful attention to the layout of your program and the use of indentation. You will be asked to tidy up poorly presented code.
Remember, source code is primarily for people to read and understand.
Example 2.1 Write a program using a while loop to print out a message 10 times. Each message should be on a separate line using this format:
1: A message 2: A message 3: A message and so on...
Numbering should start from 1. Substitute whatever message you like.
Answer:
Take care to get all those loop conditions and counter increments correct. Easy to make mistakes...
// Written by A.Person, October 2002
// Answer to Ex2 example question 1
class Q2_1
{
public void displayMessages()
{
int n = 0;
while (n < 10)
{
n = n + 1; // or n++;
System.out.print(n);
System.out.print(": ");
System.out.println("Hello World");
}
}
public static void main(String[] args)
{
Q2_1 q2_1 = new Q2_1();
q2_1.displayMessages();
}
}
You can also have less have verbose variations such as:
// Written by A.Person, October 2002
// Alternative answer to Ex2 example question 1
class Q2_1a
{
public void displayMessages()
{
int n = 0;
while (n++ < 10)
{
System.out.println(n + ": Hello World");
}
}
public static void main(String[] args)
{
Q2_1a q2_1a = new Q2_1a();
q2_1a.displayMessages();
}
}
With both programs note the use of indentation and the way braces have been
lined up. Use of indentation, blank space and blank lines has no effect of the
execution of programs, but their proper use greatly increases readability and
makes mistakes less likely.
Example 2.2 Repeat Example 2.1 using a do loop.
Answer:
// Written by A.Person, October 2002
// Answer to Ex2 example question 2
class Q2_2
{
public void displayMessages()
{
int n = 0;
do
{
n = n + 1;
System.out.println(n + ": Hello World");
}
while (n < 10);
}
public static void main(String[] args)
{
Q2_2 q2_2 = new Q2_2();
q2_2.displayMessages();
}
}
Be careful to get the loop counting correct.
Example 2.3 Repeat Example2.1 using a for loop.
Answer:
// Written by A.Person, October 2002
// Answer to Ex2 example question 3
class Q2_3
{
public void displayMessages()
{
for (int n = 0 ; n < 10 ; n++)
{
System.out.println((n+1) + ": Hello World");
}
}
public static void main(String[] args)
{
Q2_3 q2_3 = new Q2_3();
q2_3.displayMessages();
}
}
Again, watch out for the loop counting.
Example 2.4 Write a program using loops to display the following:
**** **** **** ****
You may only print one character at a time.
Hint: nested loops.
Answer:
Note that you can only output characters from left to right across a line, and each line must be complete before starting the next. You cannot move the output position around to output characters in an arbitrary position.
// Written by A.Person, October 2002
// Answer to Ex2 example question 4
class Q2_4
{
public void displayShape()
{
for (int m = 0 ; m < 4 ; m++)
{
for (int n = 0 ; n < 4 ; n++)
{
System.out.print('*');
}
System.out.println("");
}
}
public static void main(String[] args)
{
Q2_4 q2_4 = new Q2_4();
q2_4.displayShape();
}
}
While loops can be used instead.
Questions like this one, which involve displaying a shape made from printed characters, all rely on spotting the pattern needed to draw the shape. The pattern then needs to be translated into an algorithm using loops and selection, in order to output the correct characters in the correct sequence (character-by-charactor across a line, line-by-line). With this example the pattern is straightforward:
repeat 4 times
{
a loop that outputs four stars
a newline
}
You answer all the following questions!
Q2.1 Write a program using a while loop to display the twelve times table, like this:
1 * 12 = 13 2 * 12 = 24 3 * 12 = 36 and so on.
Note: the multiplication operator is *.
Q2.2 Repeat Q2.1 using a do loop.
Q2.3 Repeat Q2.1 using a for loop.
Q2.4 Write a program using loops to display the following:
***** * * * * *****
You may display only one character at a time (i.e., you cannot have a statement such as: System.out.println("*****"); to output an entire line at once. A loop must be used to write characters one at a time). Space characters should be output to display the spaces inside the shape.
Hint: nested loops.
Q2.5 Write a program using loops to display the following:
* ** *** **** ***** ******
You may display only one character at a time. Note, you don't need to output spaces after the last star on any line.
Q2.6 Write a program using loops to display the following:
***** ***** ***** ***** ***** ***** *****
You may display only one character at a time.
Q2.7 Write a program to display the following:
******** * * * **** * * * * * * **** * * * ********
You may print only one character at a time.
Hint: Find out about the if statement.
Q2.8 Write a program using loops to display the following:
*#*#*# #*#*#* *#*#*# #*#*#* *#*#*# #*#*#*
You may display only one character at a time.
Q2.9 Write a program using loops to display the following:
* * * * * * * * * * * *
You may print only one character at a time.
Q2.10 Write a program using loops to display the following:
******* #* * ##* * # #* * # #* * # #** # #* #######
You may display only one character at a time.
2.11 Write a drawing program that draws a graph showing the curves y=sin(x), y=cos(x) and y = tan(x). Include properly labelled axes, to look like this example (this shows the curve y=x^2+1):

Choose suitable ranges for the axes of the graph to show the curves to the best effect.
Hints: Break the drawing of the graph down into a series of steps: draw the x-axis, label the x-axis, draw the y-axis, label the y-axis, etc. Use loops to draw the curves using points. A point can be drawn using a 1x1 rectangle. Remember that on the window co-ordinate system (0,0) is top left, so you will have to take care when you compute the coordinates of lines and points..
Q2.12 Follow the instructions on the robot program web page to copy, compile and run the basic robot program (see the link on this page - http://www.cs.ucl.ac.uk/staff/G.Roberts/1b1a/).
Then write the robot code needed to move the robot to the door from any location in the room (i.e., make sure you can write the program discussed in the lectures).
Q2.13 Write a robot program to move the robot to the door from any location in the room but this time when the room contains obstacles. The obstacles can be placed randomly or be placed to change the shape of the room (for example, to make the room T-shaped).
Q2.14 Write a drawing program to plot a spiral using a series of points, like this:

Hint: If you can draw a circle, just keep changing the radius.
Q2.15 Write a method to display rectangles of any character like the following:
***** ***** %%%%%%%%% ***** %%%%%%%%% ***** or %%%%%%%%%
The method parameters should give the number of rows and columns, and the character to use.
Use the method to display various rectangles of different sizes.
Q2.16 Modify the drawing program to include methods for drawing rectangles and triangles of any size and at any location. Draw a picture using the methods.