Lecture 15 Log into Windows/ACENET. Use a web browser to download today's exercise program. Go to course webpage http://csserver.evansville.edu/~hwang/s11-courses/cs205.html Right-click on TestStatsProgram.zip link. Save target/link to Documents -> Visual Studio 2010 -> Projects folder. Browse to TestStatsProgram.zip, right-click on it and select Extract All... and extract project folder Double-click into the TestStatsProgram folders to the solution file, then double-click it to start up VS. Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 1 Outline Programming Assignment 4 clarifications Reminder: Programming Assignment 4 due on Wednesday by 4:30pm. Questions? Arrays Declaration and creation arrays Array element access Accessing all array elements using for-loops Array parameters Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 2 Programming Assignment 4 ∞ =4 ∑ k=0 k −1 1 1 1 1 1 =4 − − 2 k1 1 3 5 7 9 In the above summation, k (the loop counter) starts at 0, rather than 1, so to sum numberOfTerms terms (the number input by the user), the final value of k in ComputePI should be (numberOfTerms-1) rather than numberOfTerms. This can be done by making the loop counter test (k < numberOfTerms) rather than (k <= numberOfTerms). Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 3 Programming Assignment 4 The example output in the assignment sheet counts 0 to numberOfTerms. (i.e., (numberOfTerms+1) terms). With only numberOfTerms terms, the output would be: Enter the number of terms for this approximation of PI: 10 10 terms give an approximate value for PI of 3.041840. Enter the number of terms for this approximation of PI: 100 100 terms give an approximate value for PI of 3.131593. Enter the number of terms for this approximation of PI: 1000 1000 terms give an approximate value for PI of 3.140593. Enter the number of terms for this approximation of PI: 0 Good­bye! Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 4 Programming Assignment 4 Although you can use Math.Pow (-1, k) to compute the numerator of each term, doing so is inefficient. All that is needed is for the sign to alternate between iterations. Here are a few ways to do so: Use an integer variable for the numerator of the term that is initially 1.0 and negate it (using unary minus) after each term is computed. After computing a term, use an if-statement with a condition so that the if-body adds the term and the else-body subtracts the term. E.g., test whether k is even or odd (evenly divisible by 2); or test a boolean flag that is initially true and negated it (using logical not) after the if-statement. Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 5 TestStats Program Examine file TestStats.cs. So far, we have dealt with variables that are a single value. But sometimes it is inconvenient to have unique names for every memory location. For today's example, we want to compute the average of a number of test scores and the difference of each test score relative to the average for a class of students. For CS 205, we have 11 students, so we have variables named score1, score2, score3, ... Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 6 TestStats Program To solve our problem, there are separate statements to read in a test score from the console into each of the variables. (Note that the GetTestScore method returns the input value rather than passing it back.) To compute the average, all the variables are summed together using a very long addition expression (score1+score2+score3+...). Then there are separate statements to display all the test scores and their differences. This it tedious and error prone. And not very flexible: what if the class has 50 students? 100? Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 7 Arrays What we need is a way to name a collection of values and a way to access an individual item in the collection using that name. An array is a collection of items that can be accessed by giving the position (or index) of the value in the collection. Formally, an array is a fixed-size ordered collection of items (called the elements) of the same type. Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 8 Array Declaration and Creation Unlike the primitive types (int, double, etc.), an array (in C#) must be created before it can be used. Array variables are declared and array objects are created using the following syntax: array variable declaration array creation statement <type> [] <name> = new <type> [ <size> ]; always empty where type is the element type and size is the number of elements in the created array. Note that the [ ]'s in the type name are empty. Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 9 Array Declaration and Creation For our example, we could declare: double [] score = new double [11]; Even better would be to ask the user: string userInput; int numStudents; Console.Write ("Enter the number of students: "); userInput = Console.ReadLine(); numStudents = int.Parse(userInput); double [] score = new double [numStudents]; score array's size is numStudents Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 10 Array Element Access To access an array element, you give the array name and the index of the element. Almost all programming languages (including C#) use square brackets for indexing: <array name>[<index>] as the syntax for accessing an array element. This expression can be used on either the left of an assignment (as a variable to set the array element value) or the right side (as an expression). Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 11 Array Element Access Here is one way of looking at what an array is: double [] score = new double [11]; score[0] score score[1] score[2] score[10] ... Note that indexing of the array elements starts at 0 (not 1), so the 11th element has index 10. So for all arrays, the last element has index (size-1). Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 12 Accessing All Array Elements Typically, we want to access each array element and do something with it. As the indexes are sequential, we can use a for-loop for this. The indexes run from 0 to size-1, so such a loop test uses < (rather than <=): for (int index = 0; i < score.Length; i++) { // do something with score[i] } Note: arrays have a property called Length, that is the size of the array. Properties are access using the dot ('.') notation. Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 13 In-class Exercise Modify the Main method of the TestStats program as follows: Replace the score variables with an array of 11 elements. Replace the calls to GetTestScore with a for-loop that calls GetTestScore for each array element. Modify the computation of total to use the array elements. (We will fix this later.) Replace the calls to DisplayResultRow with a forloop that calls DisplayResultRow for each array element. Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 14 Array Parameters Just like other data items, arrays can be passed to a method as a parameter. Unlike other data items, arrays are always passed by reference, and there is no special syntax for doing so. The syntax for an array parameter is: ... <methodname> (<type> [ ] <arrayname>, ...) For example, a method ComputeAverage that receives an array and returns the average of the values in the array would have header: static double ComputeAverage (double [ ] array) Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 15 Array Arguments To call a method that has an array parameter, the corresponding argument simply is the array name. (That is, there are no square brackets or size.) In the example, to call ComputeAverage, we would write: average = ComputeAverage (score); Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 16 In-class Exercise Modify the TestStats program as follows: Add a method ComputeAverage that receives an array of real numbers and returns the average of the numbers in the array. The average should be computed by using a for-loop to sum the elements of the array together, then dividing by the number of elements in the array. At the beginnin of the Main method, write code to get the number of test scores from the user; change the array creation to use this number for its size. Replace the average-computing code in the Main method with a call to ComputeAverage. Monday, February 14 CS 205 Programming for the Sciences - Lecture 15 17