Search code examples
javaarraysfor-loopintegerbluej

Writing a program to find smallest and largest number in a random array. Logic of the program is correct, but not executing properly. What's the fix?


Here is the program:

import java.util.Scanner;
class NumbersInArray
{
    public static void main()
    {
        System.out.println("\f");
        Scanner sc = new Scanner(System.in);
        int a[] = new int[10];
        int ll = 0;
        int sl = 0;
        int currentMax1 = 0;
        int currentMax2 = 0;
        System.out.println("Enter 10 random numbers");
        for (int i = 0; i <= 9; i++)
        {
            a[i] = sc.nextInt();
        }
        for (int i = 0; i <= 9; i++)
        {
            currentMax1 = Math.max(a[i],currentMax1);
            ll = currentMax1;
        }
        System.out.println("The largest number is "+ll);
        for (int j = 0; j <= 9; j++)
        {
            currentMax2 = Math.min(a[j],currentMax2);
            sl = currentMax2;
        }
        System.out.println("The smallest number is "+sl);
    }
}

In this program, the user enters 10 random numbers into an integer array. The from this array, the smallest and largest numbers are picked out and printed. I have written this program in a suitable manner in a way that should give the proper output. But instead, the program doesn't work though it compiles. What changes do I make to get it to work?

This is the output I am getting: Current output

Ideally, it should say the minimum number is 109, but it instead says 0. I understand why. It's because the value of currentMax2 is 0. But how do I make it recognise the smallest number in the array?


Solution

  • The problem is that you are setting the currentMax1 e currentMax2 to a value chosen by you. The same problem would occur in the case that you set the currentMax1 to a bigger number than all the ones that you set in input.

    you would have 0 and the number set up by you.

    To resolve this problem, since you can't set a number yuorself (because you can't guess which numbers will be given in input), then you start by the first number that the user gives.

    There are many ways to do this, so i won't provide any code (and since this seems like an exercise).

    Try to think of a way of getting a value of the one in input as a starting point and then what to do since you got one already.

    This should get you to the resolution of the problem ;)