Andreea Alistar
Andreea Alistar

Reputation: 101

Finding the minimum in an array

I have some problems with this code:

import java.util.*;

public class Function{
    public static void main(String[] Problem) {
        int i, continut, minim = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Type the maximum number of element:");
        continut = in.nextInt();
        int array[] = new int[continut];
        for (i = 0; i < continut; i++) {
            array[i] = in.nextInt();
        }

        for (i = 0; i < continut; i++) {
            if (array[i] < minim) {
                minim = array[i];
            }
        }

        System.out.print(minim);
    }
}

I don't understand why after I run this program the output always gives me minim=0.

Upvotes: 0

Views: 74

Answers (5)

Pranay Saha
Pranay Saha

Reputation: 298

You have to store the first value of your array as minim. Then you have to check that value against the others, if other values are smaller than minim then replace that minim with that number.

You can do that by adding

minim = array[0];

before your code

Upvotes: -1

janos
janos

Reputation: 124804

Assign the first input to minim, and iterate from the 2nd to compare against minim and update:

int minim = array[0];
for (i = 1; i < array.length; i++) {
    if (array[i] < minim) {
        minim = array[i];
    }
}

However, this requires that there are at least one elements. In fact if there are no elements, finding the minimum doesn't make sense. So it's good to add input validation:

while (true) {
    System.out.println("Type the maximum number of element:");
    continut = in.nextInt();
    if (contitut > 0) {
        break;
    }
    System.out.println("Invalid input: please enter an integer > 0");
}

Upvotes: 0

sadia zar
sadia zar

Reputation: 62

Instead of 0 you can initialize it with the first element of array like

minim=array[0];

Now you can easily check minimum from that array!

Upvotes: 0

Yassin Hajaj
Yassin Hajaj

Reputation: 21995

minim=Integer.MAX_VALUE

Instead of 0 should do the work. This way, youre pretty much sure the first value testes is below minim.

Upvotes: 1

Pshemo
Pshemo

Reputation: 124275

Your current minim is set to 0 and you are probably providing bigger numbers which means that minimum will never be replaced by any smaller number.

To avoid this problem you can initialize minim with

  1. first value from user,
  2. maximal possible integer minim = Integer.MAX_VALUE.

Upvotes: 3

Related Questions