This practical task introduces you to repetition which allows to loop over blocks of code numerous times. The
number of iterations is dependent on the problem we are solving and can be controlled using three different
loop structures: for, while and do … while. When using the for loop, we need to be aware of the number of
iterations we will be carrying out, however for the while or do … while they will repeat until the condition
holds. Remember that the do … while will always carry out the instructions in the loop at least once, and
therefore it is very useful for validating a user’s input.
The tasks in the first part of this practical provide the step‐by‐step instructions on how to program in C# using
loops. This is followed by a number of tasks for you to complete by applying the knowledge gained in the first
1. Design an algorithm, first writing a pseudocode on paper, which prints the sum of 1, 2, 3, …, to an upper
bound determined by the user’s input (e.g. 100). Then create a new C# Console Application project and
write a program to achieve this. Once coded, it should also compute and display the average of the
numbers. The output should look like:
The sum is 5050
The average is 50.5
Give a new name to the main class of the project by changing it from the default Program to Repetition
in the Solution Explorer of your IDE (Microsoft Visual Studio or Studio Code). Type the following code into
the Main method of the Repetition class.
Complete the missing parts, compile, and run the program. Check whether the produced output is as
2. Add a new block of code into the Main method. Modify the code written in the first task to use a while
loop instead of the for loop, which you need to replace with the following code.
What is the difference between the for and while loops? If you want to see what is happening in the loops
then trace sum and number. You can do this by adding the following line inside each of the loops after the
This will allow you to see what is happening during each iteration of the loop.
3. Add one more block of code into the Main method. Modify the code to use a do … while loop instead
of the while loop. Replace the while loop with the following code.