# making triangle using *

• 09-13-2011, 08:37 AM
Bravid2001
making triangle using *
I have searched for this and found many similiar questions. The trick here is to not make the exact same image as below. The triangles need to be seperate.

Write a java application that displays the following patterns separately one below the other.
Use for loops to generate the patterns. There are 4 Triangle patterns.
All asterisks (*) should be printed by a single statement of the form System.out.print('*');

* ********** ********** *
** ********* ********* **
*** ******** ******** ***
**** ******* ******* ****
***** ****** ****** *****
****** ***** ***** ******
******* **** **** *******
******** *** *** ********
********* ** ** *********
********** * * **********

I have figured out the 1st triangle and the third triangle. Although I don't completely understand why the third triangle works. I can't seem to figure out the 2nd and 4th. Here is what I have:

//This program display 4 triangle patterns using for loops

//Use the Scanner class to create an object to read input from system.in
public class Triangle3 {

public static void main (String[] args){

/*Create for loop for triangle 1
/* loop 10 times
*/

int row;
// maximum number of rows
int maxRows = 10;

//create a loop
for (row = 1; row <= maxRows; row++) {

//print *
int firstTri;
for (firstTri = 1; firstTri <= row; firstTri++){
System.out.print ("*");
}

//print a new line
System.out.println();

}

row = 1;
maxRows = 10;

//Create for loop for triangle 3
for (row = 1; row <= maxRows; row++) {

//print *
int thirdTri;
for (thirdTri = 10; thirdTri >= row; thirdTri--){
System.out.print ("*");
}

//print a new line
System.out.println();

}

}

}
• 09-13-2011, 09:05 AM
JosAH
Re: making triangle using *
You should decompose your problem(s) in manageable chunks; have a look at this small method:

Code:

```public static void printNChars(char c, int n) {   for (int i= 0; i < n; i++)       System.out.print(c); }```
You have to pass it a char and an int n; it'll print n of those chars on one line; it can be used by the following two methods:

Code:

```public static void printNStars(int n) { printNChars('*', n); } public static void printNSpaces(int n) { printNChars(' ', n); }```
The first method prints n stars while the second method prints n spaces (whatever the value of n may be). Now try to formulate your original problem(s) in terms of the two little methods above.

kind regards,

Jos