INF230 Basics in C# Programming AUBG, COS dept Lecture 32 Title: Arrays (part 2) Reference: Doyle, chap 8
Lecture Contents: Two-dimensional arrays including rectangular types Two-dimensional arrays including jagged types Multidimensional arrays The ArrayList class to create dynamic lists
From Problem Analysis to Program Design Chapter 8 Advanced Collections C# Programming: From Problem Analysis to Program Design 4th Edition
Lecture Contents: Iteration based on data structures – the FOR…EACH type loops Using LINQ with Arrays
Using Loops to access Arrays Given an array: int[] numbers = new int[] {5, 12, 5, 7, 12, 24, 244}; Write a while … loop to output all array elements
Using Loops to access Arrays Given an array: int[] numbers = new int[] {5, 12, 5, 7, 12, 24, 244}; Write a do … while loop to output all array elements
Using Loops to access Arrays Given an array: int[] numbers = new int[] {5, 12, 5, 7, 12, 24, 244}; Write a for loop to output all array elements
Using Loops to access Arrays int cnt = 0; while (cnt < numbers.Length) { Console.Write(" " + numbers[cnt]); cnt += 1; } Console.WriteLine("\n"); //=========================================== cnt = 0; do Console.Write(" " + numbers[cnt]); cnt += 1; } while (cnt < numbers.Length); for (cnt=0; cnt < numbers.Length; cnt++)Console.Write(" " + numbers[cnt]);
Using Loops to access Arrays Given an array: int[] numbers = new int[] {5, 12, 5, 7, 12, 24, 244}; Write a for each loop to output all array elements
Using Loops to access Arrays Given an array: int[] numbers = new int[] {5, 12, 5, 7, 12, 24, 244}; foreach (int Val in numbers) Console.Write(" " + Val); // cnt is called a counter variable. // Val is called a looping variable or iteration variable.
For Each Loops can be replaced with for (int i=1; i<ages.Length; i++) { if(ages[i] > max) max = ages[i]; } can be replaced with foreach (int age in ages) if(age > max) max = age;
For Each Loops (continued) In the for… loop, the counter variable i can have any name. In the foreach loop, the looping variable age can have any name. The primary difference between the two types of loops is that in a foreach loop no changes can be made in the values of elements of the array.
7.2 Using LINQ with Arrays LINQ Queries
What is LINQ? LINQ stands for Language INtegrated Query A query is a request for information LINQ provides a standardized way to retrieve information from data sources as arrays, text files, XML documents and data bases
LINQ Query A LINQ query for an array is declarative code that describes what you want to retrieve from an array. A LINQ query is a variable – instance/object of a class (also data container) that has contents – sequence of data items extracted and filtered from a source
LINQ Query Code of the form range variable var queryName = from var in arrayName source data where [condition on var] select var; declares the variable queryName as a query and assigns to it a sequence of the values from arrayName that satisfy the stated condition. query operators
LINQ Query (continued) Phrases “from var in arrayName” “where [condition on var]” “select var” are called query clauses. Keywords from, where, select are called query operators. var is called a range variable. arrayName is called a source data.
LINQ Query (continued) var queryName = from var in arrayName where [condition on var] select var; The entire expression to the right of the equal sign = is called a query expression.
LINQ Query (continued) Most query expressions begin with from clause and end with select clause. Each from clause identifies the data source and a range variable. A where clause is added to filter or exclude data from the result.
LINQ Query (continued) The data flow explained (subject Input LINQ Output of further query processing) Data filtered Source sequence of values
LINQ Query (continued) Example // test LINQ int[] nums = new int[] {5, 12, 5, 7, 12}; var numQuery = from num in nums select num; num – range variable nums – data source /array/ from, select – query operators from num in nums – query clause select num – query clause whole text to the right of equal sign – query expression
LINQ Query (continued) Example // test LINQ int[] nums = new int[] {5, 12, 5, 7, 12}; var numQuery = from num in nums select num; How to view the output generated by numQuery? See next slide
LINQ Query (continued) Example // test LINQ int[] nums = new int[] {5, 12, 5, 7, 12}; var numQuery = from num in nums select num; How to view the output generated by numQuery? foreach (int val in numQuery) Console.WriteLine(val);
LINQ Query (continued) Output saved in non text format as contents of numQuery. The values in the sequence can be converted to an array /method toArray()/, displayed in a list box, or written to a text file. var numQuery = … int[] numArray = new int[10]; numArray = numQuery.ToArray(); foreach (int val in numArray) Console.WriteLine(val);
LINQ Query (continued) Output saved in non text format as contents of numQuery. Instead of fixing the array size in advance [10] as on the previous slide, we can count the actual number of array elements using extra loop. var numQuery = from num in nums select num; int broi = 0; foreach (int var in numQuery) {broi++;} int[] arr = new int[broi]; arr = numQuery.ToArray();
LINQ Query (continued) Other useful methods: numQuery.Count() numQuery.Average() numQuery.Sum()
LINQ Query (continued) The example was so simple: primitive 1 to 1 copy source to output The real power of LINQ happens when filtering the input gets involved. The where contextual keyword operator
LINQ Query (continued) int[] nums = new int[] {5, 12, 5, 7, 12}; var numQuery = from num in nums select num; // to be updated as shown below where num < 10
LINQ Query (continued) int[] nums = new int[] {5, 12, 5, 7, 12}; var numQuery = from num in nums select num; // to be updated as shown below where num > 10 && num < 15
LINQ Query (continued) // test LINQ The where operators are said to filter data. The select operators are said to project data.
LINQ Query (continued) The variable in the Select clause can be replaced by an expression involving the variable var numQuery = from num in nums where num < 10 select num + 5 * num; Remark: Missing Select clause produces the same effect as the clause Select num.
Function Procedures in Queries Methods are commonly used in Where and Select clauses var presQuery = from pres in presidents where FirstName(pres) = txtFirstName.Text select IncludeTitle(pres); foreach (pres in presQuery) lstPres.Items.Add(pres);
Function Procedures in Queries Methods are commonly used in Where and Select clauses var presQuery = from pres in presidents where FirstName(pres) = txtFirstName.Text select IncludeTitle(pres); OR: lstPres.DataSource = presQuery.ToList; //???
Continuation of Program String IncludeTitle(String pres) { return "President " + pres; }
Order By Operator Sorts string values into alphabetical order (either ascending or descending) Sorts numbers into numeric order (either ascending or descending) int[] nums = new int[] { 5, 12, 5, 7, 12 }; var numQuery = from num in nums orderby num ascending select num;
Exercises Write a program that uses a LINQ query to calculate the sum of the numbers in the array declared below: int[] pp = new int[10] { 2, 5, -5, 8, -8, 30, 50, 300. 4, -80};
Exercises Write a program that uses a LINQ query to calculate the average of the numbers in the array declared below: int[] pp = new int[10] { 2, 5, -5, 8, -8, 30, 50, 300. 4, -80};
Thank You For Your Attention!
Two-Dimensional Arrays Two-dimensional and other multidimensional arrays follow same guidelines as one-dimensional Referenced much like you reference a matrix Two kinds of two-dimensional arrays Rectangular Visualized as a table divided into rows and columns Jagged or ragged Visualized as a table whose rows are with variable number of elements C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) int [ , ] calories = { {900, 750, 1020}, {300, 1000, 2700}, {500, 700, 2100}, {400, 900, 1780}, {600, 1200, 1100}, {575, 1150, 1900}, {600, 1020, 1700} }; Notice how each row is grouped using curly braces. A comma is used to separate rows Values are stored side by side in contiguous memory locations using a row major format C# Programming: From Problem Analysis to Program Design
Two-Dimensional Representation Figure 8-1 Two-dimensional structure C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) Declaration format type [ , ] identifier = new type [integral value, integral value]; Two integral values are required for a two-dimensional array Number of rows listed first Data values placed in array must be of the same base type Example (create a 7x3 matrix) int [ , ] calories = new int[7, 3]; C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) calories references address of calories[0,0] Figure 8-2 Two-dimensional calories array C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) Length property gets total number of elements in all dimensions Console.WriteLine(calories.Length); // Returns 21 GetLength( ) – returns the number of rows or columns GetLength(0) returns number of rows GetLength(1) returns number of columns Console.WriteLine(calories.GetLength(1)); //Display 3 (columns) Console.WriteLine(calories.GetLength(0)); //Display 7 (rows) Console.WriteLine(calories.Rank); // returns 2 (dimensions) C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) int [ , ] calories = new int[7, 3]; Console.WriteLine(calories.GetUpperBound(0)); // Returns 6 (row index) foreach (int cal in calories) // Displays all values Console.Write(cal + " "); for (int r = 0; r < calories.GetLength(0); r++) for (int c = 0; c < calories.GetLength(1); c++) calories[r, c] = 0; // Initializes all cells C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) Example illustrate: Passing 2-D array as a parameter to a method Method returning 1-D array C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued Average by day - size 7) public static double[ ] CalculateAverageByDay (int[ , ] calories) { int sum = 0; double[ ] dailyAverage = new double[7]; for (int r = 0; r < calories.GetLength(0); r++) for (int c = 0; c < calories.GetLength(1); c++) sum += calories[r, c]; dailyAverage[r] = (double)sum / calories.GetLength(1); sum = 0; } return dailyAverage; Method returns array of averages…row averages C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued Average by meal - size 3) public static double[ ] CalculateAverageByMeal(int[ , ] calories) { int sum = 0; double[ ] mealAverage = new double[3]; for (int c = 0; c < calories.GetLength(1); c++) for (int r = 0; r < calories.GetLength(0); r++) sum += calories[r, c]; mealAverage[c] = (double)sum / calories.GetLength(0); sum = 0; } return mealAverage; Method returns array of averages…col averages C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued average Calories per Meal – void or int as return value) public static void DisplayAverageCaloriesPerMeal (int[ , ] calories) { double sum = 0; for (int da = 0; da < calories.GetLength(0); da++) for (int ml = 0; ml < calories.GetLength(1); ml++) sum += calories[da, ml]; Console.WriteLine("\nCaloric Average Per Meal: {0:N0}", sum / calories.Length); } da and ml used as row/col identifiers →more representative of the data C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued average Calories per Meal – void or int as return value) public static int DisplayAverageCaloriesPerMeal (int[ , ] calories) { double sum = 0; for (int da = 0; da < calories.GetLength(0); da++) for (int ml = 0; ml < calories.GetLength(1); ml++) sum += calories[da, ml]; return sum / calories.Length; } da and ml used as row/col identifiers →more representative of the data C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) Figure 8-3 Output from WeeklyCalorieCounter C# Programming: From Problem Analysis to Program Design
Two-Dimensional Arrays (continued) To align numbers for output, format specifier used Console.WriteLine("{0,-10}: {1,6}", mealTime[c ], mealAverage[c ].ToString("N0")); Comma separates placeholder index from width specifier First argument ({0,-10}) indicates that the first argument should be displayed in a width of 10 Negative value in front of the 10 indicates the value should be left justified Second argument ({1,6}) indicates the numbers are right justified in a width of 6 character positions C# Programming: From Problem Analysis to Program Design
Jagged Arrays Rectangular arrays always have a rectangular shape, like a table; jagged arrays do not Also called ‘arrays of arrays’ Example int[ ] [ ] anArray = new int[4] [ ]; anArray [0] = new int[ ] {100, 200}; anArray [1] = new int[ ] {11, 22, 37}; anArray [2] = new int[ ] {16, 72, 83, 99, 106}; anArray [3] = new int[ ] {1, 2, 3, 4}; C# Programming: From Problem Analysis to Program Design
Multidimensional Arrays Limited only by your imagination as far as the number of dimensions Format for creating three-dimensional array type [ , , ] identifier = new type [integral value, integral value, integral value]; Example (rectangular) int [ , , ] calories = new int [4 ,7 ,3]; (4 week; 7 days; 3 meals) Allocates storage for 84 elements C# Programming: From Problem Analysis to Program Design
Multidimensional Arrays (continued) Figure 8-4 Three-dimensional array Upper bounds on the indexes are 3, 6, 2 C# Programming: From Problem Analysis to Program Design
Multidimensional Arrays (continued) int [ , , ] calories = new int [4, 7, 4]; // Loop to place the row total in the last column, indexed by 3 for (int wk = 0; wk < calories.GetLength(0); wk++) { for (int da = 0; da < calories.GetLength(1); da++) for (int ml = 0; ml < calories.GetLength(2) - 1; ml++) calories[wk, da, 3] += calories[wk, da, ml]; } C# Programming: From Problem Analysis to Program Design
Multidimensional Arrays (continued) Index from the calories array for the day number used as index for the string day name array C# Programming: From Problem Analysis to Program Design
ArrayList Class Limitations of traditional array Cannot change the size or length of an array after it is created ArrayList class facilitates creating listlike structure, AND it can dynamically increase or decrease in length Similar to vector class found in other languages Includes large number of predefined methods using System.Collections; C# Programming: From Problem Analysis to Program Design
ArrayList Class (continued) Table 8-1 ArrayList members C# Programming: From Problem Analysis to Program Design
ArrayList Class (continued) Table 8-1 ArrayList members (continued) C# Programming: From Problem Analysis to Program Design
ArrayList Class (continued) Table 8-1 ArrayList members (continued) C# Programming: From Problem Analysis to Program Design
ArrayList Class (continued) Any predefined or user-defined type can be used as an ArrayList object C# also includes a List<> class List<> class requires that objects be the same type when you place them in the structure ArrayList allows you to mix types C# Programming: From Problem Analysis to Program Design
ArrayList Class (continued) ArrayList anArray = new ArrayList( ); // Instantiates ArrayList anArray.Add("Today is the first day of the rest of your life!"); anArray.Add("Live it to the fullest!"); anArray.Add("ok"); anArray.Add("You may not get a second chance."); anArray.RemoveAt(2); // Removes the third physical one for (int i = 0; i < ar.Count; i++) //Displays elements Console.WriteLine(ar[i] ); C# Programming: From Problem Analysis to Program Design
ArrayList Class (continued) Figure 8-6 Sample run from the ArrayList example C# Programming: From Problem Analysis to Program Design
ArrayList Class (continued) using System; using System.Collections; class SBArrayList { static void Main(string[] args) ArrayList ar = new ArrayList(); ar.Add("Sofia"); ar.Add("Varna"); ar.Add("Bourgas"); for (int i = ar.Count-1; i>=0; i--) Console.Write(ar[i] + " "); ar.Remove("Varna"); Console.WriteLine(); } C# Programming: From Problem Analysis to Program Design
TempAgency Application Example Figure 8-8 Problem specification for Manatee example C# Programming: From Problem Analysis to Program Design
TempAgency Application Example (continued) Table 8-3 Instance field members for the TempAgency class C# Programming: From Problem Analysis to Program Design
TempAgency Application Example (continued) Figure 8-9 Prototype C# Programming: From Problem Analysis to Program Design
TempAgency Application Example (continued) Figure 8-10 Class diagrams C# Programming: From Problem Analysis to Program Design
TempAgency Application Example (continued) Figure 8-11 TempAgency class methods behavior C# Programming: From Problem Analysis to Program Design
TempAgency Application Example (continued) Figure 8-12 TempAgency application output Review TempAgency Example C# Programming: From Problem Analysis to Program Design
Practical Demo Source Code Fragments
Practical Tasks // two-dimensional arrays - rect or square table - matrix Console.WriteLine("\n\n2D arrays - matrix"); int[,] matrix1 = new int[3, 5]; for (i = 0; i < 3; i++) for (j = 0; j < 5; j++) matrix1[i, j] = i * 5 + j * 10; { Console.Write(" " + matrix1[i, j]); Console.WriteLine(); }
Practical Tasks // two-dimensional arrays - rect or square table - matrix Console.WriteLine(); for (i = 0; i < matrix1.GetLength(0); i++) { for (j = 0; j < matrix1.GetLength(1); j++) Console.Write(" " + matrix1[i, j]); } // iteration based on data structures - foreach Console.WriteLine("\n2D array and iteration based on data structures"); foreach (int idd in matrix1) Console.Write(" " + idd);
Practical Tasks // two-dimensional arrays - rect or square table - matrix // two-dimensional arrays - list of initializers Console.WriteLine("\n2D array and list of initializers"); int[,] matrix2 = { { 51, 52, 53, 54, 55 }, { 61, 62, 63, 64, 65 }, { 71, 72, 73, 74, 75 } }; for (i = 0; i < matrix2.GetLength(0); i++) { for (j = 0; j < matrix2.GetLength(1); j++) Console.Write(" " + matrix2[i, j]); Console.WriteLine(); }
Practical Tasks The difference in declaring 2D rectangular array /matrix/ and 2D jagged /ragged/ array // two-dimensional arrays - rect or square table - matrix // two-dimensional arrays - list of initializers int[,] matrix2 = { { 51, 52, 53, 54, 55 }, { 61, 62, 63, 64, 65 }, { 71, 72, 73, 74, 75 } }; // two-dimensional arrays - special case - jagged array no 1 int[][] matrix3 = new int[3][]; matrix3[0] = new int[] { 0, 2, 4, 6, 8, 10 }; matrix3[1] = new int[] { 1, 3, 5, 7 }; matrix3[2] = new int[] { 11, 22 };
Practical Tasks // two-dimensional arrays - special case - jagged array no 1 Console.WriteLine("\n2D array - special case - jagged array"); int[][] matrix3 = new int[3][]; matrix3[0] = new int[] { 0, 2, 4, 6, 8, 10 }; matrix3[1] = new int[] { 1, 3, 5, 7 }; matrix3[2] = new int[] { 11, 22 }; // display jagged arraay for (i = 0; i < matrix3.Length; i++) { Console.WriteLine(); for (j = 0; j < matrix3[i].Length; j++) Console.Write(" " + matrix3[i][j]); }
Practical Tasks // two-dimensional arrays - special case - jagged array no 2 int[][] matrix4; matrix4 = new int[3][]; matrix4[0] = new int[10]; matrix4[1] = new int[6]; matrix4[2] = new int[8]; for (i = 0; i < matrix4.Length; i++) { Console.WriteLine(); for (j = 0; j < matrix4[i].Length; j++) Console.Write(" " + matrix4[i][j]); }
Practical Tasks // associative array - special case - hashtable Console.WriteLine("\nAssociative array - hashtable - key and value"); Hashtable ht = new Hashtable(); ht.Add("Sofia", "BG"); ht.Add("Bern", "CH"); System.Windows.Forms.MessageBox.Show((string)ht["Sofia"]); Console.WriteLine(ht["Sofia"]); Console.WriteLine(); Hashtable htt = new Hashtable(); htt.Add(10, "BG"); htt.Add(210, "DE"); System.Windows.Forms.MessageBox.Show((string)htt[210]); Console.WriteLine(htt[210]);
Thank You For Your Attention!