Author Topic: Java - Smallest and Biggest number and positions for N numbers  (Read 1471 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
Java - Smallest and Biggest number and positions for N numbers
« on: December 02, 2011, 02:19:52 pm »
Can you give us the program in Java to find the smallest and biggest number and its positions for a given set of N numbers?

Here is the Java code:

Code: (Java)
//Source Code Listing


import java.lang.*;
import java.util.*;
import java.io.*;
 
 
class SmallBig
{
      public static String ReadString()
      {
           try
           {
                 InputStreamReader input = new InputStreamReader(System.in);
                 BufferedReader reader = new BufferedReader(input);
                 return reader.readLine();
           }
           catch (Exception e)
           {

                 e.printStackTrace();
                 return "";
           }
      }


      public static int ReadInteger()
      {
           try
           {
                 InputStreamReader input = new InputStreamReader(System.in);
                 BufferedReader reader = new BufferedReader(input);
                 return Integer.parseInt(reader.readLine());
           }
           catch (Exception e)
           {

                 e.printStackTrace();
                 return 0;
           }
      }
      
      
 
      public static void main(String[] args)
      {      
         System.out.println("Enter the total numbers:");
         int n = ReadInteger();
         int[] arrNumbers = new int[n];

         for (int i = 0; i < n; i++)
         {
            System.out.format("Enter %d No.: ", i + 1);
            arrNumbers[i] = ReadInteger();
         }
         
         int smallest = arrNumbers[0];
         int biggest = arrNumbers[0];
         int smallpos = 0;
         int bigpos = 0;
         for (int i = 0; i < n; i++)
         {
            if (smallest > arrNumbers[i])
            {
               smallest = arrNumbers[i];
               smallpos = i;
            }
            if (biggest < arrNumbers[i])
            {
               biggest = arrNumbers[i];
               bigpos = i;
            }
         }

         System.out.println();
         System.out.format("Smallest Number: %4d Position: %d\n", smallest, smallpos);
         System.out.format("Biggest  Number: %4d Position: %d\n", biggest, bigpos);
      }
}


/***
Sample Output:

Enter the total numbers:5
Enter 1 No.: 1
Enter 2 No.: 11
Enter 3 No.: 111
Enter 4 No.: 1111
Enter 5 No.: -111

Smallest Number: -111 Position: 4
Biggest  Number: 1111 Position: 3
Press any key to continue . . .

***/

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1