Counting and Looping
The program in LoveCS.java prints “I love Computer Science!!” 10 times. Copy it to your directory and compile and run it to see how it works. Then modify it as follows:
// ****************************************************************
// LoveCS.java
//
// Use a while loop to print many messages declaring your
// passion for computer science
// ****************************************************************
public class LoveCS
{
public static void main(String[] args)
{
final int LIMIT = 10;
in count = 1;
while (count <= LIMIT)
{
System.out.println(“I love Computer Science!!”);
count++;
}
}
}
1. Instead of using constant LIMIT, ask the user how many times the message should be printed. You will need to declare a variable to store the user’s response and use that variable to control the loop. (Remember that all caps is used only for constants!)
2. Number each line in the output, and add a message at the end of the loop that says how many times the message was printed. So if the user enters 3, your program should print this:
1 I love Computer Science!!
2 I love Computer Science!!
3 I love Computer Science!!
Printed this message 3 times
3. If the message is printed N times, compute and print the sum of the numbers from 1 to N. So for the example above, the last line would now read:
Printed this message 3 times. The sum of the numbers from 1 to 3 is 6.
Note that you will need to add a variable to hold the sum.