Advertisement
mmayoub

School, 05.09.2017, Ex1, array reverse

Sep 6th, 2017
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.81 KB | None | 0 0
  1. public class Ex1 {
  2.     // Write a Java program to reverse an array of integer values
  3.     public static void main(String[] args) {
  4.         // initialize array
  5.         int[] arr = { 3, 1, 5, 2, 7, 12, 79, 10 };
  6.  
  7.         // print source array
  8.         System.out.print("Array before reverse: ");
  9.         for (int i = 0; i < arr.length; i += 1) {
  10.             System.out.print(arr[i] + " ");
  11.         }
  12.         System.out.println();
  13.  
  14.         // reverse the array order
  15.         int left = 0;
  16.         int right = arr.length - 1;
  17.  
  18.         while (left < right) {
  19.             // switch values
  20.             int tmp = arr[left];
  21.             arr[left] = arr[right];
  22.             arr[right] = tmp;
  23.  
  24.             left += 1;
  25.             right -= 1;
  26.  
  27.         }
  28.  
  29.         // print the array after reverse
  30.         System.out.print("Array after reverse : ");
  31.         for (int i = 0; i < arr.length; i += 1) {
  32.             System.out.print(arr[i] + " ");
  33.         }
  34.         System.out.println();
  35.  
  36.     }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement