-9

Question is : Take 10 integers from keyboard using loop and print their average value on the screen.

how can I get average while using for loop in java

Here is what I have tried:

Scanner sc = new Scanner(System.in); 
int sum = 1; 
for (int i=1; i<=10; i++ ) { 
    System.out.println("Enter number "); 
    sum = sum + sc.nextInt(); 
    int avg = sum/10; 
}
System.out.println("sum is "+ sum); 
System.out.println("Avg is : "+ avg);
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
  • 2
    You're on the right track. But: 1) why does `sum` start from 1? Doesn't it make more sense to start from **zero**? 2) No need to compute `avg` on every trip through the loop; just once _after_ the loop is fine, and avoids an issue of **scope** with the `avg` varaible. – Kevin Anderson Mar 06 '21 at 09:33
  • Does this code even compiles? – CyberMafia Mar 06 '21 at 09:53

1 Answers1

-1

here is the full code and comments for you in case you don't understand the code


/**
 * This class is built and tested in java version 15.0.2
 * @since 15.0.2
 */
public class AverageDemo {
    public static void main(String[] args) {
        //Array size. you can change this size whatever you want
        //for the array
        int size = 10;
        //Declare a integer number array. You can also use List<Integer>
        int[] num = new int[size];
        System.out.println("Insert 10 integer numbers:");
        //use Scanner class for better data input. Make sure it imported in java.util.Scanner
        Scanner scanner = new Scanner(System.in);

        //start a loop for insert the numbers
        //the array will start counting from num[0] -> num[size - 1] so condition i <= size will
        //throws a exception
        for (int i = 0; i < size; i++) {
            System.out.print("num["+i+"]=");
            num[i] = scanner.nextInt();
        }

        //If you want to test whether the array is fully inserted.
        //Remove these commented lines
        
        // for (int i = 0; i < size; i++) {
        //    System.out.println(num[i]);
        // }
        
        System.out.println(average(num, size));
        
    }
    
    //Helper method for average calculating
    //the rule is average equals total of all integer numbers divides with how much numbers in numbers list
    
    private static double average(int[] num, int size) {
        int total = 0;
        for (int i = 0; i < size; i++) {
            total += num[i];
        }
        
        return (double)total / size;
    }
}
KhanhPham
  • 1
  • 1