Question 1- Write a Java program to find the average marks of students in class for BCSL-043 40 assignments. Make necessary provision for exceptions handling in your program.
Solution -
import java.util.Scanner;
public class average
{
public static void main(String[] args) {
int [] marks = new int[20];
int average;
Scanner sc = new Scanner(System.in);
System.out.println("Enter 20 students marks");
try
{
int i,sum=0;
for (i=0; i<20;i++)
{
marks[i] = sc.nextInt();
if(marks[i] < 0)
throw new Exception("negative marks");
sum +=marks[i];
}
System.out.println("Average marks of 20 students is: "+sum/20);
}
catch(Exception e)
{
System.out.println("Marks can not be negative");
}
}
}
FileName: average.java
To execute the file first go to that directory where this file is saved. than complie the file usign this command : javac average.java
To run the file type this command: java average
Output:
Enter 20 students marks
12 23 53 64 23 54 65 45 65 86 46 86 23 64 34 64 65 86 45 23
Average marks of 20 students is: 51
12 23 53 64 23 54 65 45 65 86 46 86 23 64 34 64 65 86 45 23
Average marks of 20 students is: 51
Enter 20 students marks
23 45 -10
Marks can not be negative
23 45 -10
Marks can not be negative
if you have any doubt related to this post, you can ask in comment section and if you want solution of any previous year questions. please post that question in section we will try to solve that
0 comments:
Post a Comment