How to draw Isosceles Triangle in Java using only two for loops? -
i can able draw pattern triangle using 3 for-loops want draw using 2 for-loops.
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 program of mine 3 loops
import java.util.scanner; class isotrg { public static void main(string[] args) { int n; system.out.println("enter no. line:"); scanner sc = new scanner(system.in); n = sc.nextint(); (int = 0; < (2 * n) - 1; i++) { int d = 1; if (i < n) { (int j = 0; j <= i; j++) { system.out.print(d + " "); d++; } system.out.println(); } else { for(int j = 1; j < (2 * n) - i; j++) { system.out.print(d + " "); d++; } system.out.println(); } } } }
your code given doing right steps print triangle correctly. key focus on here stopping condition of loop. when i < n (in case, when i less 7), don't want j exceed i. when i greater n, don't want j exceed 2n - i.
so, considering both of these conditions jointly, want j less i , want less 2n - i. join 2 conditions using logical , operator. you'll have adjust bounds of loop appropriately, checking relative values of i , j @ both ends ensure they're lining appropriately:
public static void main(string[] args) { int n; system.out.println("enter no. line:"); scanner sc = new scanner(system.in); n = sc.nextint(); (int = 1; < (2 * n); i++) { (int j = 1; j <= && j <= (2 * n) - i; j++) { system.out.print(j + " "); } system.out.println(); } } additionally, notice can remove unnecessary intermediate variable d.
Comments
Post a Comment