Difference between revisions of "Print Array"

From CompSciWiki
Jump to: navigation, search
 
Line 1: Line 1:
{{1010PrAD|ProblemName=Print Array
+
{{1010PrAD|ProblemName=Print Numbers
  
|Problem= Write a method which will take an array of ints as a parameter.
+
|Problem= Write a method which will take 3 ints as parameters.
The method should print the elements of the array, separated by a comma.
+
The method should print the elements of the array in order, separated by a comma.
 
<BR><BR>
 
<BR><BR>
 
Example:
 
Example:
 
<BR>
 
<BR>
int[] n = {45,32,78,45,890,45,32};<BR>
+
printNumbers(5, 7, 4);<BR>
printArray(n);<BR>
+
Output:4,5,7
Output:45,32,78,890,45,32
+
  
  
Line 14: Line 13:
  
 
|SideSection=
 
|SideSection=
Printing an array is a very common task in programming, there are
 
many situations which require such output. It is also very useful
 
for testing, to check that the elements in an array are what they
 
are supposed to be.
 
  
  
|Solution=To solve this problem you need to use a for loop.
+
|Solution=
Loop from 0 through all elements of the input array. At each
+
You should split this up into three methods which print out the smallest, middle and largest images.
iteration, print out the current array element and a comma.
+
<pre>
 +
public static void printSmallest( int n1, int n2, int n3 );
 +
public static void printMiddle( int n1, int n2, int n3 );
 +
public static void printLargest( int n1, int n2, int n3 );
 +
</pre>
 +
 
 +
You will need to use <b>if statements<b> to determine the proper
 +
order to print out the numbers.
 +
<pre>
 +
if( n1 <= n2 && n1 <= n3 )
 +
{
 +
  System.out.print( n1 );
 +
}
 +
else if( n2 <= n3 )
 +
{
 +
  System.out.print( n1 );
 +
}
 +
else
 +
{
 +
  System.out.print( n1 );
 +
}
 +
</pre>
  
  
 
|SolutionCode=
 
|SolutionCode=
 
<pre>
 
<pre>
public static void printArray( int[] n )
+
public static void printArray( int n1, int n2, int n3 )
 
{
 
{
 
   for( int i = 0; i < n.length; i++ )
 
   for( int i = 0; i < n.length; i++ )

Latest revision as of 12:37, 6 April 2010

Back to the Program-A-Day homepage

Problem

Write a method which will take 3 ints as parameters. The method should print the elements of the array in order, separated by a comma.

Example:
printNumbers(5, 7, 4);
Output:4,5,7

 

...by students

Solution

You should split this up into three methods which print out the smallest, middle and largest images.

public static void printSmallest( int n1, int n2, int n3 );
public static void printMiddle( int n1, int n2, int n3 );
public static void printLargest( int n1, int n2, int n3 );

You will need to use if statements<b> to determine the proper order to print out the numbers.

if( n1 <= n2 && n1 <= n3 )
{
   System.out.print( n1 );
}
else if( n2 <= n3 )
{
   System.out.print( n1 );
}
else
{
   System.out.print( n1 );
}

Code

Solution Code

Back to the Program-A-Day homepage