CSCI 1301 – Lab 24

Clément Aubert

November 15, 2018

A Simple Loop

Write a program that asks the user to enter a positive integer, and then uses a for loop to compute the sum of all the integers between 1 and the integer given by the user. For instance, if the user enters 5, your program should display 15 at the screen (i.e., 1 + 2 + 3 + 4 + 5 = 15).

Then, answer the following questions:

  1. Whitout running your program, can you tell what will happen if the user enter a negative value?
  2. Do you think you could have written the same program using a while loop?
  3. How could you change your program so that it would compute the product instead of the sum (i.e., for 5, 1 × 2 × 3 × 4 × 5 = 120)?
  4. How could you change your program so that it would display on the screen the divisors of the integer entered (i.e., for 5, only 1 and 5).

You can modify your program to check your answers to the previous questions. Once you are done, modify your original program with two respects:

  1. Once the result of the computation is displayed at the screen, ask the user if (s)he wants to compute the sum using another integer or quit, and act accordingly.
  2. Make some input-validation: floatting-point values, strings and negative values should not be allowed (i.e., your program should ask for another value).

A Guessing Game (Optional)

We will revisit our guessing game from Lab 16. If you haven’t solved it already, have a look back and solve it.

Read carefully the challenge below, and think about the parts of your previous program you can re-use to solve this one.

Write a program that asks the user which level of difficulty (s)he wants to play: easy, medium or hard. Then, generate a random number: between 0 and 10 for easy, between 0 and 50 for medium, and between 0 and 100 for hard. Then, let the user try to guess the number you randomly generated: