Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Determining the smallest number in an array

I created an array and now I need to determine the smallest element out of the array. I successfully determined the largest number but Im having a lot of trouble with the smallest number. To find the largest array element, I simply initialized largest to sales[1]. I tried repeating this method for the smallest but anytime I do I seem to be getting either zero or the largest element again.

Here is my code:

// ****************************************************************
// Sales.java
//
// Reads in and stores sales for each of 5 salespeople. Displays
// sales entered by salesperson id and total sales for all salespeople.
//
// ****************************************************************
import java.util.Scanner;

public class Sales
{
public static void main(String[] args)
{
int SALESPEOPLE;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number of sales person(s): ");
SALESPEOPLE = scan.nextInt();

double[] sales = new double[(SALESPEOPLE)+1];
double sum;
double largest = sales[1];
double smallest = sales[1];
int GreatSalesperson=0;
int badSalesperson=0;

for (int i=1; i<sales.length; i++)
{

System.out.print("Enter sales for salesperson " + i + ": ");
sales[i] = scan.nextDouble();

if (sales[i]>largest)
{
largest = sales[i];
GreatSalesperson = i;
}

if (sales[i]<smallest)
{
smallest = sales[i];
}
}


/*for (int i=1; i<sales.length; i++)
{

if (sales[i]>sales[1])
largest = sales[i];
}*/

System.out.println("\nSalesperson Sales");
System.out.println("-------");
sum = 0;
for (int i=1; i<sales.length; i++)
{
System.out.println(" " + i + " " + sales[i]);
sum += sales[i];
}

System.out.println("\nTotal sales: " + sum);
System.out.println("Salesperson " + GreatSalesperson + " made the most money: " + largest + " CONGRATULATIONS!" );

System.out.println("The smallest: " + badSalesperson + " made the least money: " + smallest + "Try Harder!" );

}
}
[2636 byte] By [leospyder] at [2007-11-11 8:27:25]
# 1 Re: Determining the smallest number in an array
The best way to make these things work is set "smallest" to be larger than the largest possible value ( such as 10000000 or +infinity) and set "largest" to be a value smaller than the smallest possible value (such as -1 if all values are going to be positive ..., are -infinity if negative values are possible). Then you will, for sure, have something smaller/larger ...
nspils at 2007-11-11 22:35:27 >
# 2 Re: Determining the smallest number in an array
there is a bug in the code:
if (sales[i]>largest)
{
largest = sales[i];
GreatSalesperson = i;
}

if (sales[i]<smallest)
{
smallest = sales[i];
}
}
you set GreatSalesperson, but not badSalesperson
graviton at 2007-11-11 22:36:21 >