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);
}
}
}