Shiv_k Shiv_k - 4 years ago 74
Java Question

Why the output is 0 instead for a[0] instead of -1?

I am new to java array,want to calculate small element in an array when array contains negative elements.

class test_array {
//test_array class

public static void main(String args[])
{
int[] a={4,2,99,9,-1,0};
int small=a[0];

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

System.out.println(a[0]);
}
}

Answer Source
int small = a[0];

here you gave 4 to small

you didn't change this value if you find a smaller one. Instead of that you are changing smaller one into this value by

a[i] = small;

this code and small value doesn't change at all. Your 'small' value is always 4.

when it compares a[5] and small (it means 0 and 4) it passes if statement and makes a[0]=a[5] ( gives it '0').

You are comparing only with first char of array with this algoryhtm but you need to compare it with a dynamic "small" value. Change code like that.

class test_array {
//test_array class  

    public static void main(String args[])
    {
            int[] a={4,2,99,9,-1,0};           
            int small=a[0];

        for (int i=1;i<a.length;i++)               
        {                                      
            if(a[i]<small)
            {                                             
                small=a[i];
            } 
        }

        System.out.println(small);       
    }   
}       

Choose first array element as small, then compare. If there is any smaller value, give this value to 'small'. Do it in a loop for all array and find smallest value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download