Left triangle, * **
from above pattern we come to know that- 1)we need to print pattern containing n rows (for above pattern n is 4). 2)each row contains star and no of stars i each row is incremented by 1. So for Left alinged triangle we need to use 2 for loop. 1st "for loop" for printing n row. 2nd "for loop for printing stars in each rows. Code for Left alinged triangle- public static void leftTriangle() {
Correctly selected triangle- *
**
from above pattern we come to know that- 1)we need to print pattern containing n rows (for above pattern n is 4). 2)In each row we need to print spaces followed by a star & no of spaces in each row is decremented by 1. So for Right alinged triangle we need to use 3 for loop. 1st "for loop" for printing n row. 2nd "for loop for printing spaces. 3rd "for loop" for printing stars. Code for Right alinged triangle - public void rightTriangle() {
Triangle Center- *
* * *
from the above figure we learn that - 1) we need to print a template containing n lines (for the above figure, n is 4). 2) Inside each line, we must print spaces followed by a star, and then again a space. The number of spaces in each line at startup decreases by 1. So, for a regular triangle with a triangle, we need to use 3 for the loop. 1st "cycle" for printing n lines. 2nd "for print cycles. Third" cycle "for printing stars.
The code for the central triangle is
public void centerTriangle() { for (int a=1;a<=4;a++)// for lop for row { for (int c =4;c>=a;c--)// for loop for space { System.out.print(" "); } for (int b=1;b<=a;b++)// for loop for column { System.out.print("*"+" "); } System.out.println();} }
CODE FOR PRINTING ALL 3 SAMPLES - public class space 4 {public static void leftTriangle () {/// there are no lines 4 for (int a = 1; a <= 4; a ++) // for the loop for the line {
for (int b = 1; b <= a; b ++) for the loop for the column {System.out.print ("*"); }
System.out.println();} } public static void rightTriangle() { // here 1st print space and then print star for (int a=1;a<=4;a++)// for loop for row { for (int c =3;c>=a;c--)// for loop for space { System.out.print(" "); } for (int d=1;d<=a;d++)// for loop for column { System.out.print("*"); } System.out.println(); } } public static void centerTriangle() { for (int a=1;a<=4;a++)// for lop for row { for (int c =4;c>=a;c--)// for loop for space { System.out.print(" "); } for (int b=1;b<=a;b++)// for loop for column { System.out.print("*"+" "); } System.out.println();} } public static void main (String args []) { space4 s=new space4(); s.leftTriangle(); s.rightTriangle(); s.centerTriangle(); } }
source share