Skip to main content

Section 13.9 Fun With Loops!

Remember: the best way to learn to code is to write code! So letโ€™s practice our loops. Pick one of the following prompts. And most importantly: have fun! If you get done early, pick another one!

Subsection 13.9.1 Option 1

Activity 13.8.

Write a program that prompts the user to enter a positive integer n and then computes the sum of the numbers from 1 through n. For example, if the user enters 5, then your programโ€™s output should be:
"The sum of the numbers from 1 through 5 equals 15."
A quick way to check that your program works is to ensure that the sum of the numbers from 1 to n equals \(\frac{n(n+1)}{2}\text{.}\)
Write two versions of this program: One using a while-loop, and another one using a for-loop.

admin.....open in new window

Subsection 13.9.2 Option 2

Activity 13.9.

Write a program that continuously asks the user to enter a nonzero number and adds up all of the numbers entered. The program should terminate when the user enters a zero and then print out the total sum.
Here is a sample run of the program:
Please enter a number: 5
Please enter a number: 11
Please enter a number: -3
Please enter a number: 0
The numbers you entered add up to 13.

admin.....open in new window

Subsection 13.9.3 Option 3

Activity 13.10.

Write a program that prompts the user for two numbers p and q, then calculates the greatest common divisor of p and q. You may do so using the "brute force" method: If q \(\leq\) p, for example, you simply check each of the divisors q, q-1, q-2, ..., 1, until you find one that divides both p and q.
Challenge: implement the Euclidean algorithm!

admin.....open in new window

Subsection 13.9.4 Option 4

Activity 13.11.

Write a program that determines whether a number entered by the user is prime (again, you may use the โ€œbrute forceโ€ method, going through all possible divisors 2, 3, 4, โ€ฆ, n).
(You only really need to check factors up to \(\sqrt{n}\text{.}\))

admin.....open in new window