For this lab you will write a Java program that prompts the user to enter a posi
ID: 3888545 • Letter: F
Question
For this lab you will write a Java program that prompts the user to enter a positive integer. Your program should use a loop to compute a Hailstone Series, using that integer as a start point. The Hailstone series is defined as follows: start with any integer n strictly greater than 0. If n is even, then the next value in the series is n/2. If n is odd, then the next value in the series is 3*n + 1.
This is a sample transcript of what your program should do. Items in bold are user input and should not be put on the screen by your program.
Enter a starting value: 19
19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
A second run of the code might look like this:
Enter a starting value: 18
18, 9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
Note that when the series reaches the value of 1, the sequence will start repeating: 1, 4, 2, 1 ... At this point we say that the series has converged and our loop should stop rather than repeat infinitely. Make sure your loop stops when it reaches the value of 1.
Explanation / Answer
HailStoneSeries.java
import java.util.Scanner;
public class HailStoneSeries {
public static void main(String[] args) {
// Declaring variables
int n;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
// Getting the input entered by the user
System.out.print("Enter a starting value: ");
n = sc.nextInt();
System.out.print(n + " ");
// This while loop continues to execute until the n value becomes 1
while (n > 1) {
// if n is even then this block of code will be executed
if (n % 2 == 0) {
n = n / 2;
System.out.print(n + " ");
} else {
// if n is odd then this block of code will be executed
n = (3 * n + 1);
System.out.print(n + " ");
}
}
}
}
______________________
Output:
Enter a starting value: 19
19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
___________________
Output#1:
Enter a starting value: 18
18 9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
_____________Could you rate me well.Plz .Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.