Can someone please help me. I’m having a hard time on fixing the logic of my codes. this program is supposed to compute the average of a numbers entered by the user assuming that the size of the array is set to 100 and if User enters -99, program will be terminated
i know the problem is within the while loop processing
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int ctr=0, sum=0, ave = 0;
while(num[ctr]!= -99)
{
System.out.print("Enter number: ");
num[ctr]= input.nextInt();
sum += num[ctr];
ctr++;
}
System.out.print("Numbers are " );
for(int x = 0; x<ctr; x++)
{
System.out.print(num[x] + " ");
}
ave = sum / (ctr-1);
System.out.println("Average is " + ave);
}
}
You should read the first input outside the while
whileloop. Because when the user enters-99, inside the loop you incrementctrso the check will be on the wrong number. So actually you are never checking the current number you wanted to check.But you need to handle the case which the user only enters one number, in this case you’re dividing by zero, and you’re getting the wrong average. You should also do:
instead of:
Now you’ll get good results.