Hello,

i need to use fork() for the below problem

Problem statement is program would accept various 2d arrays as inputs as long as the user wishes to enter.. Every individual sum of the array is calculated and sum of each array becomes the element of a resultant array and then the output would be the sum total of resultant array.My aim is to find and compare the computation speed by implementing the problem in two ways one is the normal program in C which would take care of the above and the other using fork() (I have implemented using the normal method whose code is pasted after the example. I need to know hw it can be implemented using fork()). Plz help!!!
Example :
number of matrices to be entered = 2
dimension of 1st matrix = 2x2
1st matrix : 1 2
3 4
dimension of 2nd matrix = 2x3
2nd matrix 2 1 3
1 3 5

Resultant matrix : 10 (sum of elements of 1st matrix)
15(sum of elements of 2nd matrix
sum of resultant : 25

Code :

``````#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
#include<alloc.h>
#include <time.h>

int  main()
{
int num,p,q,i,j,k,result=0,array_result = 0;
int arr[10];
int **a;
clrscr();
printf("Enter the number of matrices : ");
scanf("%d",&num);
for(k=0;k<num;k++)
{
printf("Enter the dimension of %d matrix : ",k+1);
scanf("%d%d : \n",&p,&q);
a=(int **)malloc(p*sizeof(int *));

for(i=0;i<p;i++)
{
a[i] = (int *)malloc(q*sizeof(int));}

for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&a[i][j]);
}

result = sum(a,p,q);
system("PAUSE");
arr[k] = result;

}

{
array_result = array_result + arr[k];
}
}       printf("Resultant Array : Sum total of each input array \n");
for(k=0;k<num;k++)
printf(" %d\n",arr[k]);
printf("Sum Total of Resultant Result : %d\n", array_result);
printf("Elapsed time: %u secs.\n", clock()/CLOCKS_PER_SEC);

return 0;
}

int sum(int **arr,int p,int q)
{
int res = 0,i=0,j=0;
for(i=0;i<p;i++)
for(j=0;j<q;j++)
{
res = res + arr[i][j];
}
return res;
}``````
2
Contributors
1
4
Views
9 Years
Discussion Span
Last Post by Duoas

It might help to consider what two things you are doing.

1) input an array
2) return its sum

The main program should work something like

``````main()
{
sum = 0;
while (user wishes to input an array)
{
sum += get_and_sum_array();
}
print sum;
}

int get_and_sum_array() { ... }``````

To use fork, instead of calling a function to read and sum an array from the user, instead fork and return the sum via the exit status code. Keep in mind that the status code is limited in range. You could return the number other ways, but for your assignment just keep it simple and stupid.

Make sure to spend some time at the man pages for fork() and wait().

Good luck!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.