i am getting errors printing numbers in reverse and not to sureabout finding the
ID: 3618642 • Letter: I
Question
i am getting errors printing numbers in reverse and not to sureabout finding the smallest and largest number in the arrayimport java.util.Scanner;
public class Main
{
/**
* @param args the command linearguments
*/
public static void main(String[] args) {
// TODO code applicationlogic here}
Scanner input= newScanner (System.in);
// declare an array forten number
int[]arr=newint[10];
int average=0;
int sum=0;
for (int i=0;i<10; i++)
{
System.out.println("enter a number");
int num= input.nextInt();
arr[i]= num;
}
print (arr);
int ans = (average (arr));
System.out.printf ("the average is"+ ans);
}
// fill array with tennumbers
public static void print(int [] num)
{
for (int i=num.length; i>0; i++)
{
System.out.println (num[i]);
}
}
public static int average (int [] num)
{
int sum=0;
int average=0;
for (int i =0; i<num.length;i++)
{
sum= sum+num[i];
average= sum/10;
}
return average;
}
}
Explanation / Answer
/** The problem with your print function was your for statement: for (int i=num.length; i>0; i++) You initially set int i to begin iterating from index 10 of the'num' array. But since 'num' only has 10 elements, thus only has indexes from0-9. That's why you get the out of bounds error. To fix this, just change it to: i = num.length - 1; Then the other error was that i++ should be i--. So the print function now looks like this: public static void print(int[] num) { for (int i = num.length- 1; i > 0; i--) { System.out.println(num[i]); } } I've also added a simple min max finder function. It just iterates through the 'num' array and returns a 2 elementarray, the 1st element is the min, the 2nd is the max. hope this helps. PM me if you have any questions :) **/ import java.util.Scanner; public class Main { /** * @param args the command linearguments */ public static void main(String[] args) { // TODO code applicationlogic here} Scanner input = newScanner(System.in); // declare an array forten number int[] arr = newint[10]; int average = 0; int sum = 0; for (int i = 0; i 0; i--) { System.out.println(num[i]); } } /************* min-max finder method **************/ public static int[] minmax(int[] num) { int min = num[0]; int max = num[0]; for (int i = 0; i max) { max = num[i]; } if (num[i]Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.