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

Write a program that reads a sequence of integers into an array and that compute

ID: 3769399 • Letter: W

Question

Write a program that reads a sequence of integers into an array and that computes the alternating sum of all elements in the array.

For example, if the program is executed with the input data: 2 1 4 9 16 9 7 4 9 11 Then it computes 2 - 1 + 4 - 9 + 16 - 9 + 7 - 4 + 9 – 11 = 4

Use a scanner object to gather the inputs from the user. Remember that you will not know how many numbers the user will input each time the program is run. Check out our book’s info on partially filled arrays, or my part of the class java program on the Declaration of Independence.

Explanation / Answer

import java.util.*;
class Sum{
   public static int sumAlternate(int a[],int size){
       int sum = 0;
       for(int i = 0; i < size; i++){
           sum += a[i]*Math.pow(-1,i);
       }
       return sum;
   }
   public static void main(String args[]){
       Scanner in = new Scanner(System.in);
       int n = in.nextInt();
       int[] a = new int[n];
       for(int i =0; i < n; i++)
           a[i] = in.nextInt();
       System.out.println("Sum: "+ sumAlternate(a,n));
   }
}