简体   繁体   中英

Sum of alternate elements of integer array

Yes, the problem seems rather easy. I was asked to write a small piece of code (Java) that finds out the sum and average of alternate elements of integer array. The starting position will be given by the user. For example, if the user inputs 3 as the starting position, the sum module will start from index (3-1= 2). My objective is to not complete my homework or stuff, but to learn why my code is not working. So if anyone could point out please and suggest fixes? Here's the code:

import java.util.Scanner;
public class Program {

static int ar[]; static int sum = 0; static double avg = 0.0;
static Scanner sc = new Scanner(System.in);
public Program(int s){
    ar = new int[s];
}
void accept(){
    for (int i = 0; i<ar.length; i++){
        System.out.println("Enter value of ar["+i+"] : ");
        ar[i] = sc.nextInt();
    }
}
void calc(int pos){
    for (int i = (pos-1); i<ar.length; i+=2){
        sum = ar[i] + ar[i+1];
    }
}
public static void main(String[] args){
    boolean run = true;
    while (run){
    System.out.println("Enter the size of the array: ");
    int size = sc.nextInt(); 
    Program a = new Program(size);
    a.accept(); 
    System.out.println("Enter starting position: "); int pos = sc.nextInt(); //Accept position
    if (pos<0 || pos>ar.length){
        System.out.println("ERROR: Restart operations");
        run = true;
    }
    a.calc(pos); //Index = pos - 1; 
    run = false; avg = sum/ar.length;
    System.out.println("The sum of alternate elements is: " + sum + "\n and their average is: " + avg); 

   }
 }
}

In your calc method, you got the for loop definition right (ie the initial value, the condition and the increment are all correct), but inside the loop, the sum calculation is wrong. In each iteration, you should add the current element - ar[i] - to the total sum :

for (int i = (pos-1); i<ar.length; i+=2){
    sum = sum + ar[i]; // or sum += ar[i];
}

You also have an error in the average calculation :

avg = sum/ar.length;

This would only be correct if the average is on all elements. Since the average is on half the elements, you shouldn't divide by ar.length .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM