Majima
Majima

Reputation: 31

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

Upvotes: 0

Views: 620

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79025

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  

Upvotes: 2

Related Questions