ITEC 120
L04a: Loops

Objectives

To successfully complete this lab you will develop loops that count and loops that accumulate values.

Assignment

Write a program called Count that prompts the user for a starting number and ending number, then outputs all the numbers between the start and end (including the start and end) and prints the sum of all those numbers. Like so (user input is in red):

   Enter a starting number: 4
   Enter an ending number:  12
   
   4
   5
   6
   7
   8
   9
   10
   11
   12
   
   The sum of the numbers from 4 to 12 is 72

This can be a hard problem to solve if you try to solve it all at once. It can be helpful when solving problems like this to break it down into smaller problems. First, solve an easier problem, get it working, and then incrementally add functionality to your program.  Try this approach:

Counting Down

So far, you have probably entered a starting number that comes before the ending number. What should you do if someone enters a starting number that is larger than the ending number? Change your program so that it will count down if the user enters a starting number that is bigger than the ending number. (But the counting up part of your program should still work too.)

   Enter a starting point: 5
   Enter an ending point: 2

   5
   4
   3
   2

   The sum of the numbers from 5 to 2 is 14

Test your program

Are you done? Maybe. We should make sure that there are no inputs that will "break" our code. What happens when you enter negative numbers into your program? Have you tried it? How about if the starting point and the ending point are the same number? Here are some test cases you should try.

 START   END     SUM
     4     4       4
    10     5      45
     3     9      42
     4    -3       4
    -4     6      11
    -2    -7     -27
    -5    -1     -15
     1     0       1
     0     0       0
     0     3       6
     0    -3      -6

If any of these test cases don't give you the correct answer, go fix your code. Can you think of any other test cases you should try?

Creating general solutions

Notice what we have been doing.  We started with a simple, concrete task: count from 1 to 10, and we gradually generalized our code to the point that our program counts up or down from any two numbers, and calculates the sum of those numbers.  General solutions are more reusable than specific solutions.  When you write code to perform a task, define the task in general terms so the code may be reused. 

Submit Your Assignment

Submit your Count.java file to the L04a dropbox on D2L.