您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)

 

Content Index

Content Page # 11

Examples of algorithms

Finding the sum of a set of numbers

In this example we will specify the steps necessary to perform the task of finding the sum - adding up a set of numbers.

The proposed solution is to add numbers one a time to the sum (- a running total ) until all the numbers are added. The sum will be output.

 We will need some variable to store the numbers to be added e.g. number, and a variable to hold the sum e.g. sum.

Set sum to zero

While there are numbers to add

Get the next number

Add the number to sum

 Output the sum

Find the smallest number

We will specify the steps necessary to perform the task of finding the smallest of a set of numbers.

The proposed solution is to compare one number at a time to a smallest so far. If a smaller value is found to assign it to the smallest, and continue until all numbers have been processed in this way.

The variables in this example will be nextNumber  and smallest

Intialise smallest

While there are numbers to compare

If nextNumber < smallest

Assign nextNumber to smallest

Output the smallest

Exchange values of two variables

We would like to swap the values of two variables a and b so that after the algorithm has executed the value that was in a is now in b and vice versa.

The proposed solution is to introduce a new temporary variable temp to assist in this process. Then the steps will be as follows:

Save the original value of a in temp

Assign to a the original value of b

Assign to b the value that is stored in temp  

These algorithms would need to be further refined. In the present form they represent a general solution and more work is required.

In the first two examples the number of numbers to be processed was arbitrary ' While there are numbers to add', While there are numbers to compare'. How will the end of input be determined? It could be a special sentinel value or there may be another input from the user in response to a request 慳ny more numbers? (Y/N)?etc. This needs to be specified

The type of variables and most probably further variables will be required.

The actual format of the output e.g. the text of the messages displayed with the output etc.

At each stage the developer should test the algorithm specifying some test data and going through the steps to see if the required outcome will be achieved making any necessary corrections. This test data should be kept and used to test the actual program.  

Once a correct algorithm has been specified, the process of producing a working Java program is straightforward' 

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg