c fibonacci sequence with thrads code example
Example 1: fibonacci series in c
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);
for(i=2;i<number;++i)
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}
Example 2: fibonacci series in c
#include <stdio.h>
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while (nextTerm <= n) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Example 3: Fibonacci program c pthread
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int n;
int *fibseq;
int i;
void *runn(void *arg);
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("format is:./a.out <intgervalue>\n");
return -1;
}
if (atoi(argv[1]) < 0)
{
printf("%d must be>=0\n", atoi(argv[1]));
return -1;
}
n = atoi(argv[1]);
fibseq = (int *)malloc(n * sizeof(int));
pthread_t *threads = (pthread_t *) malloc(n * sizeof(pthread_t));
pthread_attr_t attr;
pthread_attr_init(&attr);
for (i = 0; i < n; i++)
{
pthread_create(&threads[i], &attr, runn, NULL);
}
int j;
for (j = 0; j < n; j++)
{
pthread_join(threads[j], NULL);
}
printf("The Fibonacci sequence.:");
int k;
for (k = 0; k < n; k++)
{
printf("%d,", fibseq[k]);
}
return 0;
}
void *runn(void *arg)
{
if (i == 0)
{
fibseq[i] = 0;
pthread_exit(0);
}
if (i == 1)
{
fibseq[i] = 1;
pthread_exit(0);
}
else
{
fibseq[i] = fibseq[i - 1] + fibseq[i - 2];
pthread_exit(0);
}
}