Solution to Program 1

 

/**

*

*   Name(s):

*   ID(s):

*   Sections(s):

*

*   CS100J: Program 1

*   Fall 2000

*  

*   Input any integer and repeatedly divide it by 2 if even and multiply itby

*   3 and add 1 if odd.  Stop on reaching 1 or less.

*

*/

 

import java.io.*;

public class CUCSApplication

{

public static void main ( String[] args )

{

          int k;

 

          // Initialize TokenReader object to read from standard input.

          TokenReader in = new TokenReader( System.in );

 

          // Read and write some numbers and strings

          System.out.println( "Please enter an integer: " );

 

          // Read integer

          k = in.readInt();

 

          // Perform algorithm

          while ( k > 1 )

               if ( k % 2 == 0 ) {     // test if k is even

                   k = k/2;

                   System.out.println( k + " after dividing by 2" );

               }

               else {          // if k is odd

                   k = 3*k + 1;

                   System.out.println( k + " after multiplying by 3 and adding 1" );

               }

    

System.out.println( "Done!" );

     }

}