In: Computer Science
(JAVA)
InvertArrangement
+invert(int[] a) : int []
+print(int[] a) : void
Example 1: the invert method receives the following arrangement: [1,2,3,4,5]
The invert method returns the array [5,4,3,2,1]
Example 2: the print method receives the following array:
[5,4,3,2,1]
The print method prints: 5,4,3,2,1 (data separated by commas).
TIP: for the print method use System.out.print () without the "ln".
Example 1:
public static int[] invert(int[] a){
int l=a.length;
int j=0;
int n[]=new int[l];//create new array
for(int i=l-1;i>=0;i--){
n[j]=a[i];//copy elements from last to new array
j++;
}
return n;//return array
}
Example 2:
public static void print(int[] a){
int i;
for(i=0;i<a.length-1;i++){
System.out.print(a[i]+",");//print each element
}
System.out.print(a[i]);
}
Full Code:
public class Main
{
public static int[] invert(int[] a){
int l=a.length;
int j=0;
int n[]=new int[l];//create new array
for(int i=l-1;i>=0;i--){
n[j]=a[i];//copy elements from last to new array
j++;
}
return n;//return array
}
public static void print(int[] a){
int i;
for(i=0;i<a.length-1;i++){
System.out.print(a[i]+",");//print each element
}
System.out.print(a[i]);
}
public static void main(String[] args) {
int a[]={1,2,3,4,5};
a=invert(a);//call function and
invert elements
print(a);
}
}
Screenshots:
Screenshots:
The screenshots are attached below for reference.
Please follow them for output.
Please upvote my answer. Thank you.