Condition-controlled loops

If you’ve done the count condition exercise you know that you can loop with a count-condition to do something a fixed number of times. SOmetimes however, you don’t know how many  times you want to do something beforehand. You simple want to do this until a certain condition is no longer valid. You can sometimes accomplish this with a for loop and if-statements, but a better way to do it is usually to use one of the options the language gives you. Below you’ll find two exercises where you can apply this. We’ll stick to numbers for simplicity.Also, when using loops with conditions, make sure the loop will actually end. DOn’t end up with an infinite loop!

Exercise #1

Goal

Write a program that sets a variable to 10000 and another value to 0. In my example I’ll call them counter and target. Use a thrid variable to store the current total value. Starta loop and keep increasing your counter by one (1) until and add the counter to the current total value. Exit the loop when the current total value reaches the target value. Print the current value as well as the counter before the program ends.

Language: Any
Difficulty level: Very easy.
Estimated time: 5-10 minutes

Exercise #2

Goal

The definition of a prime number is that it’s only positive divisors are 1 and itself. It also has to be greater than one. Write a program that prints all prime numbers between 1 and 1.000.000. To do this in a resonable amount of time you need to know some math and how to use a specific operator or function in your programming language of choice (See hints below if you need help). I suggest testing with a lower number first. Your first few results should be 2,3,5,7,11,13.  NOTE: This program will take a long time to run.

Language: Any
Difficulty level: Very easy.
Estimated time: 10-20 minutes

Hint #1 Hint #2 Hint #3 Solution in C#
This entry was posted in Basic control flow. Bookmark the permalink.