English

Fill an array (type int, size n). Print the max and the elements min and their position.

Advertisements
Advertisements

Question

Fill an array (type int, size n).

Print the max and the elements min and their position.

Code Writing
Advertisements

Solution

import java.util.*;
class clArrays
{
    public void main()
    {
        Scanner sc = new Scanner(System.in);        
        System.out.print("Enter the array size : ");
        int n = sc.nextInt();        
        int R[] = new int[n];
        int j = 0;        
        System.out.print(" Enter the elements : \n");
        for(j = 0; j < n; j++)
        {
            System.out.print("Enter value for cell number " + j + " : ");
            R[j] = sc.nextInt();
        }        
        int min = R[0], minp = 0;
        for(j = 1; j < n; j++)
        {
            if(min > R[j])
            {
                min = R[j];
                minp = j;
            }
        }        
        int max = R[0], maxp = 0;
        for(j = 1; j < n; j++)
        {
            if(max < R[j])
            {
                max = R[j];
                maxp = j;
            }
        }        
        System.out.println(" Largest Element is : " + max + " at position " + maxp);
        System.out.println(" Smallest Element is : " + min + " at position " + minp);
    }
}

Output:

Enter the array size: 8

Enter the elements :

Enter value for cell number 0 : 55

Enter value for cell number 1: 66

Enter value for cell number 2 : 44 

Enter value for cell number 3 : 22 

Enter value for cell number 4 : 88 

Enter value for cell number 5 : 11 

Enter value for cell number 6 : 99 

Enter value for cell number 7 : 77 

Largest Element is : 99 at position 6

Smallest Element is : 11 at position 5

shaalaa.com
  Is there an error in this question or solution?
Chapter 11: Programs Overall - Arrays [Page 252]

APPEARS IN

Rupa Pandit Computer Applications [English] Class 10 ICSE
Chapter 11 Programs Overall
Arrays | Q 6. | Page 252
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×