Thread Closed

JAVA simple array problem

 
Share Thread Thread Tools
Oct10-07, 04:04 AM   #1
 
Smile

JAVA simple array problem


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
PhysOrg.com
PhysOrg
science news on PhysOrg.com

>> Ants and carnivorous plants conspire for mutualistic feeding
>> Forecast for Titan: Wild weather could be ahead
>> Researchers stitch defects into the world's thinnest semiconductor
Oct10-07, 06:58 AM   #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.
Feb18-09, 04:48 AM   #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[i] )
{
secondlargest = largest;
largest = number[i];
}

if(secondlargest < number[i] && largest != number[i] )
secondlargest = number[i];

}

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


}
Thread Closed
Thread Tools


Similar Threads for: JAVA simple array problem
Thread Forum Replies
[SOLVED] Simple Java Problem Programming & Comp Sci 2
Sorting an Array in Java Programming & Comp Sci 9
how do display/generate webpage content with info from an array in a .java file? Programming & Comp Sci 1
Simple array problem Programming & Comp Sci 10
converting from an array of function values to coordinate array of different length Programming & Comp Sci 3