Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

java - Creating Triangular Multiplication Table using Do-while Loop

I want to ask a question or a probable favor on how am I going to make my program coding "do-while loop" in creating a Triangular Multiplication. Is there a probable way on to create such thing without using any other statement?

public class Main {
  static void ssbr(int n) {
    int i = 1;
    
    do{
    System.out.printf("%4d", n * i);
    i = i + 1;
    } while(i <= 7);
    System.out.println("");
    }

public static void main(String[] args) {
    int i = 1;
    do{
    ssbr(i);
            i = i + 1;
        } while (i <= 7);
    }
}

Output it gave:

1  2  3  4  5  6  7
2  4  6  8 10 11 12
3  6  9 12 15 18 21
4  8 12 16 20 24 30
5 10 15 20 25 30 35
6 12 18 24 30 36 42
7 14 21 28 35 42 49

Output I wanted:

1
2  4
3  6  9
4  8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
question from:https://stackoverflow.com/questions/65917401/creating-triangular-multiplication-table-using-do-while-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it with the following algorithm:

  1. You have to do it 7 times and therefore you can use a loop that should run 7 times.
  2. Each row starts with the row number, and run for row number * row number times with a step-value equal to the row number.

Given below is the implementation of this algorithm using for loop and I leave it to you to implement it using the do-while loop (as it seems to be your homework ??)

public class Main {
    public static void main(String[] args) {
        int n = 7;
        for (int row = 1; row <= n; row++) {
            for (int col = row; col <= row * row; col += row) {
                System.out.printf("%-4d", col);
            }
            System.out.println();
        }
    }
}

Output:

1   
2   4   
3   6   9   
4   8   12  16  
5   10  15  20  25  
6   12  18  24  30  36  
7   14  21  28  35  42  49  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...