90 likes | 209 Views
CSC 1051 – Data Structures and Algorithms I. Arrays as Parameters. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/
E N D
CSC 1051 – Data Structures and Algorithms I Arrays as Parameters Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus CSC 1051 M.A. Papalaskari, Villanova University
Arrays as Parameters • An entire array can be passed as a parameter to a method (just like any other object). For example: int[] ratings = {4, 3, 3, 1, 4, 3, 1, 0, 3, 4}; System.out.println(average(ratings)); • Assumes a definition for method average(), for example: public static double average(int[] a) { for (intnum: a) sum += num; return ((double)sum/a.length); } CSC 1051 M.A. Papalaskari, Villanova University
Try this: Write a method that adds 2 to the value of each element in an array of type double[]. CSC 1051 M.A. Papalaskari, Villanova University
Command-Line Arguments • It turns out we have been using arrays as parameters all along! • public static void main (String[] args) CSC 1051 M.A. Papalaskari, Villanova University
Command-Line Arguments • It turns out we have been using arrays as parameters all along! • These values come from command-line arguments that are provided when the interpreter is invoked • jGrasp calls them “Run Arguments” public class Test { • public static void main (String[] args) • { • System.out.println (); • System.out.println (" " + args[0]); • System.out.println (" " + args[1]); • } • } CSC 1051 M.A. Papalaskari, Villanova University
Copying elements vs. copying array variables: What does it mean to “copy an array”? • Suppose we have two arrays: int[] a = {147, 323, 89, 933}; int[] b = {100, 200, 300, 400}; Afterwards, what is the effect of the following? for (inti=0; i<a.length; i++) a[i] = b[i]; a = b; a[1] = 1111; b[2] = 2222; CSC 1051 M.A. Papalaskari, Villanova University
1) Copying elements: 0 1 2 3 a 147 323 89 933 0 1 2 3 b 100 200 300 400 What changes? for (inti=0; i<a.length; i++) a[i] = b[i]; a[1] = 1111; b[2] = 2222; CSC 1051 M.A. Papalaskari, Villanova University
2) Copying array variables: 0 1 2 3 a 147 323 89 933 0 1 2 3 b 100 200 300 400 What changes? a = b; a[1] = 1111; b[2] = 2222; CSC 1051 M.A. Papalaskari, Villanova University
Array parameters revisited • How is using an array as a parameter like “copying an array”? public class TestAddTwo{ • public static void main (String[] args) { • double[] b = {0.5, 0.6, 0.7}; • addTwo (b); • for (double num: b) • System.out.print(" " + num); • } • private static void addTwo(double[] a) { • for (inti = 0; i<a.length; i++) • a[i] += 2; • } • } CSC 1051 M.A. Papalaskari, Villanova University