Problem:
=======
Reverse the elements within an array using JAVA
Algorithm:
==========
1. Initialize the array with random values.
2. Declare a variable called temp and initialize the value with 0.
3. Iterate the array and swap the first element of the array and last element of the array.
4. Print out the result
Solution:
=========
import java.util.*;
import java.security.SecureRandom;
class ReverseTheArrayElementsUtility{
public static void main(String[] args){
int[] a= new int[3];
initializeArray(a);
System.out.println("Printing initial array values");
printArray(a);
reverseArrayValues(a);
System.out.println("Printing after reversal of an array");
printArray(a);
}
public static void initializeArray(int[] array){
Random random = new SecureRandom();
for(int i=0;i < array.length; i++){
array[i] = random.nextInt(100);
}
}
public static void printArray(int[] array){
Arrays.stream(array).forEach(System.out::println);
}
public static void reverseArrayValues(int[] array){
int temp = 0;
for(int i=1; i < array.length-1; i++){
temp = array[i-1];
array[i-1] = array[array.length - i];
array[array.length-i] = temp;
}
}
}
Output:
==========
Printing initial array values
81
59
96
Printing after reversal of an array
96
59
81
Printing initial array values
95
47
89
Printing after reversal of an array
89
47
95
=======
Reverse the elements within an array using JAVA
Algorithm:
==========
1. Initialize the array with random values.
2. Declare a variable called temp and initialize the value with 0.
3. Iterate the array and swap the first element of the array and last element of the array.
4. Print out the result
Solution:
=========
import java.util.*;
import java.security.SecureRandom;
class ReverseTheArrayElementsUtility{
public static void main(String[] args){
int[] a= new int[3];
initializeArray(a);
System.out.println("Printing initial array values");
printArray(a);
reverseArrayValues(a);
System.out.println("Printing after reversal of an array");
printArray(a);
}
public static void initializeArray(int[] array){
Random random = new SecureRandom();
for(int i=0;i < array.length; i++){
array[i] = random.nextInt(100);
}
}
public static void printArray(int[] array){
Arrays.stream(array).forEach(System.out::println);
}
public static void reverseArrayValues(int[] array){
int temp = 0;
for(int i=1; i < array.length-1; i++){
temp = array[i-1];
array[i-1] = array[array.length - i];
array[array.length-i] = temp;
}
}
}
Output:
==========
Printing initial array values
81
59
96
Printing after reversal of an array
96
59
81
Printing initial array values
95
47
89
Printing after reversal of an array
89
47
95
No comments:
Post a Comment