In: Computer Science
8.37 Lab 8b: Count by 3 Expanded
Task
This program is a continuation of Lab 8a. Create a program called CountBy3.java that will accept two numbers from the user, one to serve as the starting point and the other number as the ending point.
For this program, you will need two loops. The first loop will handle the print out "Counting by 3 from [starting value] to [ending value]". The ending value may not be what is inputted from the user. Instead, your loop will determine if you have to modify the ending value to be a number that is some multiple of 3 times the starting value. If there is any confusion, check out the sample output below.
Your second loop will then count by 3 up until the ending value or before if the ending value is not divisible by 3. Print the numbers separated by a space.
Sample output for input of 2 and 31:
Enter starting value: 2 Enter ending value: 31 Counting by 3 from 2 to 29: 2 5 8 11 14 17 20 23 26 29
IMPORTANT: Pieces of this code will be very similar to lab 8a and the two loops will be similar as well.
Source Code:
Output:
Code in text format (See above images of code for indentation):
import java.util.*;
/*class definition*/
public class CountBy3
{
/*main method*/
public static void main(String[] args)
{
/*Scanner class to read input from the user*/
Scanner read=new Scanner(System.in);
/*variables*/
int start,end,i,dend=0;
/*read start value*/
System.out.print("Enter starting value: ");
start=read.nextInt();
/*read end value*/
System.out.print("Enter Ending value: ");
end=read.nextInt();
/*find the ending value*/
for(i=start;i<end;i+=3)
dend=i;
/*print header*/
System.out.println("Counting by 3 from "+start+" to "+dend+":");
/*print numbers separated by space*/
for(i=start;i<end;i+=3)
System.out.print(i+" ");
}
}