60 664
Assignments Done
97,7%
Successfully Done
In April 2018

Answer to Question #75071 in C for Mohammad

Question #75071
Write a C program that reads 10 integers (between 0-1000) into a one-dimensional array
and computes and finds the value that has the largest chain. You should compute the
largest chain as explained below.
Example:
For each value (n) in your array, your chain will be determined as follows;
If n is even -> n=n/2
If n is odd -> n=3n+1
For example , if 12 is your starting number , the chain will be ,
6 -> 3 -> 10 -> 5 ->16 -> 8 -> 4 -> 2 -> 1
12 is even so 12/2 will be 6.
6 is even 6/3 will be 3.
3 is odd 3*3+1 will be 10.
.
.
.
The chain will grow until the value is 1.
Write a function called findLargestChain() that accepts an integer, finds and prints the
chain elements to the screen , and returns the number of elements.
You should store the number of elements into another array.
In the main program, you should read 10 integers into an array , call the function for each
integer and store the number of elements into another array.
Expert's answer
#include <stdio.h>
#include <stdlib.h>

int findLargestChain(int n)
{
printf("Chain for %d\n",n);
int ans=1;
while(n>1)
{
if(n&1)
{
n=3*n+1;
}
else
{
n/=2;
}
++ans;
printf("%d",n);
if(n!=1)
{
printf("->");
}
}

printf("\n");

return ans;
}

int main()
{
int *arr=malloc(sizeof(int)*10);
int *resArr=malloc(sizeof(int)*10);

int i;
int maxChainElement=0;
int chainLength=0;
for(i=0;i<10;++i)
{
arr[i]=rand()%1000;
resArr[i]=findLargestChain(arr[i]);
if(resArr[i]>chainLength)
{
chainLength=resArr[i];
maxChainElement=arr[i];
}
}

printf("Element that has the largest chain with length %d is %d\n",chainLength,maxChainElement);

free(arr);
free(resArr);

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions