Saturday, April 6, 2013

Max Finder program

With the MaxFinder program, you can find a maximum number in a list of your numbers.
You can have a large list of numbers as you want. In this program, you will learn to use an array to store a collection of numbers. So the array in this program is the list of numbers.

MaxFinder source code:

1 import java.util.Scanner;
2 class MaxFinder{
 
3   public static void main(String[] args){
   
4 Scanner sc=new Scanner(System.in);
5 int n;
6 int i;
7 int max;
System.out.print("How many numbers in your list? ");
8 n=sc.nextInt();
9 Integer[] ls=new Integer[n];
10   for(i=0;i<n;i++)
{
System.out.format("Enter number %d:",i+1);
ls[i]=sc.nextInt();
}
11 max=ls[0];
12 for(i=1;i<n;i++){
if(max<ls[i]) max=ls[i];
}

13   System.out.format("The maximum number in the list is %d.\n", max);
14     }  

15}

Program Output
Java Max Finder program

Code Explanation: 
1 Include Scanner class in the program so that  you can use its nextInt method to receive input from keyboard.
2 Open MaxFinder class block.
3 Open the main method block.
4 Create Scanner object sc.
5 Declare local variable n to store the number of list items.
6 Declare local variable i to be used in for loop iteration.
7 Declare local variable max to store the maximum number in the list.
8 Receive the number of list items input form keyboards.
9 Create an array called ls to store n items.
10 Use a for loop to receive assign a value input from keyboard to every list item.
11 Let the variable max take the first item of the list.
12 The max (the first item) is compared to the next item of the list. If it is less than the next item, update the max by letting it take the next item. The comparison process repeats until every item of the list is examined.
13 Display the maximum number on the screen.
14 Close the main method block.
15 Close the MaxFinder class block.

1 comment: