Presentation is loading. Please wait.

Presentation is loading. Please wait.

Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.

Similar presentations


Presentation on theme: "Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade."— Presentation transcript:

1 Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade 1”); grade1 = keyboard.nextInt(); System.out.println(“Please enter grade 2”); grade2 = keyboard.nextInt(); System.out.println(“Please enter grade 3”); grade3 = keyboard.nextInt(); System.out.println(“Please enter grade 4”); grade4 = keyboard.nextInt(); System.out.println(“Please enter grade 5”); grade5 = keyboard.nextInt(); System.out.println(“Thank you”); System.out.println(“The grades are ” + grade1 + “ ” + grade2 + “ ” + grade3 + “ ” + grade4 + “ ” + grade5); double avg = (grade1 + grade2 + grade3 + grade4 + grade5)/5.0; System.out.println(“Their average is ” + avg);

2 Lecture 7 Arrays An array is a data structure that represents a collection of the same type of data (homogeneous data). Declaring an array: datatype[] arrayRefVar; Example: //declare an array of double named myList double[] myList; datatype arrayRefVar[]; // This style is correct, but not preferred double myList[];

3 Creating an array: Example: myList = new double[10];
arrayRefVar = new datatype[arraySize]; Example: //create an array using new double[10]; myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array. We can declare an array and create it at the same time! datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10];

4 The array elements are accessed through the index
The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In our example, myList holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: myList[0] = 0; myList[1] = 4; myList[2] = 8; myList[9] = 36; First element is at index 0 and last element is at index 9 (one less than the number of elements) Exercise: Declare an array of type char called firstName And create the array so it contains exactly the number of letters in your first name.

5 This shorthand notation is equivalent to the following statements:
After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the value in myList[0] and myList[1] to myList[2]. myList[2] = myList[0] + myList[1]; Declaring, creating, initializing in one step: double[] theList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] theList = new double[4]; theList[0] = 1.9; theList[1] = 2.9; theList[2] = 3.4; theList[3] = 3.5;

6 Exercise Fill in the values of the elements of this array. A int[] A;
A = new int[5]; A[0] = 1; A[1] = 2; A[2] = A[0] + A[1]; A[3] = A[1] + A[2]; A[4] = A[2] + A[3]; A

7 Solution Fill in the values of the elements of this array. A int[] A;
A = new int[5]; A[0] = 1; A[1] = 2; A[2] = A[0] + A[1]; A[3] = A[1] + A[2]; A[4] = A[2] + A[3]; A 1 2 3 5 8

8 What is the output? int[] first = new int[8]; int[] second = new int[8]; int[] third = new int[8]; for (int j = 0; j < 8; j++) { first[j] = 2*j; second[j] = j + first[j]; third[j] = first[j] *second[j]; } //for j for (int k = 0; k < 8; k++) System.out.println(third[k]); } //for k

9 Exercise Can you find a way to print out all of the elements of the given array A without us having to write the println statement lots of times? A 1 2 3 5 8

10 Exercise Can you find the average temperature for the week without having to write out a separate addition for each element? temperature 65 68 64 68 70 68 70

11 Average Temperature double sum = 0.0; for(int i = 0; i < 7; i++)
sum = sum + temperature[i]; double avg = sum / 7.0; System.out.println(“Week average “ + avg);

12 Exercise Write a loop to find the values of the highest temperature and the lowest temperature for the week.

13 Solution // Initialize double max = temperature[0];
double min = temperature[0]; for(int i = 1; i < 7; i++) { if(temperature[i] > max) max = temperature[i]; if(temperature[i] < min) min = temperature[i]; }

14 Built-in Constants Smallest possible double value Double.MIN_VALUE
Largest possible double value Double.MAX_VALUE Smallest possible int value Integer.MIN_VALUE Largest possible int value Integer.MAX_VALUE

15 Length Attribute Array variables have a built in attribute name that can be used to find how many things the array can hold. int[] list = { 3, 2, 5, 7 }; for(int i = 0; i < list.length; i++) System.out.println(list[i]); For this array list.length is 4

16 Exercise Assume that cards is an array of type int values that has been created. Assume all elements have been assigned a value. Write Java statements to count how many even values are stored in the array. Use the .length attribute Declare needed variables

17 Solution int numEvens = 0; for(int i = 0; i < cards.length; i++) {
if(cards[i] % 2 == 0) numEvens++; }

18 Exercise Assume that a Scanner keyboard is created.
Assume that an array is created. int[] list = new int[10]; Write a loop to fill the array by prompting the user to enter an integer and assigning it into the next un-filled array slot.

19 Solution int[] list = new int[10]; int n;
for(int i = 0; i < list.length; i++) { n = keyboard.nextInt(); list[i] = n; }

20 Index Out of Bounds Create & initialize an array.
int[] cards = { 7, 10, 4, 8, 9 }; Each of these statements will crash your program with an array index out of bounds exception System.out.println(cards[5]); cards[6] = cards[6] + 1; cards[-1] = 0; cards[-7] = 10;

21 Exercise Assume two arrays of integers named A and B are created and initialized. Assume both arrays have the same length. Write a loop to count how many corresponding pairs of elements are identical. If A[0] equals B[0] increase count by one Etc…

22 Solution int count = 0; for(int i = 0; i < A.length; i++)
if(A[i] == B[i]) count = count + 1;

23 Exercise Given that M is an array of type char elements that has been initialized. Write Java statements to count how many times the letters X, Y, or Z are found in array M.

24 Solution Write Java statements to count how many times the letters X, Y, or Z are found in array M. int count = 0; for(int i = 0; i < M.length; i++) if(M[i] == ‘X’ || M[i] == ‘Y’ || M[i] == ‘Z’) count++;

25 Exercise Given that M is an array of type char elements that has been initialized. Write Java statements to declare and create a new array named copyOfM that is a duplication of the array named M.

26 Solution char[] copyOfM = new char[M.length];
for(int i = 0; i < M.length; i++) copyofM[i] = M[i];

27 findSum Method Write a method named findSum that accepts an array of integer values (assuming all elements are initialized) and return the integer sum of all elements in the given array.

28 findSum Method public static int findSum(int[] w) { int sum = 0;
for(int i = 0; i < w.length; i++) sum = sum + w[i]; return sum; }

29 Calling findSum public static void main(String[] args) {
int[] grades = {89, 73, 90, 94}; //call the method findSum with grades int sum = ; System.out.println(“Grade Sum: “ + sum); } public static int findSum(int[] W) int sum = 0; for(int i = 0; i < W.length; i++) sum = sum + W[i]; return sum;

30 Exercise Write a method named countN
that receives an array of type int values and a given integer value N, and return the number of times where the given value N appears in the given array.

31 Solution public static int countN(int[] data, int N) {
int numFound = 0; for(int i = 0; i < data.length; i++) if(data[i] == N) numFound++; return numFound; }

32 Exercise Write a method named indexOfFound that receives an array of type int elements and a target integer value T, and returns the smallest index of such an integer value if T is in the array; otherwise return -1. Example: list ={1, 2, 3, 4, 5} Then int index=indexOfFound(list, 2); index=indexOfFound(list, 6);

33 Solution public static int indexOfFound (int[] array, int t) { int s = -1; for (int i = 0; i < array.length; i++) if (array[i] == t) s = i; return s; }

34 Exercise Write a method named compare
that receives two arrays of type char values, and returns the type boolean value true if two arrays are the same; otherwise, returns false.

35 Solution public static boolean compare(char[] list1, char[] list2) { boolean sameArray = true; if (list1.length == list2.length) for (int i=0; i<list1.length; i++) if (list1[i] != list2[i]) sameArray = false; } else return sameArray;

36 We can pass arrays to methods, but it’s different from passing “primitive” parameters.
For a parameter of a primitive type value (int, float, double, etc.), the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. pass-by-value For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument. pass-by-reference

37 What is the output? public class Test {
public static void main(String[] args) int x = 1; int[] y = {1, 2, 3, 4, 5}; int a = 0; System.out.println("x is " + x); for (a = 0; a < y.length; a++) System.out.println("y[" + a + "] = " + y[a]); effect(x, y); for (a = 0; a < 5; a++) } //main public static void effect(int num, int[] nums) num = 1001; nums[0] = 5555; nums[3] = 3333; } //effect } //Test

38 What is the Output? public static void main(String[] args) {
int[] A = { 1, 2, 3, 4, 5 }; System.out.println(“Before”); printArray(A); foo(A, 2); System.out.println(“After”); } public static void foo(int[] G, int N) for(int i = 0; i < G.length; i++) G[i] = G[i] * N; public static void printArray(int[] W) for(int i = 0; i < W.length; i++) System.out.println(W[i]);

39 Swap Given two integer variables A and B.
How can you swap their values? Before example A = 5; B = 9; After A will be 9 and B will be 5

40 Swap Use a third integer variable int temp; temp = A; A = B; B = temp;

41 Using swapFirstLast Contents of A after the call… 1, 4, 3, 2, 5
int[] A = { 5, 4, 3, 2, 1 }; swapFirstLast(A); Contents of A after the call… 1, 4, 3, 2, 5

42 Solution public static void swapFirstLast( int[] data) { int temp;
temp = data[0]; data[0] = data[ data.length-1 ]; data[ data.length-1 ] = temp; }

43 Exercise Write a method named swap that receives an array of type int values and integer index i and integer index j, and swap the values contained in array slots with indices i and j. Example: int[] A = { 5, 4, 3, 2, 1 }; // Swap vales in slots #0, #4 swap(A, 0, 4); Contents of A after the call… 1, 4, 3, 2, 5 What would swap the 2 with 4? swap(A, ____, _____ );

44 Solution public static void swap(int[] data, int i, int j) { int temp;
temp = data[i]; data[i] = data[j]; data[j] = temp; }

45 What does this code do? public static void main(String[] args) {
int[] A = { 10, 8, 5, 2, 6, 13 }; int x = findIndex(A, 5); int y = findIndex(A, 4); int z = findIndex(A, 3); } public static int findIndex(int[] data, int startAt) int large = data[startAt]; int index = startAt; for(int i = 0; i < startAt; i++) if(data[i] > large) large = data[i]; index = i; return index;

46 What does this code do? public static void main(String[] args) {
int[] A = { 10, 8, 5, 2, 6, 13 }; int x = findIndex(A, 5); swap(A, 5, x); //the array A={10, 8, 5, 2, 6 ,13} x = findIndex(A, 4); swap(A, 4, x); // the array A={6, 8, 5, 2, 10, 13} }

47 What does this code do? public static void main(String[] args) {
int[] A = { 10, 8, 5, 2, 6, 13 }; int x; for(int i = A.length - 1; i > 0; i--) x = findIndex(A, i); if (x != i) swap(A, i, x); }

48 Selection Sort Sorts elements of array into order of smallest to largest. At each step find the largest value among the portion of the array not yet sorted. Swap that largest value with the element with the largest index among the portion of the array not yet sorted.

49 Selection Sort public static void selSort(int[] A) { int x;
for(int i = A.length - 1; i > 0; i--) x = findIndex(A, i); if (x != i) swap(A, i, x); }

50 Two-Dimensional Data Class of 5 students
Each student has 3 test scores Store this information in a two-dimensional array First dimension: which student 0, 1, 2, 3 or 4 Second dimension: which test score 0, 1, or 2

51 Declaring a 2D Array Give a second pair of square brackets to tell Java you want a 2D array Example: int[][] grades;

52 Creating a 2D Array Create array elements by telling how many ROWS and COLUMNS Example: grades = new int[5][3]; grades is a two-dimensional array, with 5 rows and 3 columns. One row for each student. One column for each test. Java arrays are row major, which means that we always refer to the row first.

53 Declare & Create Short Cut
Example: int[][] grades = new int[5][3];

54 Initializing Elements
// First student scores grades[0][0] = 78; grades[0][1] = 83; grades[0][2] = 82; Write assignment statements to fill-in the rest of the array.

55 Declare & Create & Initialize Short Cut
Example: int[][] grades = { { 78, 83, 82 }, { 90, 88, 94 }, { 71, 73, 78 }, { 97, 96, 95 }, { 89, 93, 90 } }; A Two-D Array is an array of arrays. Each row is itself a One-D array.

56 Row, Column Indices 1 2 3 4 78 83 82 90 88 94 71 73 97 96 95 89 93 Give both the ROW and COLUMN indices to pick out an individual element. The fourth student’s third test score is at ROW 3, COLUMN 2

57 What are the elements of the array table?
int[][] table = new int[3][4]; x = 1; for (row = 0; row < 3; row++) for (col = 0; col < 4; col++) { table[row][col] = x; x++; } //for col column row

58 Length Attribute Since each row is itself a One-D array you can ask each row to tell you its length. For our grades example: grades[0].length is 3 What are the values of: grades[1].length grades[2].length grades[3].length grades[4].length

59 Exercise: Average Overall
Find the average test score of all students’ test scores. Use grades.length to tell you how many rows in the 2D array. Use grades[0].length to tell you how many columns in the 2D array.

60 Exercise: Average Overall
int sum = 0; for(int r = 0; r < grades.length; r++) for(int c = 0; c < grades[0].length; c++) sum = sum + grades[r][c]; int avg = sum / (grades.length * grades[0].length); Does it matter if we used grades[r].length to get the number of columns?

61 Write a method that prints out the elements in a 2-D array (as they appear in the matrix)

62 Exercise: print 2-D array
public static void printArray(int[][] matrix) { for(int i = 0; i < matrix.length; i++) for(int j = 0; j < matrix[0].length; j++) System.out.print(matrix[i][j]+” “); System.out.println(“ “); }

63 Write a method that returns the maximum element in a 2-D array.
Things work pretty much the same way with 3-D arrays (and 4-D and …)

64 Exercise: find maximum in a 2D array
public static int findMax(int[][] matrix) { int max = matrix[0][0]; for(int i = 0; i < matrix.length; i++) for(int j = 0; j < matrix[0].length; j++) if ( matrix[i][j] > max) max = matrix[i][j]; return max; }


Download ppt "Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade."

Similar presentations


Ads by Google