Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem 4. Write a Java program using fork() to compute average of N numbers. Th

ID: 3542890 • Letter: P

Question

                    Problem 4.                                                       Write a Java program using fork() to compute average of N numbers. The parent                                                       process forks a child process that takes input from the user, adds all the numbers
                    and returns the sum and the count of numbers to the parent process that divides the sum
                    by the count of the number, and prints out the average.                                      Problem 4.                                      Write a Java program using fork() to compute average of N numbers. The parent                                      process forks a child process that takes input from the user, adds all the numbers
                    and returns the sum and the count of numbers to the parent process that divides the sum
                    by the count of the number, and prints out the average.                 

Explanation / Answer


import java.util.Scanner;
    import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
   
    public class Sum extends RecursiveTask<Integer> {
   
   
    private final int num;
   
    public Sum(int num) {
        this.num=num;
    }
   
   
    @Override
    protected Integer compute() {
        int sum=0;
       for(int i=1;i<=num;i++){sum+=i;}
        return sum;
    }
   
   
   
    public static void main(String[] args) {
        // create a random data set
        System.out.println("enter n : ");
        Scanner in=new Scanner(System.in);
        int temp=in.nextInt();
       
       
   
        // submit the task to the pool
       final ForkJoinPool pool = new ForkJoinPool(4);
        final Sum finder = new Sum(temp);
        System.out.println( "the average is : "+pool.invoke(finder)/(double)temp);
       
    }
    }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote