Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Assignment8 {
- //Simple method for printing arrays.
- public static void printArray( int [] array ) {
- for( int i = 0; i < array.length; i++ ) {
- System.out.print( array[i] + " " );
- }
- System.out.println();
- }
- //Method that initalizes the array elements to their index + 1, so
- // 1 2 3 4 5 ....
- public static void initializeArray( int [] array ) {
- for( int i = 0; i < array.length; i++ ) {
- array[i] = i + 1;
- }
- }
- //TODO: Write a method that squares each element of the array and
- //and returns the result. Note: we did something very close with
- //a method that doubled each element of the array.
- public static int [] squareArray( int [] array ) {
- for(int i=0; i<array.length; i++) {
- array[i] = array[i] * array[i];
- }
- return array;
- }
- //TODO: Write a method that reverses all elements of the array and
- //and returns the result. NOTE: This is in the book! You may use the
- //book's code.
- public static int [] reverseArray( int [] array ) {
- int len = array.length;
- int[] newArray = new int[len];
- for (int i=0; i<len; i++) {
- newArray[(len-1)-i]=array[i];
- }
- return newArray;
- }
- //TODO: Write a method that transposes each pair of elements in the
- //array. It swaps each element with the element next to it, so
- // For even size: 1 2 3 4 5 6 transposed is 2 1 4 3 6 5, and
- // For od size: 1 2 3 4 5 transposed is 2 1 4 3 5
- public static int [] transposeArray( int [] array ) {
- for (int i=0; i<array.length-1; i+=2) {
- int temp = array[i];
- array[i] = array[i+1];
- array[i+1] = temp;
- }
- return array;
- }
- //The main method does not need to be changed. It is complete.
- //You only need to fill in the three methods directly above.
- public static void main ( String [] args ) {
- int arraySize = 0;
- Scanner input = new Scanner(System.in);
- //Creates an array of numbers. Size based on user input.
- System.out.print("Enter size of array: ");
- arraySize = input.nextInt();
- int [] numbers = new int [arraySize];
- //Initialize and print array using given methods.
- initializeArray( numbers );
- System.out.println("Values in array are:");
- printArray(numbers);
- //Square all the numbers in the array and print.
- numbers = squareArray(numbers);
- System.out.println("Values in array when squared are:");
- printArray(numbers);
- //Re-initialize then reverse all the numbers in the array and print.
- initializeArray( numbers );
- numbers = reverseArray(numbers);
- System.out.println("Values in array when reversed are:");
- printArray(numbers);
- //Re-initialize then transpose all the numbers in the array and print.
- initializeArray( numbers );
- numbers = transposeArray(numbers);
- System.out.println("Values in array when transposed are:");
- printArray(numbers);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement