You are to take the conditional from the previous section an

You are to take the conditional from the previous section and build a loop around it to find the Collatz sequence. The structure of this would be: while (n > 1) {If (n is even) {n = n/2;} else {n = 3 * n + 1;} cout

Solution

Following is the C++ code, printing collatz sequence for different values of n

#include <iostream>
using namespace std;

void collatzSequence( int n ){
   cout << n << \" \";
   while( n > 1 ){
       if( n%2 == 0 ){
           n = n/2;
       }
       else{
           n = 3*n + 1;
       }
       cout << n << \" \";
   }
   cout << endl;
}

int main(){
   int Ns[] = {10,11,12,13,14,15,16};
   int size = sizeof(Ns)/sizeof(int);
   for(int i = 0; i < size; i++ ){
       collatzSequence( Ns[i] );
   }

   return 0;
}

 You are to take the conditional from the previous section and build a loop around it to find the Collatz sequence. The structure of this would be: while (n >

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site