370 likes | 396 Views
Dive into the fundamentals and applications of arrays in C# programming. Learn how to manipulate data efficiently, calculate averages, and work with test scores.
E N D
COP 2360 – C# Programming Chapter 7 & 8- Arrays and Strings
Annoucements • What’s My Grade web site • A word about testing • Another word about testing
Pseudo Code Exercise • Someone hands you a folder with student test records. • Each test record has the student’s name and five test scores (from 0 to 100) • Write the pseudo code to calculate the average of the five test scores for each student.
Arrays • Life without arrays • Suppose we needed to get the average grade for five test scores and then print out all grades lower than that average. • Since we don’t know which scores to output until AFTER all of the data has been input, we will need to hold data until the five test scores have been read in. • So we create five variables, input the information, and then test each one of them.
//Program to find the average test score and output the average //test score and all the test scores that are less than //the average test score. static void Main(string[] args) { int test0, test1, test2, test3, test4; double average; Console.WriteLine("Enter five test scores. One on each line: "); test0 = int.Parse(Console.ReadLine()); test1 = int.Parse(Console.ReadLine()); test2 = int.Parse(Console.ReadLine()); test3 = int.Parse(Console.ReadLine()); test4 = int.Parse(Console.ReadLine()); average = (test0 + test1 + test2 + test3 + test4) / 5.0; Console.WriteLine("The average test score = {0}", average); if (test0 < average) {Console.WriteLine("{0} is less that the average test score.", test0);} if (test1 < average) {Console.WriteLine("{0} is less that the average test score.", test1);} if (test2 < average) {Console.WriteLine("{0} is less that the average test score.", test2);} if (test3 < average) {Console.WriteLine("{0} is less that the average test score.", test3);} if (test4 < average) {Console.WriteLine("{0} is less that the average test score.", test4);} Console.ReadKey(); return; } Life Without Arrays
What’s an Array And how can this help • An array is a collection of variables of the same data type. • The array is referenced by a single name suffixed with an index pointer. • Let’s redo our grading example
int [] test = new int[5]; double average; Console.WriteLine("Enter five test scores. One on each line: "); test[0] = int.Parse(Console.ReadLine()); test[1] = int.Parse(Console.ReadLine()); test[2] = int.Parse(Console.ReadLine()); test[3] = int.Parse(Console.ReadLine()); test[4] = int.Parse(Console.ReadLine()); int total = 0; for (int i =0;i<5;i++) { total = total + test[i]; } average = total / 5.0; Console.WriteLine("The average test score = {0}", average); for (int i =0;i<5;i++) { if (test[i] < average) Console.WriteLine("{0} is less that the average test score.", test[i]); } Console.ReadKey(); return; Life With an Array
Now what can we do? • Since we have an array basis, we can • Ask the user how many test scores there are • Input the test scores using a For or While loop • Greatly reduce our coding
Console.Write("How Many Scores? "); int nNumbTests = int.Parse(Console.ReadLine()); int[] test = new int[nNumbTests]; double average = 0; int total = 0; Console.WriteLine("Enter {0} test scores. One on each line: ", nNumbTests); for (int i = 0; i < nNumbTests; i++) { test[i] = int.Parse(Console.ReadLine()); total = total + test[i]; average = (double)total / (double)nNumbTests; } Console.WriteLine("The average test score = {0}", average); for (int i = 0; i < nNumbTests; i++) { if (test[i] < average) Console.WriteLine("{0} is less that the average test score.", test[i]); } Console.ReadKey(); return; Revised Grading Program
Array Basics • When declared, memory is set aside based on the variable type and number of elements in the array • int[] nPrices = new int [100] Will allocate an array named nPrices with 100 elements The elements are indexed from 0 to 99: (why not 1 to 100 – Which by the way is one of the things I hate with “C” Type Languages) Each element can hold one integer value • The above example is a “one dimensional” array. • It may be easier to think that the computer is creating 100 separate variables named nPrices[0] through nPrices[99] (or maybe not)
Array Basics • Array variables can be used in any of our expressions just like any other variables. But they MUST include the suffix with the index. • In the example we just went through, we had: • Console.WriteLine("{0} is less that the average test score.", test[i]); • What do you think would happen if I reference just test? • Console.WriteLine(test);
Array Basics • Normal arrays sizes are static. • That is, they cannot be changed once initialized. • You can use constants or variables in the definitions • const int nARRAY_SIZE = 20; • int[] nMyArray = int[nARRAY_SIZE]; • Next Week we’ll touch on ArrayLists which can be dynamic • Arrays can be initialized when they are declared • char[] sLetterGrade = new char[5] {‘A’,’B’,’C’,’D’,’E’}; • int[] nScore = new int[5] {0,0,0,0,0}; // initializes ALL elements to 0 • int[] nDemo = {3,6,9}; //Creates an array with three elements
Array Basics • Supposed we have two arrays • int[] nArrayOne = {1,2,3,4,5}; • int[] nArrayTwo = new int[5]; • We would like to copy nArrayOne to nArrayTwo • But we cannot do it directly!! • We must copy element by element. • Same is true for comparison, printing, etc. • Also, as parameters to methods, arrays are always By Ref
Standard Array Copy Routine for (int i=0;i<5;i++) { nArraytwo[i] = nArrayone[i]; } • how bout doing that in a function? static void copyArray(int[] pnArrayIn, int[] pnArrayOut, int pSize) { for (int i = 0; i < pSize; i++) { pnArrayOut[i] = pnArrayIn[i]; } } • What happens if I do say nArrayTwo = nArrayOne?
Let’s do some fun Array stuff int[] nSomeFun = {5, 4, 7, 2, 3, 5, 1, 8, 9, 0}; nSomeFun[5] = nSomeFun[5] + nSomeFun[9]; nSomeFun[1] = nSomeFun[2] * nSomeFun[6]; nSomeFun[0] = nSomeFun[0] + nSomeFun[9]; nSomeFun[4] = nSomeFun[1] + nSomeFun[2]; for (int i=0;i<10;i++) { nSomeFun[9] = nSomeFun[9] + nSomeFun[i]; } • What are the values of each element of nSomeFun? • It may help to create a grid to hold the initial values like an excel sheet.
Strings – Stringsand even more Strings • In the beginning, c had no string manipulation abilities. • Instead all they had were character arrays. • They had to manipulate text using the same type of array manipulation stuff we just looked at for other simple variables. • c was used a lot for scientific calculations and as a replacement for assembly language (and when compared to assembly language, the programmers were just as happy as they could be!!)
Strings – Stringsand even more Strings • But, as we have seen above, arrays have limitations that make sense for a series of numbers, but not a series of letters. • You can’t compare two arrays without using a for loop • You can’t easily move the contents of one array to another
The ‘c-string’ • But, because c used functions and libraries in a very similar manner as c#, some industrious programmers came up with the ‘c-string’ • Basically they wrote a library (cstring) that included functions to make it easier to manipulate character arrays • At first, there were many, many libraries until they were standardized into the cstring library available today. • They defined a ‘c-string’ as an array of type char where the last character of the string contain the “null” character (0)
The string library • Because c-strings sucked so badly, many more businesses with many more programmers wrote a new, new library called “string” which makes string values look and act like regular variable types. • These also had a bunch of different varieties, and these were again standardized into what we now know as the “string” data type.
The String Class • C# carried the String Library further into the String Class • Stores a collection of Unicode characters • Immutable series of characters (What does that mean) • Making a change isn’t making a change, it’s making a new string!! • Reference type • Normally equality operators, == and !=, compare the object’s references, but operators function differently with string than with other reference objects • Equality operators are defined to compare the contents or values • Includes large number of predefined methods
The String Class • Can process variables of string type as a group of characters • Can also access individual characters in string using an index with [ ] • First character is indexed by zero string sValue = "C# Programming"; object sObj; string s = "C#";
Let’s play with some string functions • Write a program that uses Console.ReadLine() to store a line of text into a string variable. • Then, go into a loop and ask the user to enter a character. • Find the character in the string. If found, tell the user where the character is and replace it with the letter “X”, then display the text back. If not found, say that it wasn’t found. • If the user enters a “#”, stop the program.
Strings and Arrays • Let’s Look at our main routine • Now we can finally understand what the heck that parameter named Args is • It’s whatever is entered into the command line when the program is run. • Let’s try it out and see what happens!!
A now for Assignment 3 • Let’s Play Hangman!!
And now for a very bad segue • Let’s go back to our talk about arrays….
Let’s Search for some stuff • Let’s suppose we have an array of integers • We want to have the user enter an integer and then search through the array for that value • How would we do this? • How would we do this by hand? • What programming language basic process would we need to use to facilitate this?
Let’s Sort an Array • Let’s suppose we have the same array of integers • We want to sort the array from smallest to largest integer value • How would we do this? • How would we do this by hand? • Let’s Do It • Now Let’s Program It
Let’s Sort an Array • Write a program that creates a 10 item array of type int. • The program should then ask the user to enter 10 integers. • Once stored in the array, the program should use the sort algorithm we just worked out to sort the numbers, and then output the sorted array.
Let’s talk about our Find algorithm now that the data is sorted. • What are some of the ways we can improve our find algorithm if the array is sorted? • How does each change potentially change how long it takes to search for something? • ut oh, we may be talking logs here
Parallel Arrays • Sometimes you may have two or more arrays that are linked in someway • State abbreviations to State Names for example. • String[] sStateAbbrevs = new String[50]; • String[] sStateNames = new String[50]; • Now, we can have a user enter the two digit state abbreviation, use our look-up logic from a couple of slides ago, and find the abbreviation. Once we have the abbreviation, we are also pointing to the name.
Two Dimensional Array • double[,] fSalesArray = new double [10] [5]; • initializes a two dimensional array with 10 rows and 5 columns • What could be some examples where we might want to use a two dimensional array? • What other “things” look like the example below?
Jagged Arrays • Really an Array of Arrays where the the first brackets identifies the number of arrays. The second the item within that array • int[][] n7 = new int[2][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} }; • int[][] n8 = new int[][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} }; • int[][] n9 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
Multidimensional Arrays • Just like we did with two dimensional arrays, one can define as many dimensions as you would like when an array is created.