KIT506 Programming Practical 3: Repeat actions for a number of steps
KIT506 Programming Practical 3: Repeat actions for a number of steps
[ ↔ Expand↶ Close all sections ] Only visible sections will be included when printing this document.
Aims:
to understand multiway branching with switch; and
to use for loops to repeat an action a given number of times.
1 Reading Exercises
1.1 Nested ifs
Trace the following code to determine the final value of result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int x = 10;
int y = 5;
int result = 0;
if (x % y == 0) {
result = 1;
if (x < y) {
result = 2;
} else {
result = 3;
}
} else {
result = 4;
}
If we were to trace the value of all variables in this program we would produce the following tracing table:
Line x y result
1 10
2 10 5
3 10 5 0
6 10 5 1
10 10 5 3
Which tells us the the final value of result is 3.
To work this out we can trace the program to the first decision point at line 5 (x % y == 0, which asks ‘is x evenly divisible by y?’) to determine that 10 is evenly divisible by 5 and so the if branch will be executed. This updates the value of result to 1, but the program keeps going…
The if on line 7 asks if x is less than y (i.e., ‘is 10 less than 5?’). Since this is false the else branch (line 9) is executed, changing result to 3.
1.2 Switch
Without creating a tracing table (you won’t need it), determine the output of this code if the user enters the text monday when prompted:
string day;
string message;
Console.Write("What day is it today? ");
day = Console.ReadLine();
switch (day.ToLower())
{
case "sunday": message = "Time for the weekly shopping"; break;
case "monday": message = "I hate Mondays - Garfield"; break;
case "tuesday": message = "Only four more days to go"; break;
case "wednesday": message = "Middle of the week!"; break;
case "thursday": message = "Will there be thunder later?"; break;
case "friday": message = "TGIF!"; break;
case "saturday": message = "It's the weekend!"; break;
default: message = "I don't understand what day of the week '" + day + "' is."; break;
}
Console.WriteLine(message);
If the user enters Monday then the program will output
I hate Mondays - NAME if the user were to enter TueSDaY?
Only four more days to go
By calling ToLower() on the string the user has entered we guarantee that we can match English day names to the lower case values in the switch’s cases.
Finally, what if the user entered onsdag, which is the name of Wednesday in Swedish, Norwegian and Danish?
I don't understand what day of the week 'onsdag' is.
Tip: You can control a switch statement with integers, characters, strings (as above) and enumerated types.
2 Repeating actions for a given number of times
2.1 Repeat n times
Create a new program and in the Main method write a for-loop that prints 20 asterisks (*). Before you write it answer the following, keeping in mind the structure of the loop:
for (initialisation; boolean expression to test; update)
{
body
}
What is the initialisation? We need a counter, so we can declare an int variable and initialise it in the initialisation part. int i = 0 or int i = 1 would work.
What is the test? We want to stop when we have printed 20 asterisks, so we should continue to loop as long as our counter is less than that: i < 20 if i began at 0 or i <= 20 if i began at 1.
What is the update? Since we’re counting actions (printing a single asterisk) we should increment i by 1 each time: i++ is a shorthand for i = i + 1
What is the loop body? We want to print a single asterisk, but do not want to move to the next line until the end, so Console.Write("*") is suitable.
So the contents of our program will look like the following (hint: starting at zero will be useful for later):
for (int i = 0; i < 20; i++)
{
Console.Write("*");
}
Console.WriteLine(); //add a newline to the end
2.2 For each index in an array or List
One of the common uses for a for-loop is for iterating of the indices (positions) in structures such as Lists and arrays. Temporarily comment out the loop code you wrote before (wrap it in an opening /* and closing */) as you’ll use it again next, and write some new code before it.
Add the following at the start of the Main method. It declares and initialises an array of integer values:
int[] counts = {1, 0, 5, 7, 4, 2, 1};
Diagrammatically, counts looks like:
index 0 1 2 3 4 5 6
value 1 0 5 7 4 2 1
Task: Now write a for-loop that will display each value in the array counts, one per line, prefixed by its position and a pipe symbol |. In other words, we want the output to look like:
0 | 1
1 | 0
2 | 5
3 | 7
4 | 4
5 | 2
6 | 1
What is the initialisation? Array indices start at zero, so we should initialise the loop variable (call it n) to that: int n = 0.
What is the test? We want to stop when n is beyond the end of the array, which we can read using counts.Length, so i < counts.Length
What is the update? Since we’re visiting each position in the array, we should step by 1: n++
What is the loop body? We want to print the current position, followed by |, followed by the value at that position in the array, which we can access via counts[n], so Console.WriteLine(n + " | " + counts[n]) is suitable.
So the contents of our program (up to the commented out code from before) will look like the following:
int[] counts = {1, 0, 5, 7, 4, 2, 1};
for (int n = 0; n < counts.Length; n++)
{
Console.WriteLine(n + " | " + counts[n]);
}
2.3 (Optional challenge) Horizontal histogram
What if we want to display a text-based histogram (bar chart) instead of just the values from the array? Can you think of how you might combine the first loop with the second one to produce output like this?
0 | *
1 |
2 | *****
3 | *******
4 | ****
5 | **
6 | *
We can reuse (with a little modification) the asterisk-printing loop inside the one that prints values from the array. But, we need to make some changes:
We need to change the existing WriteLine to print just the value of n and the |, without also printing the newline character:
Console.Write(n + " | ");
Then…
…we need to copy the asterisk-printing loop immediately after that. If you used the same loop variable name, change it in one them so the identifiers are different.
If you were to run your code at the moment, would it give you the correct result (try it if you like)?
Ah, there’s one more change we need to make: set the upper bound on the inner loop to be the current value of the counts array, counts[n], rather than the fixed value of 20. When all of these changes have been made, the program will look like:
int[] counts = { 1, 0, 5, 7, 4, 2, 1 };
for (int n = 0; n < counts.Length; n++)
{
Console.Write(n + " | ");
for (int i = 0; i < counts[n]; i++)
{
Console.Write("*");
}
Console.WriteLine(); //add a newline to the end
}
3 Next week: test + while loops
At the start of next week’s practical class you’ll do a 20-minute online quiz on programming skills up to this point, which will contribute to your final grade. After that you’ll do some practical exercises involving another form of loop, the while loop.