Search code examples
javaarraysloopsswap

how to get the last value of the array variable in loops


Here is my code:

class test {
  public static void main(String args[]) { 
    int a[]={5,8,9,7,3};
    int j;

    for(j=0;j<a.length-1;j++)
    {
        if(a[j]>a[j+1])
        {
            int temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
        }
        System.out.print(a[j]+"   "); // last value of array a[4] is not printed
    }
  }
}

This is one part of my program, here last value of the array is not printed?!

Can you help me anyone how to get the last value of array?


Solution

  • Simple: add another print statement after the loop; like:

     System.out.println(a[a.length-1]);
    

    for example.

    for example. The point is that your loop is (correctly skipping that last index). So one reasonable solution is to do that last print statement after your loop; as you know that you want to print it.