Deleting upper left triangle from multiplication table

47 Views Asked by At

I'm new to programming and am taking an intro to programming class which focuses on java.

I have an assignment that have been working on but can't seem to get the last portion of the requirements.

I am creating a source code that takes an input value, a, and creates a multiplication table a x a.

So far I have:

enter image description here

The end product should look something like the image. I feel like the next step is adding a new variable that prints the maxnum variable in the end of the first iteration and leaves whitespace in front of the rest of that iteration. I'm having trouble determining how to do it though. I feel like I need another for statement but don't know where to place it. My initial guess is after the for statement that uses the variable j but haven't had much luck. Any suggestions would be appreciated, thank you all!

What I have so far:

import java.util.Scanner;

public class MultiTable {
  public static void main(String[] args) {
    Scanner in =new Scanner(System. in );
    System.out.printf("%s", "Please enter a positive max. number: ");
    int maxnum = in.nextInt();
    System.out.printf("\n");
    while (maxnum < 0) {
      System.out.printf("%s" + "\n" + "\n", "Please enter a positive max. number: ");
      maxnum = in.nextInt();
    }
    int i = 0;
    int j;
    int k;
    System.out.printf("%10d", i);
    for (i = 0; i <= maxnum - 1; i++) {
      System.out.printf("%5d", i + 1);
    }
    System.out.printf("\n" + "-----");
    for (i = 0; i <= maxnum; i++) {
      System.out.printf("-----");
    }
    System.out.printf("\n");
    for (i = 0; i <= maxnum; i++) {
      System.out.printf("%3d" + "%2s", i, " |");
      for (j = 0; j <= maxnum; j++) {
        System.out.printf("%5d", i * j);
      }
      System.out.printf("\n");
    }
  }
}

enter image description here

2

There are 2 best solutions below

1
Ram On

If you carefully look at the pattern, you'll see the indices in the lower right triangle conforms to the condition max_count <= row + column.

So accordingly you'll need to add a condition in the inner loop to print the numbers only if the condition satisfies.

if(maxnum <= i+j) {
    System.out.printf("%5d", i * j);
} else {
    System.out.printf("%5s", " ");
}
1
TheRedZelda On

Is that what you were trying to do ? multiplication table triangle

For this result, you can use two "for" loops in replacement of your last loop ^^ :

for (int i = 0; i <= maxnum; i++){
        System.out.printf("%3d"+"%2s", i, " |");
        for (int j = 0; j < i; j++){
            System.out.printf(" ".repeat(5));
        }
        for (int j = i; j <= maxnum; j++){
            System.out.printf("%5d", i*j);
        }
        System.out.printf("\n"); 
    }

I hope it'll help you !