Fibonacci Multi Threaded C Program To Print Element Of Fibonacci Series

How to write a C Program Fibonacci Multi Threaded and print the elements of Fibonacci Series in C Programming Language ?


Solution:
  1. #include <stdio.h>
  2. #include <omp.h>
  3.  
  4. int main()
  5. {
  6.   int n, a[100], i;
  7.  
  8.   // Setting number of threads to 2
  9.   omp_set_num_threads(2);
  10.  
  11.   printf("Enter the number of Fibonacci numbers to be generated : \n > ");
  12.   scanf("%d", &n);
  13.  
  14.   a[0] = 0; a[1] = 1;
  15.  
  16.   #pragma omp parallel
  17.   {
  18.     #pragma omp single
  19.     for (= 2; i < n; i++) {
  20.       a[i] = a[i-1] + a[i-2];
  21.       printf("Computation of Fibonacci number %d, thread_id is %d\n", i, omp_get_thread_num());
  22.     }
  23.    
  24.     #pragma omp barrier
  25.    
  26.     #pragma omp single
  27.     {
  28.       printf("The elements of the fibonacci series are : \n");
  29.       for (= 0; i < n; i++) {
  30.         printf("%d, thread_id is %d\n", a[i], omp_get_thread_num());
  31.       }
  32.     }
  33.   }  
  34.  
  35.   return 0;
  36. }


Learn More :