# Exercise Solutions: Control Flow & Collections¶

Line numbers are for reference. They may not match your code exactly.

## Array Practice¶

1. Loop through the array and print out each value.
 ```1 2 3 4``` ``` foreach(int num in numberArray) { Console.WriteLine(num); } ```

Note

Remember: this is not the only way to loop through an array.

Back to the exercises

## String Practice¶

1. For this exercise, create a string for the value.
2. Use the Split method to divide the string at each space and store the individual words in an array.
3. Print the array of words to verify that your code works.
 ```1 2 3``` ``` string sentence = "I would not, could not, in a box. I would not, could not with a fox. I will not eat them in a house. I will not eat them with a mouse."; string[] words = sentence.Split(" "); Console.WriteLine(string.Join("/", words)); ```

Back to the exercises

## List Practice¶

1. Write a static method to find the sum of all the even numbers in a List.
 ``` 1 2 3 4 5 6 7 8 9 10 11 12``` ``` static int sumEven(List arr) { int total = 0; foreach (int integer in arr) { if (integer % 2 == 0) { total += integer; } } return total; } ```
1. Write a static method to print out each word in a list that has exactly 5 letters.
 ``` 1 2 3 4 5 6 7 8 9 10``` ``` static void printFiveLetterWords(List wordlist) { foreach (string word in wordlist) { if (word.Length == 5) { Console.WriteLine(word); } } } ```
1. Modify your code to prompt the user to enter the word length for the search.
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18``` ``` Console.WriteLine("Enter a word length: "); string numInput = Console.ReadLine(); int numChars = int.Parse(numInput); // Call the method to print out list words of the chosen length: printXLetterWords(wordList, numChars); static void printXLetterWords(List wordlist, int length) { foreach (string word in wordlist) { if (word.Length == length) { Console.WriteLine(word); } } } ```

Back to the exercises

## Dictionary Practice¶

1. It takes in student names and ID numbers (as integers) instead of names and grades.
 ``` 1 2 3 4 5 6 7 8 9 10 11``` ``` Console.WriteLine("Enter your students' names and ID numbers (or ENTER to finish):"); Console.WriteLine("Student Name: "); newStudent = Console.ReadLine(); if (newStudent!= "") { Console.WriteLine("ID: "); int newID = int.Parse(Console.ReadLine()); students.Add(newID, newStudent); } ```
1. The keys should be the IDs and the values should be the names
 ```1 2 3 4 5 6 7 8``` ``` Console.WriteLine("\nClass roster:"); foreach (KeyValuePair student in students) { Console.WriteLine(student.Value + "'s ID: " + student.Key); } Console.WriteLine("Number of students in roster: " + students.Count); ```

Note

Review the Array and List Gradebooks to see how they used loops

Back to the exercises