Return Array

From CompSciWiki
Revision as of 12:04, 1 April 2010 by TravisAM (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Write a method which will take an array of phone numbers and add the 204 area code to each one. Print this array in main.

Example:
int[] array = {4889123, 4889124, 4889125};
returnArray(array);

Output:
2044889123
2044889124
2044889125

 

SideSectionTitle

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

The 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  )
{
}


Now that we have the skeleton we can start by creating an array in main, we will pass that array to our returnArray method. returnArray will return an array which we will store in a temporary array and print:

public static void main()
{
   int[] array = {4889123, 4889124, 4889125};
   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
   }
}


Now we will fill in returnArray. We know that it will be passed an array and we need add 204 to the beginning of each one. We will then need to return the array:

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+2040000000; // add 2040000000 to each element to give it an area code 
   }
   return array; // Return the changed array
}


Now put it all together:


public static void main()
{
   int[] array = {4889123, 4889124, 4889125};
   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+2040000000; // add 2040000000 to each element to give it an area code 
   }
   return array; // Return the changed array
}

Code

SolutionCode goes here. Please DO NOT put your code in <pre> tags!

Back to the Program-A-Day homepage