Answer to Question #286059 in Java | JSP | JSF for Hamza

Question #286059

Task #9: Using Arrays and Methods


In this task, you are being asked to write methods that manipulate arrays in Java.


Write a method that swaps the elements of the array as follows:


 Swap the value of n-1’th index with the value of 0th index.


 Swap the value of i’th index with the value of i+1’th index.


You may use the following header for this method:


static int[] arraySwapValues(int[] array)


For example, suppose that the array array has 10 values: 1 2 3 4 5 6 7 8 9 10


The method will return an array which would contain the values: 2 3 4 5 6 7 8 9 10 1


NOTE: Declare and initialize the array without taking the input from user.


1. Create a program called ArraySwapValuesLab1.java.


2. Create appropriate variables and assign values using a Scanner object.


3. Correctly display appropriate messages.

1
Expert's answer
2022-01-12T09:56:53-0500


public class ArraySwapValuesLab1 {


	/**
	 * The start point of the program
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) {


		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
		arraySwapValues(array);


		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");
		}


	}


	// Method to Swap Array
	static int[] arraySwapValues(int[] array) {


		// If array has no elements, return NULL
		if (array.length == 0)
			return null;


		int temp = array[0];
		for (int i = 0; i < array.length - 1; i++) {
			array[i] = array[i + 1];
		}
		array[array.length - 1]=temp;
		
		return array;
	}


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog