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

Write a C program that will get input from the user (e.g. using scanf, fgets, et

ID: 3920139 • Letter: W

Question

Write a C program that will get input from the user (e.g. using scanf, fgets, etc.).Your program will convert valid input from the user (only positives integers greater than zero) and return the answer. If the user input anything other than a positive integer then immediately print out an error message.

There will only be three options, which are the following:

1. Print out your name.

2. Print out the i-th Fibonacci number. Please use recursion so that it is slower.

3. Exit the program. However, before doing so, terminate all existing pthreads that are currently running before exiting.

In the first two cases you will spawn a new thread to either print your name or print out the i-th Fibonacci number. Our program will start with a 0 in the sequence.Do not wait for the answer to be generated before waiting for new input. Continue to get input from the user until the user enters "3" then exit the program.

Explanation / Answer

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

int fibonacci(int num)

{

if (num == 0)

{

return 0;

}

else if (num == 1)

{

return 1;

}

else

{

return(fibonacci(num - 1) + fibonacci(num - 2));

}

}

void *Fib(void *vargp)

{

int *n = (char*)vargp;

printf(" %dth Fibonacci number:%d ",*n,fibonacci(*n));

}

void *print_name(void *vargp)

{

sleep(1);

char *name = (char *)vargp;

printf("Your name:%s ",name);//printing name...

return NULL;

}

  

int main()

{

int n,c;

char name[20];

printf("Enter name:");

scanf("%s",c);

pthread_t thread_id;

while(1)

{

printf(" 1:Print out your name. 2:Print out the i-th Fibonacci number 3:Exit ");

printf("Enter ur choice:");

scanf("%d",&n);//reading choice

if(c==1)

{

//calling thread

pthread_create(&thread_id, NULL, print_name, (void*)name);

pthread_join(thread_id, NULL);

}

else if(c==2)

{

while(1)

{

printf("Enter a positive number:");

scanf("%d",&n);

if(n<=0)//printing error msg

{

printf(" Error---Please enter a positive number-- ");

}

else break;

}

pthread_create(&thread_id, NULL, Fib, (void*)&n);

pthread_join(thread_id, NULL);

}

else if(c==3)break;

}

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote