In: Computer Science
Solution:
Calculating sum using Arithmatic Progression.
Sum of n terms in AP = (n/2)*(2*a + (n-1)*d)
here n = 10 , a is the start value , d = 1
On simplification............
Sum = 5 * ( 2*a + 9 )
Look at the code and comments for better understanding......
Screenshot of the code:
Output:
Code to copy:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void *calculateSum(void *args)
{
//getting the start value
int start=*((int *)args);
int *sum=(int *)malloc(sizeof(int));
//calculating the sum stating with value start
// using the formula sum=5*(2*start+9)
*sum = 5*(start*2+9);
printf("The sum from %d to %d = %d\n",start,start+9,*sum);
//returning the sum
pthread_exit(sum);
}
int main()
{
//creating 4 thread variables
pthread_t t1,t2,t3,t4;
//assingning the start value
int start1=1,start2=11,start3=21,start4=31;
//creating 4 threads
pthread_create(&t1,NULL,calculateSum,(void *)&start1);
pthread_create(&t2,NULL,calculateSum,(void *)&start2);
pthread_create(&t3,NULL,calculateSum,(void *)&start3);
pthread_create(&t4,NULL,calculateSum,(void *)&start4);
//getting the sum value from thread and storing it in ret variable
void *ret_value;
pthread_join(t1,&ret_value);
int ret1=*((int *)ret_value);
pthread_join(t2,&ret_value);
int ret2=*((int *)ret_value);
pthread_join(t3,&ret_value);
int ret3=*((int *)ret_value);
pthread_join(t4,&ret_value);
int ret4=*((int *)ret_value);
//printing the thread return values
printf("Thread 0 :%d\n",ret1);
printf("Thread 1 :%d\n",ret2);
printf("Thread 2 :%d\n",ret3);
printf("Thread 3 :%d\n",ret4);
//calculatin total value
int total_sum=ret1+ret2+ret3+ret4;
printf("Total = %d\n",total_sum);
}
I hope this would help.........................:-))