Return Array
Back to the Program-A-Day homepage
ProblemWrite a method which will take an array of ints as a parameter.
The method should change the contents of the array to 1-5. Call this method from main and then print the returned array in main.
|
SideSectionTitle
An image or By Students section | |
---|---|---|
SolutionThe solution...
To solve this problem we are going to create a skeleton structure. We know that we will have two methods: main & returnArray. We know that returnArray will accept an integer array and return that array:
public static void main() { } public static int[] returnArray( int[] array ) { }
public static void main() { int[] array = {45,32,78,45,890}; int[] tempArray; tempArray = returnArray(array); for( int i = 0; i < tempArray.length; i++ ) // This will loop through every item in the array { System.out.print( tempArray[i] + "/" ); // Print the changed value } } public static int[] returnArray( int[] n ) { }
public static int[] returnArray( int[] array ) { for( int i = 0; i < array .length; i++ ) // This will loop through every item in the array { array [i] = i+1; // Change the items to i+1 - we don't want start at i because we don't want 0 } return n; // Return the changed array }
public static void main() { int[] array = {45,32,78,45,890}; int[] tempArray; tempArray = returnArray(array); for( int i = 0; i < tempArray.length; i++ ) // This will loop through every item in the array { System.out.print( tempArray[i] + "/" ); // Print the changed value } } public static int[] returnArray( int[] n ) { for( int i = 0; i < array .length; i++ ) // This will loop through every item in the array { array [i] = i+1; // Change the items to i+1 - we don't want start at i because we don't want 0 } return n; // Return the changed array } | ||
CodeSolutionCode goes here. Please DO NOT put your code in <pre> tags! |