Search code examples
javabluej

Need help trying to understand what this for loop does and how it works


I do not understand how the for loop works and what it is doing. The code is for a project that averages a users test scores and is based on how many test scores he wants to input.

I know that the program is returning as many inputs the user asks but I do not know how the for loop is doing that. I am trying to understand how it operates and what it is doing.

import java.util.Scanner;
public class average
{
     public static String getLetterGrade(double average) {
    if (average < 60) {
        return "F";
    } else if (average < 70) {
        return "D";
    } else if (average < 80) {
        return "C";
    } else if (average < 90){
        return "B";
    }
     else;{
        return "A";
    }
}
   public static void main(String[] args){
   Scanner scan = new Scanner(System.in);
   System.out.println("Welcome, please type your first name. ");
   String name = scan.nextLine();
   System.out.println("Welcome, please type your last name. ");
   String last = scan.nextLine();
   int n;
   System.out.println("How many tests would you like the average of?");
   n = scan.nextInt();

        while(n<0)
        {
            System.out.println("Invalid input.");
            System.out.println("How many tests would you like the average 
            of?");
            n = scan.nextInt();
        }
   double sum = 0, grade;
   System.out.println("Enter " + n + " scores.");

   for(int i = 0;i<n;i++)
   {
    grade = scan.nextDouble();
    sum += grade;
    }

   double average = (sum/n);
   System.out.println("Okay " + name.charAt(0) + last.charAt(0) + ", Your 
   average score is " + (average));
   System.out.println("Your letter grade is " + getLetterGrade(average));

}

}

The program runs normally and does not have errors. I am trying to understand how the for loop is working.


Solution

  • the for loop is trying to get the numbers(scores) which we want to calculate average on them. for loop runs for n times which is the number of inputs (user gives this number as input). in its body, it calls scan.nextDouble to get the nex number from the console. then adds this number to sum.