2 an instruction or group of instructions need to be repeated several times. 2 types of iteration:...

27
Lecture 11.2 Revision of Two-dimensional arrays and Iteration (loops)

Upload: louise-phillips

Post on 19-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

Lecture 11.2

Revision of Two-dimensional arrays

and Iteration (loops)

Page 2: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

2

Iteration (Repetition) An instruction or group of instructions need

to be repeated several times. 2 types of iteration:

1. You do not know how many times you will need to perform the instructions

Instructions contain words like while and until. In Java these could be “while” loop or “do-while”

loop2. You do know how many times you need to

perform the instructions. Instructions contain words like for, each and every In Java these could be coded using the “for” loop

Page 3: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

3

"While" Iteration We don't know how many times we may

have to add milk to get the perfect cuppa.

Java code syntax:

3. Add milk to cup 3.1. While drink is dark in colour 3.1.1. Add a splash of milk 3.1.2. Stir once with the spoon 3.2 Remove spoon from cup4. Add sugar

while (expression) { statement(s)}

This expression must always have a value either True or False.

Page 4: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

int i = 0;while (i < 5) { System.out.println("i is: " + i);}What does this output?

While example

i is: 0i is: 0i is: 0i is: 0i is: . . .How can we fix this problem?

Page 5: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

int i = 0;while (i < 5) { System.out.println("i is: " + i); i++;}The output will be:i is: 0i is: 1i is: 2i is: 3i is: 4Why does it not output the number 5?

While example

Page 6: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

Specification:Design and develop a Java program to accept as input: -

◦ A person’s name,◦ Percentage result for three tests.

Then output the name and the total of the three percentages.

Sample solution.We need to accept input four items of data, then check that data looks valid, and finally do some arithmetic before the final output.

While loops can be useful for validation

Page 7: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

1. Get unknown data. 1.1 get name. 1.2 get first percentage. 1.3 get second percentage. 1.4 get third percentage.2. Processing. 2.1 while first percentage is less than zero or greater than 100 2.2 get first percentage 2.3 end while. 2.4 while second percentage is less than zero or greater than 100 2.5 get second percentage 2.6 end while. 2.7 while third percentage . . .

Page 8: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

//1. Get unknown data. //1.1 get name. //1.2 get first percentage. //1.3 get second percentage. //1.4 get third percentage.//2. Processing. //2.1 while first percentage is less than zero or greater than 100 //2.2 get first percentage //2.3 end while.. . . //2.10 add together the three percentages//3. Output. //3.1 Output the total.

Page 9: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

//1. Get unknown data. //1.1 get name.String name = JOptionPane.showInputDialog(null, "enter name");

//1.2 get first percentage.int first = Integer.parseInt (JOptionPane.showInputDialog(null, "enter first percentage"));

//1.3 get second percentage.int second = Integer.parseInt (JOptionPane.showInputDialog(null, "enter second percentage"));

//1.4 get third percentage.int third = Integer.parseInt (JOptionPane.showInputDialog(null, "enter third percentage"));int total = 0;

Page 10: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

//2. Processing. //2.1 while first percentage is less than zero or greater than 100while (first < 0 || first > 100) {

//2.2 get first percentage first = Integer.parseInt (JOptionPane.showInputDialog(null, "incorrect: enter first percentage"));

//2.3 end while.}

. . . //2.10 add together the three percentagestotal = first + second + third;

//3. Output. //3.1 Output the total.System.out.println("For " + name + " The total is " + total");

Page 11: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

String name = JOptionPane.showInputDialog(null, "enter name");

int first, second, third;

do {

first = Integer.parseInt (JOptionPane.showInputDialog(null,

"enter first percentage"));

} while (first < 0 || first > 100);

do {

second = Integer.parseInt (JOptionPane.showInputDialog(null, "enter second percentage"));

} while (second < 0 || second > 100);

do {

third = Integer.parseInt (JOptionPane.showInputDialog(null, "enter second percentage"));

} while (third < 0 || third > 100);

int total = 0;

total = first + second + third.

System.out.println("For " + name + " The total is " + total").

"do-while" Iteration

Page 12: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

12

"For" Iteration Use this when we know how many times. Before we start chopping we do know how many

times we want to chop each carrot.

For loop syntax

3. Process vegetables 3.1. Select 4 juicy carrots 3.2. Chop carrots 3.2.1. For each carrot 3.2.1.1 Cut the carrot lengthways 3.2.1.2 Cut the carrot widthways 3.3 Add carrots to pan

for (initialisation; termination; increment) { statement(s)}

Page 13: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

for (initialisation;termination;increment) { statement(s)}

for (int i=0; i<5; i++) { System.out.println ("i is :" + i);}The output will be:i is: 0i is: 1i is: 2i is: 3i is: 4

The “for” loop

Page 14: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

Remember the Mini-Plu Puzzle?

1. Towards the centre of the puzzle there is a cage that requires two numbers that add up to seven.

2. Design and code a solution that prints out all the permutations of two numbers that add up to seven.

3. Hint: you can use two nested for loops.

Page 15: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

The hint is to use two nested for loops.2. Process – find pairs of numbers that add up to 7. 2.1 Loop 6 times for first number 2.2 Loop 6 times for second number 2.3 If 1st number plus 2nd number equals 7 2.4 Output the two numbers 2.5 End if. 2.6 End Loop 2.7 End Loop

Create your algorithm

Page 16: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

//2. Process – find pairs of numbers that add up to 7. // 2.1 Loop 6 times for first number

Coding: (just section 2)

Page 17: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

An array is a structure that holds multiple values of the same type. ◦ Allows us to use one variable name to access

multiple items of data. The length of an array (the number of

items it contains) is established when the array is created (at runtime).

After creation, an array is a fixed-length structure. ◦ Called a static data structure

Arrays

Page 18: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

One dimensional example import javax.swing.JOptionPane;public class inputAndReverse { public static void main (String args []) { int [] x = new int[4]; // create array size 4 int i; String inputNr; // ask for a number using size of array for the exit condition // increment the control variable by 1 each time for(i=0; i<x.length; i++){ inputNr =JOptionPane.showInputDialog(null,"Enter number"); x[i] = Integer.parseInt(inputNr); } // print a number using size of array for the initial value // reduce the control variable by 1 each time i-- // this means it will go through the array in reverse // from the last element of the array to the first element for(i=x.length-1; i>=0; i--){ System.out.println(x[i]); // the result is printing the input in reverse sequence } }

This [i] tells Java which array element to use

Page 19: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

Arrays of Other Types

Arrays can be used with any of the primitive types

char [] c = {'j','a','v','a',' ','i','s',' ', 'n','i','c','e'};

double [] values = new double[3];values[0] = 3.1;values[1] = 3.2;values[2] = 7.5;

String [] months = {"Jan", "Feb", "Mar"…"Dec"};

Page 20: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

2-Dimensional Arrays Multi-dimension arrays are declared and used

just like the 1D arrays we have used before.

int [] [] values = {{5, 6}, {7, 9}, {4, 2}};

int [] [] values = new int [3][2];values[0][0] = 5;values[0][1] = 6;values[1][0] = 7;values[1][1] = 9;values[2][0] = 4;values[2][1] = 2;

3 rows and 2 columns

• More dimensions could be added by using more indices i.e. more [n]

5 6

7 9

4 2

0

1

2

0 1

values[2][0]

Page 21: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

public class TimesTable { public static void main (String args []) { int [] [] table;

// create table with 13 rows and 13 columns table = new int[13][13]; for(int row=0; row < table.length; row++) { for(int col=0; col<table[0].length; col++) { table[row][col] = row * col; } // end for col } // end for row } // end main} // end class

table is a two-dimensional array.

The [row] [col] tells Java which array element to use

Jeliot will not run programs that contain a two-dimensional array.

Page 22: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

public class TimesTable { public static void main (String args []) { int [] [] table; int row, col;

// create table table = new int[13][13]; for(row=0; row<13; row++) { for(col=0; col<13; col++) { table[row][col] = row * col; } // end for col } // end for row

// print table for(row=0; row<13; row++) { for(col=0; col<13; col++) { System.out.print(table[row][col]); } // end for col System.out.println(); } // end for row } // end main} // end class

Note the similarity between the nested loops used to: -

a) calculate the table and

b) to print it out.

Page 23: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

Specification.Design and code a program to use a two dimensional array to hold data for 10 student results.The information will be entered at run time.There may be fewer than 10 but no more than 10 students.For each student the data must be: -

1. Seven digit student number,2. The result for six modules as a percentage,3. The overall percentage average.

The overall average must be calculated after the six module results have been entered.

Example program

Page 24: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

Valid data:1. 1234567, 40, 45, 50, 55, 60, 652. 9876543, 100, 90, 80, 30, 10, 0

Invalid data:3. 1234, 40, 45, 50, 55, 60, 654. 9876543, 101, 90, 80, 70, 30, 205. 1234567, 100, 90, 80, 70, 30, -1

Test data

Page 25: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

1. Get unknown data.1.1 get the number of students to be processed.1.2 create an array to hold student’s number and six percentage results for each student.1.3 loop once for each student

1.4 get student number1.5 loop six times

1.6 get module result1.7 end loop

1.8 end loop

Design

Page 26: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

//1. Get unknown data and declare variables.//1.1 get the number of students to be processed.

int nrStud= Integer.parseInt (JOptionPane.showInputDialog(null,"Nr of students"));

//1.2 create an array to hold student’s number and six percentage results for each student.

int [] [] studArray = new int[nrStud][7];//1.3 loop once for each student

for(int row=0; row<studArray.length; row++){ //1.4 get student number

studArray [row] [0] = Integer.parseInt (JOptionPane.showInputDialog(null,"Student number"));

//1.5 loop six times for(int col=1; col<=6; col++){

//1.6 get module result studArray [row] [col] = Integer.parseInt (JOptionPane.showInputDialog(null,"enter result "+col));

//1.7 end loop }//1.8 end loop

}

Code

Page 27: 2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need

Preparation for final test

Workshop 11a and Workshop 11b.

Next week Tuesday and Thursday will be two more examples of how to develop a Java program from a specification.