Hailstone solution -Assignment 2

/*
 * File: Hailstone.java
 * Name: 
 * Section Leader: 
 * --------------------
 * This file is the starter file for the Hailstone problem.
 */

import acm.program.*;

public class Hailstone extends ConsoleProgram {
	public void run() {
		//index for the number of loops to do
		int index =0;
		
		//query for the number
		int number = readInt("Enter a number: ");
		
		//loop until the number ==1
		while(number!=1){
			//increment the loop
			index++;
			
			//if number is even take half
			if(number%2==0){
				println(number+" is even so I take half: "+(number/=2));
			} else {
				//else if odd make it 3n+1
				println(number+" is odd, so I make 3n +1: "+(number = (number*3)+1));
			}
		}
		//print the number of loops
		println("The process took "+index+" to reach 1.");
	}
}

Leave a Reply