Reputation: 33
I'm just a beginner in Java. Can someone please tell me how to arrange this program. In this program I want to store 10 marks in an array, and then output the ones that are equal to or greater than the average. Help would be appreciated.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
}
sum = sum + mark[c];
int average = sum / 10;
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}
Upvotes: 0
Views: 144
Reputation: 54742
Just some modification in your code.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++){
if(mark[c]>=average)
System.out.print(mark[c]);
}
}
Explanation
Upvotes: 1
Reputation: 69035
sum = sum + mark[c];
statement must be inside your loop.
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++)
{
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++)
{
if(mark[c]>=average)
{
System.out.print(mark[c]);
}
}
}
Upvotes: 1
Reputation: 21
public class aver{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
int average;
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
}
for(int c = 0; c < 10; c++){
sum = sum + mark[c];
}
average = sum / 10;
for(int c = 0; c < 10; c++){
if(mark[c]>=average){
System.out.println(mark[c]);
}
}
}
}
Upvotes: 1
Reputation: 68715
You need to add another for
loop to iterate your array after calculating the average. Here is the updated code with the required for
loop:
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
for(int c = 0; c < 10; c++) {
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
for(int c = 0; c < 10; c++) {
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}
Upvotes: 1
Reputation: 13446
You need loop the array twice. The first iteration sums all the elements and computes the average. And the other iteration outputs the elements that meet your constraints.
The code is below:
public class ClassAverage{
public static void main (String Args []){
int sum = 0;
int mark[] = new int [10];
// The first iteration sums all elements
for(int c = 0; c < 10; c++){
System.out.print("Enter a mark: ");
mark[c] = Keyboard.readInt();
sum = sum + mark[c];
}
int average = sum / 10;
// This iteration outputs elements that meet your requirements.
for(int c = 0; c < 10; c++){
if(mark[c]>=average){
System.out.print(mark[c]);
}
}
}
}
Upvotes: 3