Create a java program that asks the user how many students they have in a classr
ID: 3740309 • Letter: C
Question
Create a java program that asks the user how many students they have in a classroom. Then, using a while loop, which asks the user to enter the grades (out of 100) for all students in the classroom, one at a time. Finally, the program should calculate the sum and average of the grades and print it out.
Sample Run1
Enter number of students: 3
Enter mark for student 1: 56
Enter mark for student 2: 45
Enter mark for student 3: 66
Output1: Sum = 167 and Average = 55.67
Sample Run2
Enter number of students: 6
Enter mark for student 1: 86
Enter mark for student 2: 15
Enter mark for student 3: 69
Enter mark for student 4: 77
Enter mark for student 5: 45
Enter mark for student 6: 90
Output2: Sum = 382 and Average = 63.67
P.S: Solutions for Both sample run in one Program.
Explanation / Answer
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
// taking user input of number of students
System.out.print("Enter number of students: ");
int n = sc.nextInt();
int total = 0;
// taking user input of marks
for(int i=1; i<=n; i++)
{
System.out.printf("Enter mark for student %d: ",i);
int num = sc.nextInt();
// adding marks to the total
total = total + num;
}
// printing output
System.out.printf("Sum = %d and Average = %.2f",total, total/(float)n);
}
}
/*SAMPLE OUTPUT - 1
Enter number of students: 3
Enter mark for student 1: 56
Enter mark for student 2: 45
Enter mark for student 3: 66
Sum = 167 and Average = 55.67
SAMPLE OUTPUT - 2
Enter number of students: 6
Enter mark for student 1: 86
Enter mark for student 2: 15
Enter mark for student 3: 69
Enter mark for student 4: 77
Enter mark for student 5: 45
Enter mark for student 6: 90
Sum = 382 and Average = 63.67
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.