8.36 Lab 8a: Count by 3
Introduction
For this lab, you will use a while loop to complete the task.
A while loop has this basic structure:
/* variable initializations */ while (/*stop condition*/){ /* statements to be performed multiple times */ /* make sure the variable that the stop condition relies on is changed inside the loop. */ }
Despite the structure of the while loop being different than that of a for loop, the concept behind it is still the same. Any problem solved with a for loop can be written as a while and vice verse.
Note: the adjustment of the variable the loop is dependent on must be done inside the loop, as opposed to for loops where the variable is traditionally changed in the third section of header.
Task
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. The program will then count by 3 up until the ending value. Print the numbers separated by a space.
Sample output for input of 3 and 300:
Enter starting value: 3 Enter ending value: 300 Counting by 3 up to 30: 3 6 9 12 15 18 21 24 27 30
IMPORTANT: You may assume the user inputted starting and ending values that are divisible by 3 and inputted an ending value greater than the starting value.
import java.util.Scanner; public class CountBy3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter string value: "); int start = scan.nextInt(); System.out.print("Enter ending value: "); int end = scan.nextInt(); System.out.println("Counting by 3 from "+start+" to "+end+":"); int i = start; while(i<=end){ System.out.print(i+" "); i+=3; } System.out.println(""); } }
Get Answers For Free
Most questions answered within 1 hours.