• Register
Welcome to Kodlogs, programming questions and answer website.
+1 vote
817 views

Problem:

I am provided with an assignment in which i have to sort out the problem as following. I wrote code for this but it is not working as expected. My question is as following:

Write a method swaparrayends() that swaps the first and last elements of its array parameter.

Ex: sortArray = {10, 20, 30, 40} becomes {40, 20, 30, 10}. The array's size may differ from 4.

 

by (1.6k points)  
reopened by

1 Answer

+1 vote

Solution:

import java.util.Scanner; 
public class SwapArrayEnds{ 
public static void swapArrayEnds(); 
public static void main (String [] args) 
{ 
int totalno = 4; 
int[] sortArray = new int[totalno]; 
int i = 0; 
sortArray[0] = 10; 
sortArray[1] = 20; 
sortArray[2] = 30; 
sortArray[3] = 40; 
swapArrayEnds(sortArray, totalno); 
for (i = 0; i < totalno; ++i) 
{ 
System.out.print(sortArray[i]); 
System.out.print(" "); 
} 
System.out.println(""); 
return; 
} 
} ​​​​​​​

 

 Another code to get this is:


Another code to get this is: 

import java.util.Arrays; 
public class SwapArrayEnds
{ 
public static void main(String[] args) 
{ 
int[] totNos = {10,20, 30, 40}; 
System.out.println("Input Array: "+Arrays.toString(totNos)); 
int x = totNos[0]; 
totNos[0] = totNos[totNos.length-1]; 
totNos[totNos.length-1] = x; 
System.out.println("The final output is: "+Arrays.toString(totNos)); 
} 
} 

Result: Input Array: [10, 20, 30, 40] Final Output: [40, 30, 20, 10]

 

by (5.3k points)  
...