COSC: Chap 10.4 Iterating through arrays

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

10.4.2: Iterating through an array example: Program that finds the max item

... // Determine largest (max) number (1) maxVal = userVals[0]; // Largest so far (2) for (I = 0; I < NUM_ELEMENTS; ++i) { (3) if (userVals[I] > maxVal) { (4) maxVal = userVals[i]; } } System.out.println("Max: " + maxVal); return; } } (1) Before entering the loop, maxVal must be initialized to some value because max will be compared with each array element's value. Using the first element, or any element in the array. (2) During each iteration, (3) if the array's current element value is larger than the max seen so far, (4) the program writes that value to maxVal (akin to being able to carry only one item as you walk through a store, replacing the current item by a better item whenever you see one)

Figure 10.4.1: Common for loop structure for iterating through an array.

// Iterating through myArray for (i = 0; i < numElements; ++i) { // Loop body accessing myArray[i] } NOTE: - index variable: i initialized to 0 - loop expression: i < N rather than i <= N

10.4.1: Array iteration. Given an integer array myVals of size N_SIZE (i.e. int[ ] myVals = new int[N_SIZE]), complete the code to achieve the stated goal. 1. Determine the minimum number in the array, using the same initialization as the maximum number example above. minVal = ______ ; for (i = 0; i < N_SIZE; ++i) { if (myVals[i] < minVal) { minVal = myVals[i]; } } 2. Count how many negative numbers exist in the array. cntNeg = 0; for (i = 0; i < N_SIZE; ++i) { if ( ______ ) { ++cntNeg; } } 3. Count how many odd numbers exist in the array. cntOdd = 0; for (i = 0; i < N_SIZE; ++i) { if ( (myVals[i] % 2) == 1 ) { _______________________________ ; } }

Solutions: 1. myVals[0] minVal must be initialized to an element in the array. Using the 0'th element ensures the code works for any size array. 2. myVals[i] < 0 or myVals[i] <= -1 Either myVals[I] < 0 or myVals[i] <= -1 would be correct to check if an element's value is negative. 3. cntOdd++ For each odd value found, cntOdd is incremented.

Accessing out of range index

Trying to access an array with an out-of-range index results in a runtime error that causes the program to terminate. - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

Benefit of loop structure

each array element is accessed as myArray[i] rather than the more complex myArray[i-1] -Iterate through arrays to determine some quantity about the array's items

10.4.2: Prompt user to populate array

import java.util.Scanner; public class ArrayMax { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); final int NUM_ELEMENTS = 8; //Num of elements int[] userVals = new int[NUM_ELEMENTS]; // Array of user numbers int i = 0; // Loop index int maxVal = 0; // Computed max // Prompt user to populate array System.out.println("Enter " + NUM_ELEMENTS + " integer values..."); for (i = 0; i < NUM_ELEMENTS; ++i) { System.out.print("Value: "); userVals[i] = scnr.nextInt(); } ...

10.4.3: Print the sum and average of an array's elements.

import java.util.Scanner; public class ArraySum { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); final int NUM_ELEMENTS = 8; // Number of elements int[] userVals = new int[NUM_ELEMENTS]; // User numbers int i = 0; // Loop index int sumVal = 0; // For computing sum // Prompt user to populate array System.out.println("Enter " + NUM_ELEMENTS + " integer values..."); for (i = 0; i < NUM_ELEMENTS; ++i) { System.out.println("Value: "); userVals[i] = scnr.nextInt(); } // Determine sum sumVal = 0; for (i = 0; i < NUM_ELEMENTS; ++i) { sumVal = sumVal + userVals[i]; } (1) System.out.println("Mean: " +(sumVal/NUM_ELEMENTS)+"\nSum: " + sumVal); return; } } -(1) Just change what is printed out, and calculate the mean.

Figure 10.4.3: Iterating through an array example: Program that finds the sum of an array's elements.

import java.util.Scanner; public class ArraySum { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); final int NUM_ELEMENTS = 8; // Num of elements int[] userVals = new int[NUM_ELEMENTS]; // User numbers int i = 0; // Loop index int sumVal = 0; // For computing sum //Prompt user to populate array // Determine sum (1) sumVal = 0; for (I = 0; I < NUM_ELEMENTS; ++i) { (3) sumVal = sumVal + userVals[i]; } System.out.println("Sum: " + sumVal); return; } } - For computing the sum, (1)the program initializes a variable sum to 0, (3) then simply adds the current iteration's array element value to that sum.

Printing Array from last element to first element

public class arrayOutput { public static void main (String [] args) { final int NUM_ELEMENTS = 3; int [] userVals = new int[NUM_ELEMENTS]; int i = 0; userVals[0] = 3; userVals[1] = 5; userVals[2] = 9; for (i = NUM_ELEMENTS - 1; i >= 0; --i) { System.out.println(userVals[i]); } return; } }

Printing negative elements as positive

public class arrayOutput { public static void main (String [] args) { final int NUM_ELEMENTS = 4; int [] userVals = new int[NUM_ELEMENTS]; int i = 0; userVals[0] = -1; userVals[1] = 3; userVals[2] = -5; userVals[3] = 7; for (i = 0; i < NUM_ELEMENTS; ++i) { if (userVals[i] < 0) { userVals[i] = -1 * userVals[i]; } System.out.println(userVals[i]); } return; } }

Printing only negative elements from array

public class arrayOutput { public static void main (String [] args) { final int NUM_ELEMENTS = 4; int [] userVals = new int[NUM_ELEMENTS]; int i = 0; userVals[0] = -2; userVals[1] = 3; userVals[2] = 5; userVals[3] = -8; for (i = 0; i < NUM_ELEMENTS; ++i) { if (userVals[i] < 0) { System.out.println(userVals[i]); } } return; } }


Kaugnay na mga set ng pag-aaral

Esthetics Milady Foundations CH 5 Infection Control

View Set

Wellness Chap 6 Body Composition.

View Set

Management 371 Test #2 -- Part 1

View Set

types of houses, Types of houses (1)

View Set

America's First Government Civics Test

View Set