|
|
|
Now that you've learned about loops, you know how to avoid typing the same basic block of code 3000 times. But with that ability comes a tricky question: how can we do the same thing with variables? Yes, what if you need 3000 integers, and for no good reason other than sheer laziness, you don't feel like writing a declaration for every last one of them? Well, that's why we've got arrays. An array is a "collection" of variables that are (typically) all the same type. Each variable in the collection is known as an "element", and you can basically have as many elements as you want (within reason). Instead of having to do this... int number1; int number2; int number3; // 2996 lines & a carpal tunnel later int number2999; int number3000; ...we can simply do this... int[] numbers = new int[3000]; That "new" keyword is an incredibly important concept later on, but for now, the blazes with it. What we care about right now is the little [] that appears after "int". The part before the equals, "int[] numbers", tells C# that we're declaring a variable of type int[], called "numbers". The [] is what designates the variable as an array; in this case, an array of ints. The part after the equals, "new int[3000]", is where we tell C# how many elements there are in the array. In this case, there are 3000. So, now that we know that... how do you actually use them? numbers[0] = 5; numbers[1] = 8; numbers[2] = 4; What we've done here is store a value in first three elements of the array. Element #0 now has a value of 5, Element #1 now has a value of 8, and Element #2 now has a value of 4. Yeah, I know. The counting starts at zero, not one. So the first element has an index of 0, the second element has an index of 1, and so on. You'd better just get used to this "zero-based" approach to counting, or all your indexes are going to be off by one element (which happens to programmers annoyingly often). Once you've stored information in an array, how do you get it back out? In exactly the same manner you stored it: int myNumber = numbers[2]; "myNumber" now holds a value of 4, because that's what's been stored in Element #2 of numbers. And of course, accessing the other elements in the array is just as easy, right down to the last element... numbers[2999]. Remember... the first element is zero, so the three thousandth element will be 2999! Also remember that if you try to access in invalid element, such as "numbers[-15]" or "numbers[90322]", the program will blow up. So many fatal errors, eh? Don't worry, you'll learn how to handle them really soon. What if you don't know how many elements you'll need in the array? Well, the little number in the array's declaration doesn't have to be "hardwired" into the program. It's just an int, after all, so any int will do. For example, you could ask the user for the number of elements they wanted, and then use that number when declaring the array... Console.Write("Enter number of elements: "); int numElements = Convert.ToInt32(Console.ReadLine()); int[] myNumberArray = new int[numElements]; ...and there you go. You now have an array with... however many elements the user specified. You don't have to do things that way, of course; I'm simply pointing out that the size of the array can be assigned "on the fly". It doesn't have to be predetermined. Also, you don't even need to specifiy the number of elements, if you don't mind supplying all the values right away... int[] myFirstArray = new int[] {4, 3, 76, 73, 33, 58}; The array will automatically size itself to accommodate the exact number of values you supplied. In this case, 6. As "interesting" as all of this is, however, the true power of arrays only becomes apparent when you combine them with loops... Console.WriteLine("Contents of myFirstArray:"); for(int i = 0; i < myFirstArray.Length; ++i) { Console.WriteLine("Index {0}: {1}", i+1, myFirstArray[i]); } Oh, did I forget to mention? Every array you create has its own Length value, which is perfect for use in "for" loops! With minimal effort, we now have a block of code that will print out every single number in the array. And all we had to do was use the "for" loop's "i" variable as the element number! The resulting output is this: Contents of myFirstArray: Index 1: 4 Index 2: 3 Index 3: 76 Index 4: 73 Index 5: 33 Index 6: 58 After seeing the output, you'll probably understand why I output "i+1" as the {0} parameter, and not plain "i". Even though we programmers know that all arrays start at zero, there's no reason to trouble our end-users with such information. So I have the console tell the user that's it's printing one index higher than it actually is, just so that the user gets an old-fashioned numbered list that starts at one. Considerate, wouldn't you say? And of course, once it really hits you that you can "iterate" through an vast array of numbers in just a few lines of code, dozens of new possibilities spring up. For example, you could add all the numbers in an array together... int sum = 0; for(int i = 0; i < myFirstArray.Length; ++i) { sum += myFirstArray[i]; } Console.WriteLine("Grand Total: " + sum); ...anyways, you get the idea. A few lines of code can process thousands of numbers, because of loops and arrays. By the way, if you want to manually access several (or all) array elements in a row, here's a simple trick. Rather than typing out the index you want on each line, like this... names[0] = "Bob"; names[1] = "Fred"; names[2] = "Joe"; names[3] = "Larry"; // etc ...declare an int, and increment it each time, like this... int i = -1; names[++i] = "Bob"; names[++i] = "Fred"; names[++i] = "Joe"; names[++i] = "Larry"; // etc Because "i" is incremented every time that it's used to access an element, you'll get the next element in the array every time. This trick saves you the trouble of typing the number each time. It's also safer, because it's one less thing for you to forget when you're copying and pasting code! It also means that if you change the order of the lines, it will immediately change the order of the array as well, without having to manually change the index. Now that you know about arrays, I can also mention a cool string manipulation feature that wouldn't have meant much to you earlier. Watch this: string sentence = "Penguins are awesome."; string[] words = sentence.Split(); for(int i = 0; i < words.Length; ++i) { Console.WriteLine("Word {0}: {1}", i+1, words[i]); } What's that Split() command do? It takes your string, and gives you a string[], where each member is a "word" in your string (yes, you can have arrays of strings. You can have arrays of pretty much any datatype you want). This is what you'd see on the screen: Word 1: Penguins Word 2: are Word 3: awesome. How does C# "know" where each word starts and ends? It breaks up your original string by "whitespace" characters, such as spaces and tabs. You can also supply alternative characters for it to break on, like this: string[] words = sentence.Split(new char[]{',', '-'}); In the above code, a new "word" starts everytime there's a ',' or an '-', which might be useful if you have a bunch of data that's separated by commas and dashes (hey, it could happen). Also note that we passed in a temporary char[] that we just created on the fly, in order to specify which characters we wanted. Okay, one last thing. You might be wondering what value an element contains before you actually assign something to it. In the case of a number datatype, it's pretty much always going to be zero. For a lot of other datatypes (strings, for example), the value will be "null". This is a special C# value that kind of means "this variable doesn't really exist at the moment". If you try to perform operations on a variable that has a value of null, your program will crash. What's that? Another circumstance beyond your control that might kill your program? Okay, enough of this! It's time to learn how to handle errors. But first, a code sample... using System; namespace D_Arrays { class Class1 { [STAThread] static void Main(string[] args) { // Initialize and assign values now int[] myFirstArray = new int[] {4, 3, 76, 73, 33, 58}; Console.WriteLine("Contents of myFirstArray:"); for(int i = 0; i < myFirstArray.Length; ++i) { Console.WriteLine("Index {0}: {1}", i+1, myFirstArray[i]); } Console.Write(Environment.NewLine); // Initialize now, assign values later int[] numbers = new int[3]; for(int i = 0; i < numbers.Length; ++i) { Console.Write("Enter number {0}: ", i+1); numbers[i] = Convert.ToInt32(Console.ReadLine()); } // Add up the numbers in an array int sum = 0; for(int i = 0; i < numbers.Length; ++i) { sum += numbers[i]; } Console.WriteLine("Grand Total: " + sum); // String.Split() Console.Write(Environment.NewLine + "Enter a sentence: "); string sentence = Console.ReadLine(); string[] words = sentence.Split(); for(int i = 0; i < words.Length; ++i) { Console.WriteLine("Word {0}: {1}", i+1, words[i]); } // A basic "menu" string[] animals = new string[] { "Penguin", "Donkey", "Shark", "Monkey" }; int menuChoice = 0; while( menuChoice > -1 ) { Console.Write(Environment.NewLine); Console.Write("Enter the index of the animal to view, or enter \"-1\" to quit: "); menuChoice = Convert.ToInt32( Console.ReadLine() ); if( menuChoice < 0 ) { Console.WriteLine( "Goodbye!" ); } else if( menuChoice < animals.Length ) { Console.WriteLine( animals[menuChoice] ); } else if( menuChoice >= animals.Length ) { Console.WriteLine( "Sorry, that index is too high!" ); } } // Prompt for exit Console.Write(Environment.NewLine + "Program complete! Hit enter to exit..."); Console.ReadLine(); } } } |
|