Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. //Requires:  n > 0
  2. //Modifies:  nothing
  3. //Effects:   prints a series of values
  4. //        if n is even, halve it
  5. //        if n is odd, triple it and add one
  6. //        continue until n is 1
  7. // starting with 3 gives
  8. // 3, 10, 5, 16, 8, 4, 2, 1
  9. void threeSeries (int n)
  10. {
  11. if(n<=0) //Returns if number is 0 or negative
  12.         return;
  13. if( n > 0)
  14. {
  15.     cout<<n<<", ";
  16.         while(n != 1) //Declaring the condition for this loop (while n isn't = to 1)
  17.         {
  18.                 if(n%2 == 0) //This statement finds even numbers
  19.                         {
  20.                         n /= 2; //Halves n
  21.                         cout<<n<<", ";
  22.                         }
  23.                 else if(n%2 == 1) //This statement finds odd numbers
  24.                         {
  25.                         n = (n*3) +1; //Triples n and adds 1
  26.                         cout<<n<<", ";
  27.                         }
  28.         }
  29.         cout<<endl;
  30. }
  31. }
  32.  
  33.  
  34. to:
  35.  
  36.  
  37. //Requires:  n > 0
  38. //Modifies:  nothing
  39. //Effects:   prints a series of values
  40. //        if n is even, halve it
  41. //        if n is odd, triple it and add one
  42. //        continue until n is 1
  43. // starting with 3 gives
  44. // 3, 10, 5, 16, 8, 4, 2, 1
  45. void threeSeries (int n)
  46. {
  47. if(n<=0) //Returns if number is 0 or negative
  48.         return;
  49. if( n > 0)
  50. {
  51.     cout<<n<<", ";
  52.         while(n > 1) //Declaring the condition for this loop (while n isn't = to 1)
  53.         {
  54.                 if(n%2 == 0) //This statement finds even numbers
  55.                         {
  56.                         n /= 2; //Halves n
  57.                         cout<<n<<", ";
  58.                         }
  59.                 else if(n%2 == 1) //This statement finds odd numbers
  60.                         {
  61.                         n = (n*3) +1; //Triples n and adds 1
  62.                         cout<<n<<", ";
  63.                         }
  64.         }
  65.         cout<<"1"<<endl;
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement