TEX] I have this code but can not get it to display the numbers the way i want.
I want the display
1
21
.
.
.

n-2)......1
(n-1).......1
n (n-1)... 21

My code is[/TEX]

public class print{
public static void parttens()
{  int w=4,t=0;
	int k = 1;
   int[]array=new int[5];
   for(int i=0;i<5;i++)
   {
    array[i]=k++;
	}
	for (int r=0;r<=4;r++)
	{
		for (int i=r;i>=0;i--)
			{
				System.out.print(array[i]);
				
			}
			System.out.println();
  	 
   }
}
public static void main(String []args)
{ 
 
 parttens();
 }
}

can you help me get the correct printout

I ment that is the display i get, the one i want is
1
21
321
4321
54321

Sorry i cnt get the editor to show want i wnt, the ones at the end
are to be above each other.

class pat{
public static void main(String []args)
{  int w=4,t=0;
	int k = 1;
   int[]array=new int[5];
   
	for (int r=0;r<=4;r++)
	{
		for (int i=r;i>=0;i--)
			{
				array[i]=i+1;
				System.out.print(array[i]);
 
			}
			System.out.println();
 
    }
  }

}

Look to me like you need to print some blanks in front of the numbers.

or, you could make it a lot easier:
you set a instantiate a String Object with value "";

iterate from 1 to n, doing:
theString = n + oldStringValue;
printLine(theString)

this won't use an array, if that's in your task description, but it'll do what you need.


you could apply the same to an array of course
arrayEl[0] = "1";
iterate from i = 1 < array.length
arrayEl = (i+1) +"" + arrayEl[i-1];

this would store the information in an array.

If you use stultuske's approach, I would tend to use a StringBuffer or StringBuilder instead of creating a new string every time through the loop. I know this is a small example, and memory/garbage collection isn't really a priority for you right now. I only bring this up because if you run across a similar situation where you're dealing with large amounts of data, appending to a SringBuffer is a LOT more efficient than creating a lot of String objects which just hang around after using them once, until the garbage collector is forced to clean them up.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.