Java Program to Calculate Percentage of Secured Mark

bookmark

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        //Scanner class object created
        Scanner sc = new Scanner(System.in);
        //ask user to total number of subjects
        System.out.print("Enter number of subjects: ");
        int num_subs = sc.nextInt();
        //inetger array 'marks' declared to hold the marks of subjects
        int[] marks = new int[num_subs];
        //ask user to enter full marks per subject
        System.out.print("Enter full marks per subject: ");
        int fullMarks = sc.nextInt();
        
        //ask user to enter marks for each subject
        System.out.println("Enter your marks: ");
        //using for loop taking input of marks for each subject
        for (int i = 0; i < num_subs; i++) 
        {
            marks[i] = sc.nextInt();
            // exit loop if user enters invalid marks
            if (marks[i] > fullMarks) 
            {
                System.out.println("Invalid marks");
                System.exit(0);
            }
        }
        
        //find total secured mark by calling sum() method 
        //and store in double variable 'total'
        //'marks' integer array passed as parameter
        double total=(double) sum(marks);
        
        //call findPercentage() method to find percentage
        //'total' mark, number of subjects and fullMarks are passed as parameter
        findPercentage(total, num_subs, fullMarks);
    }
    
    //user defined method findPercentage() to calculate percentage
    public static void findPercentage(double total, int num_subs, int fullMarks)
    {
        // calculate percentage
        double percentage = total / ((double) num_subs * fullMarks) * 100;
        // display percentage
        System.out.println("Your percentage is " + percentage + "%");
    }
    
    //user defined method sum() to find sum of total secured mark
    public static int sum(int[] arr) 
    {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) 
        {
            sum += arr[i];
        }
        return sum;
    }
}

 


Output:

Enter number of subjects: 6
Enter full marks per subject: 100
Enter your marks: 
86
92
78
89
72
85
Your percentage is 83.66666666666667%