Modify the LargestInArray.java program in Section 7.3 (page 325) so that the program can (40 points) Mark both the smallest and largest elements; (60 points) Compute and print the alternating sum of all input values. For example, if your program reads the input 1 4 9 16 9 7 4 9 11, then it computes 1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = -2

Respuesta :

Answer:

The Java code is given below

Explanation:

import java.util.*;

public class AlternatingSum

{

  public static void main(String[] args)

  {

      Scanner sc = new Scanner(System.in);

      String line = sc.nextLine();

      String[] nums = line.split(" ");

      int[] intArray = new int[nums.length];

      for(int i=0;i<nums.length;i++)

      {

          intArray[i] = Integer.parseInt(nums[i]);

      }

      alternatingSum(intArray);

     

  }

  public static void alternatingSum(int[] array)

  {

      int sum = 0;

      for(int i=0;i<array.length;i++)

      {

          if(i%2 == 0)

          {

              sum+= array[i];

              if(i!=0)

              System.out.print(" + "+array[i]);

              else

                  System.out.print(array[i]);

          }

          else

          {

              sum -= array[i];

              System.out.print(" - "+array[i]);

          }

      }

      System.out.println(" = "+sum);

  }

}

RELAXING NOICE
Relax