Difference between revisions of "Passing Arrays"

From CompSciWiki
Jump to: navigation, search
Line 1: Line 1:
{{1010PrAD|ProblemName=Creating An Array
+
{{1010PrAD|ProblemName=Passing Arrays
 +
|Problem= Problem...
  
|Problem= There are ten students with ten grades. Instead of storing every single grade in a single variable it is easier to store this information in an array. Given that the grades are 56%, 34%, 75%, 89%, 78%, 87%, 71%, 67%, 98%, 85%, store the grades in an integer array as percents and convert them to decimals and store them in a double array.
 
  
 
+
|SideSectionTitle = Introducing Arrays
|SideSectionTitle = Introducing Array
+
 
|SideSection=
 
|SideSection=
 
[[Image:Wiki_array01.jpg|center]]<BR>
 
[[Image:Wiki_array01.jpg|center]]<BR>
  
|Solution=First create the skeleton structure of your program
+
|Solution=
<pre>
+
public class CreatingArray{
+
  public static void main(){
+
  }
+
}
+
</pre>
+
Next, the two arrays to be used are integer and double, so we need to create the variables that will store these arrays.
+
<pre>
+
int[] intArray;
+
double[] decimalArray;
+
</pre>
+
These will go inside the main program.
+
Now a new array must be created, this is done with the ''new'' keyword.
+
<pre>
+
intArray = new int[10];
+
decimalArray = new double[10];
+
</pre>
+
The 10 specifies the size of the array that you want to create. Now we will need to store the values inside the array. This is done by equating each position within the array with they value we want to store.
+
<pre>
+
intArray[0] = 56;
+
decimalArray[0] = intArray[0]/100.0; // or decimalArray[0] = 0.56;
+
intArray[1] = 34;
+
decimalArray[1] = 0.34;
+
etc.
+
</pre>
+
If the numbers that you are entering are know before hand, as in this case, it's much faster to create array in short hand format. This is done by creating your variable array and immediately equating it to all the value you want. This will automatically create the new array of the required size and equate positions within the array to the appropriate number. This short hand for the first 3 numbers will look like this:
+
<pre>
+
int[] intArray;
+
intArray = {56, 34, 75};
+
</pre>
+
This can also be done in one line.
+
<pre>
+
int[] intArray = {56, 34, 75};
+
</pre>
+
All that needs to be done now is to create the two arrays for the grades.
+
  
 
|SolutionCode=
 
|SolutionCode=
 
<pre>
 
<pre>
public class CreatingArrays{
+
some code
  public static void main(){
+
    int[] intArray = {56, 34, 75, 89, 78, 87, 71, 67, 98, 85};
+
    double[] decimalArray = {0.56, 0.34, 0.75, 0.89, 0.78, 0.87, 0.71, 0.67, 0.98, 0.85};
+
  }
+
}
+
 
</pre>
 
</pre>
  
 
}}
 
}}

Revision as of 10:30, 8 April 2010

Back to the Program-A-Day homepage

Problem

Problem...

 

Introducing Arrays

Wiki array01.jpg

Solution

Code

Solution Code

Back to the Program-A-Day homepage