Manipulating an Array in Java (For beginners)

Problem:

Write a program where:
a) The user input the length of an array N. Then create an array of size N.
b) Fill the array with N integers that are the grades of a class of students.
c) Calculate the average of the class using a method called average()
d) Print all the values of the array, the maximum, the minimum, and the average

Output:

Not applicable

Solution:

import java.util.Scanner;

public class Prob1 {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the number of the grades you will enter: ");
int num = scan.nextInt();
int[] grades = new int[num];

for(int i=0; i<num; i++)
{
System.out.print("Enter the grade #" + (i+1) + ": ");
grades[i] = scan.nextInt();
}

PrintArray(grades);
System.out.println("Maximum is " + CalcMax(grades));
System.out.println("Minimum is " + CalcMin(grades));
System.out.println("The average is " + CalcAverage(grades));
}

public static double CalcAverage(int grades[])
{

double output = 0;
for(int grade: grades)
{
output += grade;
}

return output/grades.length;
}

public static int CalcMax(int grades[])
{
int max = grades[0];

for(int grade: grades)
{
if (grade > max)
max = grade;
}

return max;
}

public static int CalcMin(int grades[])
{

int min = grades[0];

for(int grade: grades)
{
if (grade < min)
min = grade;
}

return min;
}

public static void PrintArray(int[] grades)
{
int k = 1;
System.out.println();

for(int grade: grades)
{
System.out.println("Garde #" + k + ": " + grade);
k++;
}
}
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact