Computer Programming 1


Base unit (holds course info)


Introduction to Programming

Programming is the art of writing computer programs. A computer program is a set of instructions telling a computer how to carry out a particular task. A programmer is a person who writes these instructions. Programming is not easy, so programmers get paid lots of money to program. When you have learnt to program then you will find that it is a very enjoyable activity.

There are two reasons that programming is difficult to learn. The first is that when you write a program you have to tell the computer exactly what to do. If you are imprecise or leave out any instruction then the program will not work. Humans don't need to be so precise in normal day to day living and this takes some getting used to.

The second reason is you must be able to think about the problem as a human sees it (high level view) and as the computer sees it (the low level view) and possibly many intermediate stages as well. Typical problems that are solved by computers are too complex if viewed at a low level all the time and so the process of looking at a problem at a high level is an exercise in managing complexity. In fact many terms are applied to this process of managing complexity, some that you'll here on this course are problem subdivision, modular programming and most especially object-oriented programming.

This ability to view a problem at many different levels is difficult, but we will teach you effective techniques to manage it.

So how are we going to teach you to program. Well initially we'll be using robots. You'll have to move robots around a screen. This is a very good practice at low level programming. You'll be programming the robots in Java so you will also be developing your knowledge of the Java programming language. This will occupy the first few weeks of the module.

Then we'll move on to small stand alone Java programs. During this period we'll cover

Along the way you'll get much practice at handling typical computer tasks.

Java and Object-Oriented design

Object-Oriented design as an approach to programming where the objects in a problem are identified and the program represents these objects and works by having different objects communicate with each other.

For example, you were selected for this course (Computer Applications at DCU) by a computer program. This program allocates places on a particular course to students with appropriate points. In this program, each student would have been an object, as would each university and each course. There might have been other objects as well.

This course is an introductory course in programming and won't be concerned about design, but you need to know a little about objects because Java is an object-oriented programming language.

Objects

An object is much like the objects you already know. The bed you slept in last night or the table you had breakfast on are both objects. An important distinction is made between a type and an instance. For example, a car is a particular type of object with four wheels and an engine, whereas my black citroen AX with the dodgy steering is an instance of a car. Another instance of a car is the "Chitty Chitty Bang Bang", or the Batmobile. All these instances are obviously different cars, but all belong to the same type, i.e. a car.

In Java an object type is introduced using the class keyword. Every Java program contains at least one object type (class). If this class is called House, then the Java program will be contained in a file called House.java.

Mechanics of a program

Assuming we want to create a House object we could create the following file (called House.java).

House.java
class House
{
}
This object doesn't do anything useful, we're only using it as an example. You can now compile this file typing javac House.java. This generates a new file called House.class. Compiling a program in fact translates House.java into a file that can be understood by the computer. This class file can now be used in a program.

House.java is called the Java or the source file, House.class is called the class file.

In the next section we will create useful programs and explain how a program works.


Robot World

RobotWorld is a space designed to help you to learn to program. We will briefly describe it here and then you will write programs in it.

An example RobotWorld is can be seen in the diagram to the right.

Robot Capabilities

Programming the Robots

Simple Instructions

Acknowledgements

Some of the ideas of RobotWorld have been borrowed from the book Karel the Robot, A Gentle Introduction to the Art of Programming by Pattis, Roberts, and Stehlik. The programs that make up robot world are based largely on the work of Jonathan M. Bourgeois.


Introductory Robot World Programs

Robot Programs must contain a class to describe the RobotWorld, e.g.

RobotProgram.java
public class RobotProgram extends RobotWorld
{
	public void setWorld()
	{
		wall(1, 4, "east", 10);
	}
}

The above program creates a RobotWorld which has a wall 10 cells in length that starts at (1,4) and ends at (9,4), a cell 10 places to the east.

We'll look at the program in a minute, but first let's look at the steps required to run it. (There is also a more detailed list of instructions that you may prefer.)

  1. Open a command prompt (also called an MSDOS window). You can do this by clicking the start button, select Run and then type cmd and click the OK button. A command prompt window will appear.
  2. Type H: to change to your network drive.
  3. Create the source file, RobotProgram.java. Here are the required steps:
    1. In the command prompt window, type notepad RobotProgram.java.
    2. The notepad program starts up and asks if you want to create a new file. Click Yes.
    3. Type in the above program exactly. Take special care about capital letters (Java is case sensitive).
    4. Save the file. You can simply close the window and you will be asked if you wish to save the file. Click Yes
  4. View the contents of the directory by entering the command dir. You should see the file RobotProgram.java. You can view the file itself with the command type RobotProgram.java. It should appear on the screen. Check again that it matches the above program exactly.
  5. Now compile the file to create the file RobotProgram.class. Type javac RobotProgram.java. If you get an error message contact a supervisor (or see the more detailed instructions). If there are no error messages, you should be able to see the class file, RobotProgram.class (use the dir command again).
  6. Run the program using the command, java RobotWorld RobotProgram. (If there is a problem, see the more detailed instructions). Assuming the program ran correctly, you should now see the world with the wall in the correct location. (Note that the Run and Step buttons are not relevant when there are no robots in the world as is the case here.)

The program itself

There are some supplementary programs contained in a file called robot.jar. This contains (among others) a class called RobotWorld. This program uses a class which is a particular subtype of RobotWorld and this is indicated in Java using the extends keyword:
public class RobotProgram extends RobotWorld		     	 		 			     	 	  						 	  
Most RobotWorld programs start this way. You give the class a name (in this case RobotProgram) and extend RobotWorld.

The class is always surrounded by an opening brace { and a closing brace } as shown below.

{
	:
	:

}

The braces contain the definition of the class. In this class one method is defined: setWorld(). A Method is a set of instructions to accomplish a task. Here there is just one instruction, wall(1, 4, "east", 10) in the setWorld() method. For the moment, most methods you encounter will be of the form

	public void methodName()
Methods also surround their contents (i.e. instructions) with braces
	public void setWorld()
	{
		wall(1, 4, "east", 10);
	}
The rules for these methods are part of the Java syntax which will be explained later.

Here are some other points to note:

Summary

To write a RobotWorld program:
  1. Create a class that extends RobotWorld.
  2. define a method setWorld() that contains the required instructions.
  3. Compile the program.
  4. Run the program.
Initially it will be easier to copy a program from the notes and change the relevant instructions.

Real Robots

Now that you can set up a world, let's see how to populate it with moving robots.

This time you'll need an extra class to describe your robot. Also the setWorld method will have to create an instance of the robot and place it in the world.

Looking at the Robot class first, it has the same form as the RobotWorld class, except that it extends Robot (instead of RobotWorld):

public class FirstRobot extends Robot
{
	public void run()
	{
		move();
		move();
		turnLeft();
		move();
		move();
		turnOff();
	}
}
And instead of a setWorld() method it has a run() method. This run() method contains the instructions for the robot. In this case, as soon as the robot starts, it will move forward two squares, turn left and then move forward two more squares before terminating.

Now let's look at the ExampleProgram class. The setWorld() method creates an instance of FirstRobot called jim and then places it in the world.

class ExampleProgram extends RobotWorld		     	 		 			     	 	  						 	  
{
	public void setWorld()
	{
		FirstRobot jim = new FirstRobot(); // Create a new robot called jim
		jim.place(4, 8, "north");  // place it in the RobotWorld
	}
}
An instance of a FirstRobot can be created using the new keyword.
	FirstRobot jim = new FirstRobot();
The expression new FirstRobot() creates an instance of FirstRobot. The first part of the instruction, FirstRobot jim, says that jim is a name that can refer to any object of type FirstRobot. In short the statement says that jim is a FirstRobot.

The next statement

	jim.place(4, 8, "north");
places the robot at cell (4,8) facing north.

Now if you run the program, you will see the robot at cell (4,8) and that it is facing north. If you press the run button it will execute all the instructions until it encounters the turnOff() instruction. If you run the program again, you can try the step button. This will only execute one instruction at a time.


Roll your own commands

The instructions, move(), turnLeft(), pickBeeper(), etc are methods of the underlying Robot class. By extending the Robot class your own robots can also use these methods.

However you can also write your own methods. For example, wouldn't it be nice to have a turnRight() instruction instead of having to use three turnLeft() instructions? Well you can create a turnRight method that executes three turnLeft() instructions:

	public void turnRight()
	{
		turnLeft();
		turnLeft();
		turnLeft();
	}
If you add this method to your robot class definition (before or after the run() method) then the run() method can use the turnRight() instruction.

Similarly, you might be tired of typing lots of move() instructions. Well you could have add moveFour() method that calls individual move() instructions:

	public void moveFour()
	{
		move();
		move();
		move();
		move();
	}
This method would be added to the definition of your robot class. To see a complete example, here is a program that defines and uses both these methods.

TestWorld.java
class TestWorld extends RobotWorld
{
	public void setWorld()
	{
		PowerRobot jane = new PowerRobot(); // create a new robot
		jane.place(5, 14, "south");  
	}
}

class PowerRobot extends Robot
{
	public void run()
	{
		moveFour();
		moveFour();
		turnLeft();
		moveFour();
		turnRight();
		moveFour();
		move();
		turnRight();
	}

	public void turnRight()
	{
		turnLeft();
		turnLeft();
		turnLeft();
	}

	public void moveFour()
	{
		move();
		move();
		move();
		move();
	}
}
Compile and run this program. Where does the robot end up?

Methods that see

Imagine if you had a robot that was plonked in the middle of an unknown world. It is quite likely that he would walk into a wall and shortly thereafter cease to exist.

What we want are some instructions to tell us if there is a wall in front, or maybe we would want to know which direction we're facing. We might like to know whether there was a beeper in our cell. The following methods give us information about the world

  1. frontIsClear() This method tells us if the space in front of the robot is clear or not.
  2. beepersPresent() This method tells us if there is a beeper in our cell.
  3. beepersInBag() tells us if the robot has any beepers.
  4. The following four methods tell us if the robot is facing a particular direction:
    1. facingEast()
    2. facingNorth()
    3. facingWest()
    4. facingSouth()
All these instructions return either true or false depending on the state of the robot.

These methods can be used in the if and while statements.


Decisions, decisions

See the notes on if statements.

Looping: round and round

The while statement allow us to repeat an instruction or a set of instructions as long as some condition is true.

For example, the following code fragment moves a robot forward as long as the cell in front is clear.

   while(frontIsClear())
      move();

This code can also be expressed in a flow Chart
In a flow chart, a rectangle indicates an instruction and a diamond indicates a decision. So the program comes to the frontIsClear() method and checks the result. If the cell in front is clear, then the move() method is executed and the program now loops back to the frontIsClear() method. This process is repeated until the cell in front is no longer clear (i.e. the robot has reached a wall or the edge of the world). At that point the frontIsClear() method returns false, the while loop exits and the program moves on to the next instruction.

The table below summarizes the while statement. Every time we come to a major Java statement we will summarize it in a similar way.

The while statement
Syntax
   while(condition)
      statement
Example
   while(frontIsClear())
      move();
Purpose To execute a statement while a condition is true.

Boolean values

Boolean values are values that can be true or false. All the methods that can "see" in the RobotWorld return boolean values. There are certain boolean operators that can be used with these boolean values. These operators are AND, OR and NOT and are represented by the characters &&, || and ! respectively.

How do you apply these? Well say you want to keep turning until you are facing east. There's a method, facingEast(), that will tell us whether we are facing east or not. We would like to keep turning until we are facing east, so the code would be

   while(NOT facingEast())
      turnLeft();

The idea is that you keep turning, eventually (after at most three turns) you will be facing east and the loop will exit.

This code is in fact illegal, you'd have to replace the NOT with a !, so the code becomes

   while(!facingEast())
      turnLeft();

Sometimes you might want to move forward as long as the cell in front was clear and as long as there was a beeper in the cell. How would you do that? That's where the AND operator (&&) comes in:

   while(frontIsClear() && beepersPresent())
      move();

This will cause a robot to move as long as the cell in front is clear and there is a beeper in the current cell.


ifs and buts (or whiles)

More interesting problems can be solved by combining if statements with while statements.

On to Java

The Robot programs that you wrote were in fact Java programs so you can already write Java programs. However these programs depended on other classes (contained in robot.jar) to run. We will now look at stand alone Java programs.

The biggest difference that you will notice is that the Robot class started executing at the run() method whereas standard Java programs start at a main() method.

This main method has the following declaration

	public static void main(String []args)
We'll look at the various parts of this declaration later but from now on, every stand-alone Java program that you write will have a main() method.

Getting Acquainted

We will start with some fairly easy programs.

Note that to use some of these programs you have to add

G:\lang\java\classes
to your classpath. Your complete CLASSPATH should then be
G:\lang\java\classes;g:\lang\java\classes\robot.jar;.

Types and expressions

At this stage you know: Now we're going to introduce two areas: data types and arithmetic.

First, let's look at another program (Line numbers have been added for clarity)

  1. public class Square
  2. {
  3. public static void main(String [] args)
  4. {
  5. System.out.print(5);
  6. System.out.print(" squared is ");
  7. System.out.print(5 * 5);
  8. }
  9. }

In line 5 we use the print method to print a number and in line 7 the computer performs a simple calculation. (* is the multiplication operator.)

Some other points

	System.out.print(5 * 5);
and
	System.out.print("5 * 5");
each produce a different output. Try each of them to see the difference. The quotation marks tell the computer to print whatever occurs between them exactly as shown.

The three print methods from the program can be combined into one statement

	System.out.print(5 + " squared is " + 5 * 5);

Expressions

When the computer calculates 5 * 5 it is evaluating an expression.

Here are some other expressions

ExpressionComment
11 Constant expression
21 / 3 21 divided by 3
2 + 4
5 - 3
8 % 3 8 mod 3 (i.e. the remainder
after 8 has been divided by 3)
Expressions
An expression in Java is the name given to a combination of operands and operators that results in a numeric value. In the expression 5 + 3 the numeric value of the expression is 8, the operand is the + and the operands are 5 and 3.
We will see more about expressions in the arithmetic topic.


Variables

Here is a program with a variable

Square.java
// Square.java
// written by CDaly

public class Square
{
	public static void main(String [] args)
	{
		System.out.print("Enter a number: ");
		int n = Console.readInt();
		System.out.println(n + " squared is " + n * n);
	}
}

The first statement of this program declares an integer variable number. The Console.readInt() method causes the program to wait until the user types something at the keyboard followed by the enter key.

Compile and run this program and type a number when prompted. The computer will print the square of this number. You might think that this is not very useful, but any scientist 50 years ago would be astounded that a machine could so easily calculate the square of a number.

Variable declaration

A declaration statement creates the variable number.
	int number;
The first part of the statement contains the type of the variable, in this case an int, or an integer. This is a whole number (i.e. it has no fractional part) which can be positive or negative, e.g. 7, 2000, -1 or 11. The second part of the declaration contains the name in this case number, which will be used to refer to the variable.

Some points to note

Assignment Statements

In the Square.java program above, the variable number got its value from the keyboard. It could also have a value assigned to it using an assignment statement:
	number = 24;
Note that this is not the mathematical equals sign, it is the assignment operator. The assignment statement assigns the value of an expression (in this case 24) to a variable (in this case number).

Here are some more assignment statements:

	n = 5 * 2;
	n = 2 * (5 + 3);
	sum = n + 2;
	n = (sum - 4 * 5) / 2;
Notice that a variable can be assigned to an expression that contains another variable e.g. sum = n + 2;. In fact you can have
	sum = sum + 3;
The assignment operator assigns or gives the value of the expression on the right to the variable on the left. The expression on the left can be any expression of a definite value, including the variable on the left if it has already been given a value.

In the statement sum = sum + 3 the assignment operator causes three to be added to whatever sum previously contained. The following section of code:

	int i;
	i = 2;
	i = i + 1;
	System.out.println(i);;
would print 3.

The statement i = i + 1; increases the value of i by one and is called incrementing the value of i or simply incrementing i. This is a very common operation and even has a special shorthand: i++.

An assignment statement always has the form

	LValue = RValue;
where the LValue is always a variable, and the RValue is always an expression.

Assignments and Declarations

A variable can have a value assigned to it when it is declared, e.g.
	int age = 20;
or
	int sum = 0;
Another shorthand is to declare several variables in a line. In this case commas separate the variables:
	int i, j, k;
When declaring variables in this way, you can also assign values to them. E.g.
	int i = 9, j = -2, k = 0;

Data Types

We've already seen the int data type. The following table shows the most common C++ data types

Data typeDescriptionRange (on a 32 bit computer)Examples
intInteger, a whole number-231 to 231-1 (approx. +/- 2 billion)5, -1, 4
floatFloating point number1038 to 10-383.14f, 8.0f -0.001f
doubleDouble precision
floating point number
10308 to 10-3083.14, 8.0 -0.001
charCharacter - e.g. a
letter or a digit
'e', '2', 'A', '?'

Some points

Another data type is the string. A string is a sequence of characters. A string may be a variable or a constant. A constant string is surrounded by double quotes, e.g. "Hello" or "Hi There". You have already seen this in the Hello program.

Special Characters

There are some special characters introduced by a backslash \:
'\n'newline
'\t'Tab character
'\a'Audible alert - print it to hear a beep.
'\b'Back space
'\"'A double quote
'\\'Two backslashes represent one backslash

Try printing out the following strings from a program (You could adapt the hello program)

"What is this\b-\b\b\b-"
"What's that noise\n\a"
"\tI need my space\n\t\t\t... lots of it\n\n"
"Who said \"2B or not 2B\" and how does one get a quote into a string"

Constants Vs Variables

The following code shows some constants and variables
	int numGoals;
	char letter;
	double price;

	price = 1.99;	// A double value is assigned to a constant double
	price = price * 0.75;	// a 25% discount

	numGoals = 3;	// a hat trick
	numGoals = numGoals + 2;	// Two more in injury time.

	letter = 'A';	// Character constants are enclosed in single quotes
	letter = 'z';
	letter = '\a';

Less common data types

C++ also has longs, shorts and long doubles. The last is a higher precision double and is used to give increased accuracy. The first two are variations on an int: shorts were used in the old days when memory was expensive, and longs are normally the same as ints so if you see code that contains these you know it was written by a programmer who learnt C++ a long time ago.

You won't use these types on this course (they are only mentioned here in case you come across some antique program you can't understand).


Arithmetic

In order to evaluate an expression you have to know some things about arithmetic operations. The arithmetic in C++ should be quite familiar, but you need to watch integer division.

First of all there are the normal arithmetic operators:
+Plus: addition
-Minus: Subtraction
*Multiplication
/Division
Note that all these are binary operators, that is, they take two operands. The minus sign can also act as the unary minus, as in -5, and simply changes the sign of an operand. Unary means it takes only one operand.

Most of these operators will produce expected results e.g.
ExpressionValue
2 * 3 + 511
(3 - 1) * 510
(4 + 8) / 26

However the result of some expressions involving division can be surprising
ExpressionValue
7 / 41
1 / 20
100 / 1010

The reason is that all these numbers are integers and cannot have fractional parts. The result of the division is always rounded down. There are two ways to solve this problem, one is to use the float data type, e.g.

	float x;
	x = 1.0/2.0;

This gives x a value of 0.5. Note that you must also specify floating-point numbers by using 2.0 rather than 2.

Another method is to make use of the modulus operator, %, which gives the remainder. E.g.
ExpressionValue
8 % 32
1 % 21
100 % 101100

Here is some code that uses the modulus operator.

   int x;
   int y;
   cin >> x;
   cin >> y;
   cout << x << " divided by " << y << " is " << x / y << endl;
   cout << "The remainder is " << x % y << endl;

Precedence

Precedence rules govern the order in which the arithmetic operations are carried out.
ExpressionValue
5 + 3 * 211
(5 + 3) * 216

For example, in the expression 5 + 3 * 2, the operation involving multiplication is carried out first because multiplication has higher precedence than addition. You can change this order by using parentheses: (5 + 3) * 2. This causes the addition to be carried it before the multiplication. If you are not sure which operator has precedence, use parentheses.


Control Flow

Normally the instructions are executed in sequence (one after the other). The control flow instructions can control the flow of execution.

The Control flow instructions are used to make decisions (if and switch statements) and to perform repetitive tasks: while, for and do while statements.


if else

Here is a program that shows how to use the if statement

Old.java
// Old.java
// written by CDaly
public class Old
{
   public static void main(String [] args)
   {
      int age;
      System.out.println("Enter your age:");
      age = Console.readInt();
      if(age > 200)
         System.out.println("That's older than me!");

      if(age < 5)
         System.out.println("You're a bit young for college.");

      System.out.println("Have a nice day");
   }
}

This program uses if statements to print out different messages depending on the value of age.

if statements have the form

	if(expression)
		statement1
	else
		statement2
If expression is true, then statement1 is executed otherwise statement2 is executed. The else part is optional (and does not occur in Old.java).

So in the code

	if(age < 5)
	   cout << "You're a bit young for college.";
the message is only printed if the expression age < 5 is true, so if, for example, age was 10, the message wouldn't be printed, if age was 3 it would be printed.

The expression age > 5 is called a conditional expression or Boolean expression as it can only have values true or false. These are named after George Boole, professor of Mathematics at UCC 150 years ago.

Because Java uses = as an assignment operator, it can't also use it as the equality operator, so if you want to test is age equal to 6, you use two equal signs:

	if(age == 6)
	   cout << "You're the same age as me!";
The expression if(age = 6) is a common error, and you are likely to make this mistake many times. Remember that the equality test operator is two equal signs.

Conditional expressions use logical operators

Relational operators
OperatorMeaning
<less than
>greater than
<=less than or equal to
>=greater than or equal to
Equality operators
OperatorMeaning
==equal to
!=not equal to

Here is another example using the if statement.

Pay.java
// Pay.java
// written by NBrophy
public class Pay
{
   public static void main(String [] args)
   {
      double pay, rate, hours;	// Declare the variables
      System.out.println("Enter hours worked :");	// Get the hours
      hours = Console.readDouble();

      System.out.println("Enter the rate per hour :");	// Get the hourly rate
      rate = Console.readDouble();

      pay = rate * hours;	// calculate the pay

      // if worked more than 40 hours, pay overtime
      if(hours > 40)
         pay = pay + (hours - 40) * rate / 2;	// add another 50% for overtime

      System.out.println("The pay is " + pay + " pounds.");
   }
}
In the above examples only one statement was executed if the condition was true. If you want more than one statement to be executed, then you create a block of statements by surrounding them with braces ({ and }). e.g. the code
	// if worked more than 40 hours, pay overtime
	if(hours > 40)
	   {
	   overtime = (hours - 40) * rate / 2;
	   pay = pay + overtime;
	   }
causes both the statements within braces to be executed. The block is treated as one statement. You can have as many statements as you like in a block, including if you want, just one.

Indentation

The if statement is normally shown as
	if(expression)
	   statement
Here the statement is indented to make it stand out. Although the compiler does not require a program to be indented, it does make the program much more readable. Any program that does not follow a consistent indentation style is much harder to read and is therefore a bad program. Please ensure that your programs are correctly indented, i.e. the indentation should help someone follow the logic of the program.

for Loops

The if statement allowed the program to selectively execute a statement. You could say that it provides the computer with its decision-making ability. However for loops are much more fun; they provide computers with their notorious ability to handle boring repetitive tasks.

Here is an example program that uses a for loop.

Squares.java
// written by CDaly

public class Squares
{
   public static void main(String [] args)
   {
      int i;
      for(i = 1; i <= 10; i++)
         System.out.println(i  + " squared is "  + i * i); 
   }
}

Remember that i++ is equivalent to i = i + 1.

This short program will print

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100
The println method is called 10 times, each time with a different value if i. I.e. the println method is controlled by the for loop. Let's examine the contents of the parentheses
	for(i = 1; i <= 10; i++)
The first part i = 1 assigns 1 to i, the second part i <= 10 tells the loop to keep going as long as i is less than or equal to 10, and the last part i++ says that i should increase by one each time.

Try changing these values and see what happens.


while Loops

The while loop also allows a programmer to control looping, though it has a more general structure than the for loop.

Formally the while loop is expressed as follows

	while(condition)
		statement
The statement will be executed as long as the condition is true. If the condition is initially false, then the statement won't be executed at all.

As with the for loop, a single statement can be replaced by a block of statements surrounded by braces.

Here is an example of pseudocode to do shopping

	while (there are items on the shopping list)
		find the item
		cross it off the list
pseudocode
pseudocode is a sequence of instructions that are intended to be read by a human. These instructions frequently look like normal program code and are easily translated into program code.

What type of loop should you use

In general use a for loop when you have an index variable, otherwise use a while loop.

Another (related) rule is to use a while loop when you don't know when the loop will exit, e.g.

Example.java
// Example.java
// written by CDaly
// Example using a while loop
public class Example
{
   public static void main(String [] args)
   {
      int x = 100;
      // as long as x is greater than ten, keep dividing it by two.
      while(x > 10)
         x = x / 2;

      System.out.println("After all that, x is " + x);
   }
}

Logical operators

Sometimes you might need more powerful conditions in your if statements. For example if you want to check that someone is a teenager you want to check that their age is greater than 12 and less than 20. To say this in C++, you use the logical operator, && as shown below
	if(age > 12 && age < 20)
The other logical operator is ||, the or operator. If we want to check that someone is not a teenager then their age must be either less than 13 or greater than 19. In C++ this is
	if(age < 13 || age > 19)

do while Loops

The do while loop has the conditional test at the end of the loop. It has the form
	do {
		statement1;
		statement2;
		} while(condition) ;
The statements within the do loop get executed at least once. The loop will continue to be executed as long as the condition is true.

This loop is not as common as the while loop, but it is useful sometimes, such as when you want to insist that a user enter a particular type of value.

Three.java
// Three.java
// written by CDaly
// this program keeps looping until the user enters a number divisible by three.
public class Three
{
   public static String void main(String [] args)
   {
      int num;
      do {
         System.out.println("Enter a number: ");
         num = Console.readInt();
	} while(num % 3 != 0) ;	// if not divisible by three, ask again

      System.out.println("Thank you, " + num + " is divisible by three");
   }
}

Here is another example

Guess.java
// Guess.java
// written by CDaly
// User must guess the number the computer is thinking of
public class Guess
{
   public static void main(String [] args)
   {
      int number = 38;	// user must guess this number
      int guess;
      do {
         System.out.println("Guess a number: ");
         guess = Console.readInt();
         if(guess < number)
            System.out.println("too low");
         else if(guess > number)
            System.out.println("too high");
         }while(guess != number) ;	// keep looping until it's correct.

	// The user guessed right (or we wouldn't have got here)
        System.out.println("Well Done");
}

the switch statement

the switch statement is used to select between a number of alternatives. E.g.

switch.cpp
// switch.cpp
// Demo the switch statement

#include <iostream.h>

void main()
{
	int choice;
	cin >> choice;
	switch (choice)
		{
		case 1:
			cout << "You entered one";
			break;
		case 6:
			cout << "You entered six";
			break;
		case 22:
			cout << "You entered twenty two";
			break;

		default:
			cout << "I only deal with 1, 6, and 22";
			break;
		}
}

The user enters a choice, then if it matches a particular case, the corresponding statements are executed. Note

The switch statement is useful for handling user input, i.e. where the program has to act differently depending on the value of the user input.

Boolean Expressions

All the flow control constructs that we've seen so have been controlled by a boolean expression. A Boolean expression is an expression that evaluates to either true or false. We have already seen how the relational operators can be used to give Boolean results, e.g. x > 5 is true if x is 10 and false if x is 2.

Logical operators, && and || take two Boolean expressions and return a Boolean value e.g.


Java has a Boolean data type called boolean, so you could have the following code segment
	boolean finished;

	finished = (i != j);	// finished is true if i is not equal to j
	if(!finished)
	   System.out.println("Not finished yet.");
the parentheses aren't necessary but make the assignment clearer.

Character Conditionals

So far all the relational operators that we have used apply only to numbers, either integers ints or floating point (float or double) numbers.

Relational operators can also be applied to characters (chars). This can be quite a powerful technique, see for example the following code:

	char c;
	c = Console.readChar();
	if(c >= '0' && c <= '9')
	   System.out.println(c + " is a digit");
	else if(c >= 'a' && c <= 'z')
	   System.out.println(c + " is a lowercase letter");
	else if(c >= 'A' && c <= 'Z')
	   System.out.println(c + " is an uppercase letter");
	else
	   System.out.println(c + " is not alphanumeric";	// not a digit or a letter
So although you can't multiply or divide characters, you can compare them with other characters.

Nested loops

As you can see loops are a useful construct for programmers. You can do even more if your loops contain loops. Try the following problems.

Flow Control Summary

Flow Control is the largest topic in this course and one of the most important. A lot of material has been covered.
So far we've seen all the control flow constructs in Java We've also seen that a boolean expression or condition decides the flow of the program (except in the case of a switch statement).

You can break out of any of the loops using the break statement. There is a similar but rarer continue statement which stops executing loop statements, but moves to the start of the loop ready to execute the next batch. In the case of the for loop, continue causes the index variable to be updated also.


Arrays

An array can hold a number of similar elements, such as the ages of all the students of a class.

An array is declared as follows

	int [] age = new age[20];
This declares an array named age of 20 integers, and is equivalent to creating 20 integer variables, age[0] to age[19]. (Note that arrays start at zero.)

Here are two more examples

	char [] name = new char[10]; // an array of 10 characters
	double [] results = new double[365]; // an array of 365 doubles
Each element of the array can be accessed using an index variable, so to print out all the ages you could use
	int i;
	for(i = 0; i < 20; i++)
	   System.out.println(age[i]);
Here i is the index variable, and the ith element is accessed using age[i]. Note that the first element is age[0].

Like the simpler data types, arrays can be initialised when they are declared.

	int [] age = {16, 12, 28, 15};
In this case, the array has been initialised, and the array has the following values
elementvalue
age[0]16
age[1]12
age[2]28
age[3]15