Answers for "reverse an array in java using while loop"

12

reverse array in java

int length = array.length;
		for(int i=0;i<length/2;i++) {
			int swap = array[i];
			array[i] = array[length-i-1];
			array[length-i-1] = swap;
		}
or
Collections.reverse(Arrays.asList(array));
Posted by: Guest on May-10-2020
1

reverse an array in java using while loop

import java.util.Scanner;
public class Example
{
   public static void main(String args[])
   {
	int counter, i=0, j=0, temp;
	int number[] = new int[100];
	Scanner scanner = new Scanner(System.in);
	System.out.print("How many elements you want to enter: ");
	counter = scanner.nextInt();

	/* This loop stores all the elements that we enter in an 
	 * the array number. First element is at number[0], second at 
	 * number[1] and so on
	 */
	for(i=0; i<counter; i++)
	{
	    System.out.print("Enter Array Element"+(i+1)+": ");
	    number[i] = scanner.nextInt();
	}

	/* Here we are writing the logic to swap first element with
	 * last element, second last element with second element and
	 * so on. On the first iteration of while loop i is the index 
	 * of first element and j is the index of last. On the second
	 * iteration i is the index of second and j is the index of 
	 * second last.
	 */
	j = i - 1;     
	i = 0;         
	scanner.close();
	while(i<j)
	{
  	   temp = number[i];
	   number[i] = number[j];
	   number[j] = temp;
	   i++;
	   j--;
	}

	System.out.print("Reversed array: ");
	for(i=0; i<counter; i++)
	{
	   System.out.print(number[i]+ "  ");
	}       
   }
}
Posted by: Guest on January-30-2021

Code answers related to "reverse an array in java using while loop"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language