For-Loops to Reverse an int Array

So I wanted to go over the purpose of for-loops since they are so important for this class. Here is an example of using a For-Loop to reverse the elements in an array:

/*I used ideone.com for this program because it is a lot faster than starting eclipse if all you want to do is play around with some code. Copy this code into ideone.com and you should get the same output*/

/* Following import statements allows our program to use java libraries. Need this for print and array setup */

import java.util.*;
import java.lang.*;
import java.io.*;

class SIBlog
{
public static void main (String[] args) throws java.lang.Exception
{
int[] test = {1,2,3,4,5,6}; /* square brackets tell java to create an array and int tells java the elements will be of type integer. */
int temp; // Declare int variable called temp

for (int i = 0; i <test.length/2; i++) { //stop when it reaches half the array length using integer division

temp = test[i]; //assign value into temp
test[i] = test[(test.length-1)-i]; // swaps values
test[(test.length-1)-i] = temp; // uses temp to store value back in array

}

System.out.println(test.toString()); //Gives us memory address >> [I@106d69c
System.out.println(test); //Gives us memory address   > [I@106d69c
System.out.println(Arrays.toString(test)); // Gives us string representation of array > [6, 5, 4, 3, 2, 1]

/* “Integer division is division in which the fractional part
(remainder) is discarded is called integer division and is sometimes denoted” . */
//Examples of Integer Division
System.out.println(6/2); // give us the number 3
System.out.println(7/2); // give us the number 3
System.out.println(8/2); // give us the number 4

}

} // end of class file/program

Output:

[I@106d69c
[I@106d69c
[6, 5, 4, 3, 2, 1]
3
3
4

Leave a Reply

Your email address will not be published. Required fields are marked *