10 Practice Programs with Solutions
1. Thread to check if a number is Even or Odd
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* check_even_odd(void* arg) {
int num = *((int*)arg);
int* result = (int*)malloc(sizeof(int));
*result = (num % 2 == 0) ? 1 : 0;
pthread_exit((void*)result);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
pthread_t t1;
int* res;
pthread_create(&t1, NULL, check_even_odd, (void*)&num);
pthread_join(t1, (void**)&res);
if (*res)
printf("%d is EVEN\n", num);
else
printf("%d is ODD\n", num);
free(res);
return 0;
}
2. Thread to calculate factorial of a number
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* factorial(void* arg) {
int n = *((int*)arg);
long long* fact = (long long*)malloc(sizeof(long long));
*fact = 1;
for (int i = 2; i <= n; i++) {
*fact *= i;
}
pthread_exit((void*)fact);
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
pthread_t t1;
long long* result;
pthread_create(&t1, NULL, factorial, (void*)&n);
pthread_join(t1, (void**)&result);
printf("Factorial of %d is %lld\n", n, *result);
free(result);
return 0;
}