Home > front end >  Printing Result in Recursive Factorial Function Using Threads C
Printing Result in Recursive Factorial Function Using Threads C

Time:05-02

I am facing an issue here in trying to print the answer. Code is working well with loops as i can save the ans in a global variable and print at end. But now i want to do same with a recursive function but i am unable to store the return value in a variable to print in main() function

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> 

int num;
int result;
int factorial(int n) {
    if (n>=1)
        return n*factorial(n-1);
    else
        return 1;
}

int main()
{
pthread_t thread;
printf("Enter Number To Find Its Factorial: ");
scanf("%d",&num);
result=pthread_create (&thread,NULL,factorial,(int*)&num);

pthread_join( thread, NULL );
printf("Factorial of Number is = %d",result);
return 0;
}

Loop part of same code

int fac=1;
int* factorial()
{

for(int a=1;a<=num;a  ) 
{
fac=fac*a;
}
return &fac;

}

CodePudding user response:

Like this

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct param_t {
    int num;
    int result;
};

int factorial(int n)
{
    if (n >= 1)
        return n * factorial(n - 1);
    else
        return 1;
}

void *thread_func(void *args)
{
    struct param_t *param = (struct param_t *)args;
    param->result = factorial(param->num);
    return (void *)NULL;
}

int main()
{
    struct param_t param;
    pthread_t thread;
    printf("Enter Number To Find Its Factorial: ");
    scanf("%d", &param.num);
    pthread_create(&thread, NULL, thread_func, &param);
    pthread_join(thread, NULL);
    printf("Factorial of Number is = %d", param.result);
    return 0;
}
  • Related