Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please explain and write the C program for the following programming problem and

ID: 3594653 • Letter: P

Question

Please explain and write the C program for the following programming problem and explain details for me and write the c program for this problem? Thank you.

the Collatz conjecture concerns what happens when we take any positive integer n and apply the following algorithm:

n = n/2 if n is even, and n = 3*n+1 if n is odd}

The conjecture states that when this algorithm is continually applied, all positive integers will eventually reach 1. For example, if n = 35, the sequence is

35, 106,53,160,80,40,20,10,5,16,8,4,2,1

Please write a C program using the fork() system call that generates this sequence in the child process. The starting number will be provided from the command line. For example, if 8 is passed as a parameter on the command line, the child process wil output 8,4,2,1. Because the parent and child processes have their own copies of the data, it will be necessary for the child to output the sequence. Have the parent invoke the wait() call to wait for the child process to complete before exiting the program. Perform necessary error checking to ensure that a positive integer is passed on the command line.

Explanation / Answer

Solution:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int Collatz(int num)
{
int count = 0;       /*Initialize count to 0*/
if(num <= 0)
{
printf("Oops.... Collatz Sequence works only for positive integers.");
return 0;
}
while(count != 10000) /*Loop repeats for 10000 times.*/
{
if(num == 1)       /*If num is 1.*/
{
printf("%i ",num);/*Print it.*/
return 0;           /*Return*/
}
else if(num % 2 == 0)/*If num is even.*/
{
printf("%i ",num); /*Print it.*/
num /= 2;           /*Half the number.*/
}
else               /*If neither condition satifies, i.e., if num is odd.*/
{
printf("%i ",num);   /*Print it.*/
num = num * 3 + 1;   /*Triple the number and add 1 to it.*/
}
count++;                 /*Increment the count.*/
}
return 0;
}

int main(int argc, char *argv[])
{
int num, stat_loc = 0;
pid_t pid;
num = atoi(argv[1]);                   /*Read the value.*/
pid = fork();                       /*Creating a child process*/
if(pid == -1)                       /*If unable to create a child, generate an error message*/
{
printf("Child Process didn't get created.");
}
else if(pid == 0)       /*When running the child process.*/
{
printf("The Collatz Conjecture is: ");/*Print a prompt.*/
Collatz(num);       /*Call the function to print the sequence of numbers.*/
}    
else if(pid > 0)       /*Make the parent process wait till the child is finished.*/
{
wait(&stat_loc);
printf(" ");
}                           
}

Please, please upvote and ask your doubts in the comments.