package com.company;
import java.util.*;
public class Main {
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i <= 5; i ) {
if (array[i] > largest) {
array[i] = largest;
}
System.out.println(largest);
}
return largest;
}
public static void main(String[] args) {
// write your code here
Scanner sc = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i <= 5; i ) {
array[i] = sc.nextInt();
System.out.println(array[i]);
}
Largest(array);
System.out.println("largest element is : " Largest(array));
}
}
This is the code to find the largest no. in an array but the output I'm getting for this code isn't desirable. Please check and let me know the problems in this code.
CodePudding user response:
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
//for (int i = 0; i <= 5; i ) {
//wrong loop range
for (int i = 0; i < array.length; i ) {
if (array[i] > largest) {
//array[i] = largest;
//wrong assignment
largest = array[i];
}
System.out.println(largest);
}
return largest;
}
CodePudding user response:
Try like this :
package com.company;
import java.util.*;
public class Main {
public static int Largest(int array[]) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 5; i ) {
if (array[i] > largest) {
largest = array[i];
}
System.out.println(largest);
}
return largest;
}
public static void main(String[] args) {
// write your code here
Scanner sc = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i < 5; i ) {
array[i] = sc.nextInt();
System.out.println(array[i]);
}
Largest(array);
System.out.println("largest element is : " Largest(array));
}
}
You are wrong on two thing :
the loops on your array go until index = 5, however your array has a length of 5, so the last index is 4.
you were assigning array[i] = largest instead of largest = array[i]