1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

JAVA simple array problem

  1. Oct 10, 2007 #1
    Q1. Write a function that accepts an array of integers and returns the second largest integer in the array. Return -1 if there is no second largest.

    The signature of the function is

    public class ID
    {
    public static void main(String[] args){ }
    int f(int[ ] a) { }

    }

    Examples:

    if the input array is {1, 2, 3, 4} then return 3
    if the input array is {{4, 1, 2, 3}} then return 3
    if the input array is {1, 1, 2, 2} then return 1
    if the input array is {1, 1} then return -1
    if the input array is {1} then return -1
    if the input array is {} then return -1
     
    Last edited: Oct 10, 2007
  2. jcsd
  3. Oct 10, 2007 #2
    Ok, you have the signature, what about the actual code?

    The examples you've given doesn't demonstrate you've attempted the program. Anyone can pick the second largest number in a set. Please show us some code.
     
  4. Feb 18, 2009 #3
    public static void main(String[] args) {
    // TODO code application logic here

    int secondlargest= -1;
    int largest = -1;

    int number[] ={4, 1, 2, 3};

    for (int i=0;i < number.length;i++)
    {

    if(largest < number )
    {
    secondlargest = largest;
    largest = number;
    }

    if(secondlargest < number && largest != number )
    secondlargest = number;

    }

    System.out.println(secondlargest);
    //System.out.println(largest);
    // System.out.println(objhwa.data); // Display the string.


    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: JAVA simple array problem
  1. Arrays in Java (Replies: 3)

  2. Java class Arrays (Replies: 1)

Loading...