Sunday, September 12, 2010

Maximum Number Solution

This program will compute the max from a given set of n numbers.
This program will run a finite number of times because the first loop will run n times to input all the numbers into the array, and the second loop will run a maximum of n-1 times to check every number.

The program should return the correct answer everytime, using simple logic to test it. For example, if in a given list of 5 numbers, the maximum happened to be the first number, then max will never be reassigned to any of the other 4 numbers. If the maximum is the second number, then it will perform the check and reassign the temporary max to the second number, and that variable would never be reassigned again. If the maximum is the third number, the variable would be reassigned to the third variable during the checks, and it would never be reassigned again.


import java.util.Scanner;

public class FindMax 
{

public static void main(String[] args) 
{

int i = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers are in the list that you want find the max from?");
int numberOfItems = scan.nextInt();
int[] list = new int[numberOfItems];
int numbersInput = numberOfItems;
while(numberOfItems > 0)
{
System.out.println("Enter a number.");
int aNumber = scan.nextInt();
list[i] = aNumber;
i++;
numberOfItems--;
}
int max = list[0]; 
//Sets the first number as the temporary maximum, will compare the rest of the numbers to the temporary max
for(int j = 1; j < numbersInput; j++)
{
if(list[j]>max)
{
max = list[j];
}
}
System.out.println("The maximum number is: " + max);
}

}

2 comments: