Presentation is loading. Please wait.

Presentation is loading. Please wait.

Array ISYS 350.

Similar presentations


Presentation on theme: "Array ISYS 350."— Presentation transcript:

1 Array ISYS 350

2 C# Array An array allows you to store a group of items of the same type together. Processing a large number of items in an array is easier than processing a large number of items stored in separate variables.

3 Declaring a Array Declare an array in one statement:
Type[] arrayName = new type[array size]; Ex: string[]empName = new string[3]; double[] intRate = new double[6];

4 Array Elements Array elements are assigned an 0-based index.
Each element can be accessed by its index: arrayName[index] Ex: empName[0] intRate[2]

5 Array Initialization With the declaration statement:
string[] empName = new string[3] { "Peter", "Paul", "Mary" }; double[] intRate = new double[6] { .03, .04, .05, .06, .07, .08 }; Initialize each element separately: empName[0] = "Peter"; empName[1] = "Paul"; empName[2] = "Mary";

6 Accessing Array Elements with a for loop
int arrayIndex; for (arrayIndex = 0; arrayIndex <= 2; ++arrayIndex) { MessageBox.Show(empName[arrayIndex].ToString()); } Using array’s Length property: number of elements in array for (arrayIndex = 0; arrayIndex <= empName.Length-1; ++arrayIndex) { MessageBox.Show(empName[arrayIndex].ToString()); } Note: Length - 1

7 Example: Compute the sum and average of numbers in an array
double[] myGPAs = new double[5] { 2.5, 3.2, 3.4, 2.9, 3.6 }; double sumGPA=0, avgGPA; for (int i = 0; i <= myGPAs.Length - 1; ++i) { sumGPA += myGPAs[i]; } avgGPA = sumGPA / myGPAs.Length; MessageBox.Show("Average GPA is: " + avgGPA);

8 foreach Loop The foreach statement repeats a group of embedded statements for each element in an array.

9 foreach loop example double[] myGPAs = new double[5] { 2.5, 3.2, 3.4, 2.9, 3.6 }; double sumGPA = 0, avgGPA; foreach (double d in myGPAs) { sumGPA += d; } avgGPA = sumGPA / myGPAs.Length; MessageBox.Show("Average GPA is: " + avgGPA);

10 Using Array’s Methods and Length property
Sum(), Average(), Max(), Min(); double[] myGPAs = new double[5] { 2.5, 3.2, 3.4, 2.9, 3.6 }; double avgGPA, maxGPA, minGPA; avgGPA = myGPAs.Average(); maxGPA = myGPAs.Max(); minGPA=myGPAs.Min(); MessageBox.Show(“The size of array is: " + myGPAs.Length);

11 Create a Loan Payment Form

12 If rates are stored in an array
Method 1: Using a loop to create the Listbox with rates in the Form Load event string[] strRate = new string[6] { "3%", "4%", "5%", "6%", "7%", "8%" }; for(int i=0;i<=strRate.Length-1;i++) { listBox1.Items.Add(strRate[i]); }

13 Parallel Array Example
A parallel array to store the numerical rates: double[] intRate = new double[6] { .03, .04, .05, .06, .07, .08 }; Use listbox selectedIndex to access the rate: intRate[listBox1.SelectedIndex]

14 Code Example double[] intRate = new double[6] { .03, .04, .05, .06, .07, .08 }; double loan, rate, term, payment; loan = double.Parse(textBox1.Text); rate = intRate[listBox1.SelectedIndex]; if (radioButton1.Checked) term = 15; else term = 30; payment = Financial.Pmt(rate / 12, term * 12, -loan); textBox2.Text = payment.ToString("c");

15 Sort an Array Array Class: Sort Method Example:
Sort array elements in increasing order Example: Array.Sort(myGPAs);

16 Exercise: Weighted Avg of three exams= 60%. highest score +30%
Exercise: Weighted Avg of three exams= 60%*highest score +30%*2nd highest score +10%*lowest score Method 1: You may sort the array of exam scores. Or Method 2: You may use the Max, Min and Sum functions.

17 Count the number of words in a textbox
string.Split() returns an array:

18 Count words example String myText = textBox1.Text;
string[] wordList = (myText.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries)); textBox2.Text = wordList.Length.ToString(); foreach (string s in wordList) { MessageBox.Show(s.ToString()); }

19 Using an array of seperators
string[]seperators = new string[3] { "," ," ", ";" }; String myText = textBox1.Text; string[] wordList = (myText.Split(seperators, StringSplitOptions.RemoveEmptyEntries)); foreach (string s in wordList) { MessageBox.Show(s.ToString()); }

20 JavaScript Array

21 Array Use [] to define array and it is not require to declare array size
var names=[]; names[0]=“peter”; names[1]=“paul”; names[2]=“mary”; Or simply: Names=[“peter”,”paul”,”mary”]; myGPAs = [ 2.5, 3.2, 3.4, 2.9, 3.6 ];

22 Array length, lowercase l
<script> myGPAs = [ 2.5, 3.2, 3.4, 2.9, 3.6 ]; sumGPA=0; for (i = 0; i <= myGPAs.length - 1; ++i) { sumGPA += myGPAs[i]; } avgGPA = sumGPA / myGPAs.length; alert("Average GPA is: " + avgGPA); </script>

23 JavaScript forEach https://www.w3schools.com/jsref/jsref_foreach.asp
function myFunction(item, index) { sumGPA+=item; } </script> <body> myGPAs = [ 2.5, 3.2, 3.4, 2.9, 3.6 ]; sumGPA=0; myGPAs.forEach(myFunction); avgGPA = sumGPA / myGPAs.length; alert("Average GPA is: " + avgGPA); </body>

24 Array and document.write demo
<form name="fvForm"> Enter PV: <input type="text" id ="PV" name="PV" value="" size="10" /><br> <script> rateValues=[.04,.05,.06,.07,.08]; rateDisplay=["4%","5%","6%","7%","8%"]; document.write("<select name='Rate' id='Rate'>"); for (i=0;i<=rateValues.length-1;i++) { document.write("<option value='"+ rateValues[i] + "'>" + rateDisplay[i]+"</option>"); } document.write("</select><br>"); </script> Select Year: <br> <input type="radio" name="Year" value=10 id="Year10" />10 year<br> <input type="radio" name="Year" value=15 id="Year15" />15 year<br> <input type="radio" name="Year" value=30 id="Year30" />30 year<br> <br> Future Value: <input type="text" name="FV" id="FV" /> <input type="button" value="ComputeFV" name="btnCompute" onClick="ComputeFV()" /> </form>

25 sort() method By default, the sort() function sorts values as strings in ascending order. However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". We need to add a “compare function”.

26 HTML element’s innerHTML property
Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages. Assigning a value: document.getElementById(“p”).innerHTML = 5;

27 Example of sorting numerical array using a compare function
<head> <script> function myFunction() { myGPAs.sort(function(a, b){return a - b}); document.getElementById("demo").innerHTML =myGPAs; document.getElementById("max").innerHTML = myGPAs[myGPAs.length-1]; document.getElementById("min").innerHTML = myGPAs[0]; } </script> </head> <body> <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in ascending order.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> Highest GPA is:<p id="max"></p><br> Lowest GPA is: <p id="min"></p><br> myGPAs = [ 2.5, 3.2, 3.4, 2.9, 3.6 ]; document.getElementById("demo").innerHTML = myGPAs; </body>

28 JavaScript String split() method Split a string into an array of substrings: str.split(“,”); str.split(“ “); <script> function myFunction() { var str = "a,b,c,d,e,f"; var arr = str.split(","); document.getElementById("demo").innerHTML = arr; } </script>

29 JavaScript object https://www.w3schools.com/js/js_objects.asp
An object may have properties. Example: person1 = {firstName:"John", lastName:"Doe", age:46}; person2 = {firstName:"Paul", lastName:"Smith", age:40}; Using the “.” notation to access property value: person1FirstName=person1.firstName; person1lastName=person1.lastName;

30 Array of objects Note: use the array push method to add a new member
<body> <h2>JavaScript Objects</h2> <p>JavaScript uses names to access object properties.</p> <p id="demo"></p> <p id="demo2"></p> <script> var person1 = {firstName:"John", lastName:"Doe", age:46}; var person2 = {firstName:"Paul", lastName:"Smith", age:40}; emp=[person1,person2]; document.getElementById("demo").innerHTML = emp[0]["firstName"]; person3={firstName:"David", lastName:“Chen", age:46}; emp.push(person3); document.getElementById("demo2").innerHTML = emp[2]["firstName"]; </script> </body>

31

32 <body> <input type="button" value="Add New Employee" name="btnAddNew" onclick="addNew()"/> <br><br> Employee Table<br><br> <table id="empTable" border="1" width="400" cellspacing="1"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> </thead> <tbody> </tbody> </table> <script> var person1 = {firstName:"John", lastName:"Doe", age:46}; var person2 = {firstName:"Paul", lastName:"Smith", age:40}; person3={firstName:"David", lastName:"Chen", age:46}; employees=[person1,person2,person3]; var table = document.getElementById('empTable'); for (i = 0; i <= employees.length-1; i++) { var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell0 = row.insertCell(0); cell0.innerHTML=employees[i]["firstName"]; var cell1 = row.insertCell(1); cell1.innerHTML=employees[i]["lastName"];; var cell2 = row.insertCell(2); cell2.innerHTML=employees[i]["age"]; } </script> </body>

33 <script> function addNew() { fName=prompt("Enter first name:"); lName=prompt("Enter last name:"); empAge=prompt("Enter age:"); person = {firstName:fName, lastName:lName, age:empAge}; employees.push(person); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell0 = row.insertCell(0); cell0.innerHTML=employees[employees.length-1]["firstName"]; var cell1 = row.insertCell(1); cell1.innerHTML=employees[employees.length-1]["lastName"];; var cell2 = row.insertCell(2); cell2.innerHTML=employees[employees.length-1]["age"]; } </script>


Download ppt "Array ISYS 350."

Similar presentations


Ads by Google