In the following question, we are supposed to enter N elements in a dynamic array of size n. After entering into the array, we’ll have to find and print the maximum and minimum element present in the array.

The standard algorithm will be:

  1. Enter the size of array and create an array of the input size, say N.
  2. Using a loop construct, enter integer inputs in the array.
  3. Declare 2 variables that are going to store the minimum and maximum elements respectively.
  4. Initialize them with the element that is at the first index of the array.
  5. Using another loop construct, compare each element with the MAX and MIN.
  6. Keep swapping along.
  7. After the loop terminates, print the result accordingly.

Source Code:

/* Program to enter an array and find the maximum and minimum number */

import java.util.*;
class ArrMinMax
{
public static void main()
{
Scanner inp=new Scanner(System.in);
System.out.print("\n Enter Size of Array: ");
int n=inp.nextInt();
int i,sum=0;
int arr[]=new int[n];   //Creating N-size Array

for(i=0;i<n;i++)   //Entering N numbers in array
{
System.out.print("\n Enter: ");
arr[i]=inp.nextInt();
}

int max=arr[0],min=arr[0];  //Initializing with first element.

for(i=0;i<n;i++)
{
if(arr[i]>max)   //Checking Maximum element
 max=arr[i];

if(arr[i]<min)  //Checking Minimum element
 min=arr[i];
 
}
  
//Printing Result
System.out.println("\n Maximum Number: "+max);
System.out.println("\n Minimum Number: "+min);

}
}

Output:

Enter Size of Array: 6

 Enter: 12

 Enter: 36

 Enter: 5

 Enter: 41

 Enter: 20

 Enter: 36

 Maximum Number: 41
 Minimum Number: 5

 

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019