简体   繁体   中英

printing numbers as a triangle in java

In this problem the user has to input the starting number and the size of the triangle.if starting number is 5 and size of the triangle is 6 the output must be like this.

5
19 6
18 20 7
17 25 21 8 
16 24 23 22 9
15 14 13 12 11 10

I have already tried this problem and their is a error with my code. Can someone help me to find the error with this.

public class MyClass {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        //first number
        int n=in.nextInt();
        //size of the triangle
        int k=in.nextInt();
        int [][]arr=new int[k][k];
        int sizec=k,sizer=k,rstart=0,cstart=0,rend=k-2,cend=k-2,p=0;
        while(sizer>1&&sizec>1){
            int g=cstart;
            for(int i=rstart;i<sizer;i++){
                arr[g][i]=n;
                n++;
                g++;

            }
            for(int i=rend;i>=rstart;i--){
                arr[cend+1][i]=n;
                n++;

            }
            for(int i=cend;i>cstart;i--){
                arr[i][rstart]=n;
                n++;

            }
            rstart++;
            cstart+=2;
            rend-=2;
            sizec-=2;
            sizer-=2;
        }
        for(int j=0;j<k;j++){
            for(int h=0;h<j+1;h++){
                System.out.print(arr[j][h]+" ");
            }
            System.out.println();
        }
    }
}

You forgot a

cend--;

Put it there:

    sizer-=2;
    cend--;
}

I would also recommend that you change your variable names into words so that it is possible for other people to read your code. For example, cend could be "columnEnd".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM