Reputation: 13
So I have written code for the Collatz Sequence, but I want to be able to identify and print out the largest number that appears in the sequence. Here is my code:
import java.util.Scanner;
public class CollatzSequence {
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
int n,ts = 0;
System.out.print("This is the Lothar Collatz Sequnce. Please enter the starting number.\n>");
n = keyboard.nextInt();
do {
if (n % 2 == 0) {
n = n / 2;
System.out.println(n);
}
else {
n = n*3 + 1;
System.out.println(n);
}
ts++;
}
while (n != 1);
System.out.println("Terminated after "+ts+" steps.");
}
}
Upvotes: 1
Views: 317
Reputation: 1410
Make a variable called max
. Set it initially equal to n
. In each step, check if n > max
and if it is, set max
to n
.
Upvotes: 2