1 / 37

COP 2360 – C# Programming

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. Review Test…. Pseudo Code Exercise. Someone hands you a folder with student test records.

carmeno
Download Presentation

COP 2360 – C# Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COP 2360 – C# Programming Chapter 7 & 8- Arrays and Strings

  2. Annoucements • What’s My Grade web site • A word about testing • Another word about testing

  3. Review Test…..

  4. 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.

  5. 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.

  6. //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

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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)

  12. 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);

  13. 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

  14. 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

  15. 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?

  16. 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.

  17. 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!!)

  18. 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

  19. 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)

  20. 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.

  21. 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

  22. 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#";

  23. Some String Functions

  24. More Useful String Functions

  25. More Useful String Functions

  26. 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.

  27. 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!!

  28. A now for Assignment 3 • Let’s Play Hangman!!

  29. And now for a very bad segue • Let’s go back to our talk about arrays….

  30. 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?

  31. 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

  32. 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.

  33. 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

  34. 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.

  35. 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?

  36. 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} };

  37. 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.

More Related