Loops 10b

Description

The purpose of this challenge is to use nested looping structures (WHILE, FOR). This challenge calculates and determines the largest hailstone numbers of the Collatz Conjecture for a range of numbers.

Collatz Conjecture

Just for fun, you can watch this video on the Collatz Conjecture. The process goes as below:

  • Take any positive number
  • If the number is even, divide it by 2
  • If the number is odd, multiply it by 3, then add 1 … (3n + 1)
  • Repetitively apply this process with each result
  • The conjecture states that eventually all results will end at 1
  • Each number generated is called a hailstone number (because it goes up and down like hailstones, before eventually falling to the ground)

Requirements

  1. Declare three integers: number, largest and largestseed. Set largest to 0
  2. Declare an integer, called hailstones 
  3. Make sure to glance at the Sample Interaction to get an idea of the program flow and the user prompts
  4. Write a FOR loop that runs from 1 to 1000000.
  5. Inside the FOR loop,
    1. set hailstones to 0
    2. set number to i (or whatever counter variable is used in the FOR loop)
    3. write a WHILE statement. Within this while statement, write the necessary constructs to perform the calculations on the hailstone numbers
      1. Run the loop as long as the value of number is greater than 1. The conjecture states that the calculations must stop as soon we get to 1.
      2. If number is even, divide it by 2
      3. If number is odd, multiply it by 3 and add 1. Basically, apply the formula 3n +1
      4. Increment hailstones. This allows us to count how many hailstone numbers have been generated.
    4. From this point forward, write code outside the WHILE, but within the FOR. Keep track of the largest hailstone number found so far. If hailstones is found to be greater than largest, then set largest to hailstones. Also, set largestseed to i (or whatever counter variable is used in the FOR loop)
  6. Display a message on which seed value generated the highest hailstone number (See Sample Interaction).

DO NOT USE

You may not use any user-defined functions, or any other loops other than FOR and WHILE.

Sample Interaction / Output

Largest count of hailstones of 475 generated by 910107

LEGEND
PROGRAM OUTPUT
USER ENTRY
FROM INPUT

CATALOG ID: CPP-FLOW00010b

Print Requirements