3838 Shares

# Java code: How do you swap elements in an array?

Topic: How to write a swap program in java
June 17, 2019 / By Brenda
Question: The assignment is "In this task, you will use a for loop to read a user-designated number of integers into an array, and another for loop to swap elements in the array. Then your program will write out the array." This is what I've been able to get to work so far. The swapping for loop is where I am stuck. Any help appreciated. public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt user to enter array size System.out.printf("How many intergers will you enter? "); final int i = input.nextInt(); int[] numItems = new int[i]; // Prompt user to enter elements in array System.out.printf("Enter " + i + " integers: "); for (int j = 0; j < numItems.length; j++) { numItems[j] = input.nextInt(); System.out.print(numItems[j] + " "); } }

## Best Answers: Java code: How do you swap elements in an array?

Originally Answered: In java, what syntax can I use for taking certain values of one array and using them to create another array?
If you are doing this with a sorted array (low to high) it is easy.... 1.) determine the number of elements in the array as you are going to loop through each element. Using a For/next where idx = 1 to maxIndex (Notice I am not starting at 0) 2.) read the value in the 0 element (lowest value) into a variable X = ay(0) do this before entering the loop 3.) Start your for next loop. As you loop through each element (1 to max)you are going move its value into the element just below it ay (idx-1) = ay(idx) But as you do this movement you add the value of X which before entering the loop was set to ay(0) ay(idx-1) = ay(idx) + X since we only want to combine values in the first two elements you only need to add the value stored in X just on the first add. you can either set X = 0 after the first assignment OR use an if statement to perform the addition just once when the idx = 1 4.) after exiting the loop you will need to redim the array since everything has been copied down one position. You will have a duplicate of the last element so redim to max-1
Originally Answered: In java, what syntax can I use for taking certain values of one array and using them to create another array?
initially you're beginning with an array of four positions. we are going to call this A. A(a million) is a million A(2) is 3 A(3) is 6 and A(4) is 7. Your software might choose the equivalent of here: B = a million initiate loop C = A(a million) + A(B+a million) A(a million) = C If B = 4 go out loop. B = B + a million end loop i think of you're able to have the means to stick to this actual. Any language could have categories of loop and as a result you're able to could make minor differences. solid luck. end loop

If you have your own answer to the question how to write a swap program in java, then you can write your own version, using the form below for an extended answer.