Skip to content
Advertisement

How to Flip the triangle?

How to flip this triangle?

So i was making aritmethic sequance triangle. It was upside down. How do I turn it 180 degree?

for example:

1=1
1+2=3
1+2+3=6
etc...

my code:

package javaapplication4;

public class NewClass5 {
    public static void main(String[] args) {
        int i=5,a; 
        for(int j=i; j>=1; j--) { 
            for(a=1; a<=i; a++)
                System.out.print(a +" + ");
            int n = 0;
           for(a = 1; a<=i; a++) { 
               n = n + a;
           }
           System.out.print(" = "+ n);
           System.out.println();
           i--; 
       } 
    } 
} 

Advertisement

Answer

You can do it for any n, by getting input from the user

Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for (int i = 1; i <= n; i++) {
        int add = 0;
        for (int j = 1; j <= i; j++) {
            System.out.print(j);
            if (j == i) 
                System.out.print("=");
            else 
                System.out.print("+");    
            add += j;    
        }
        System.out.println(add);
    }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement