Click here to Skip to main content
15,887,302 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I haven't been able to get it like this:
Please enter a number:
5
|   1   2   3   4   5
-------------------------
   1|   1   2   3   4   5
   2|       4   6   8  10
   3|           9  12  15
   4|              16  20
   5|                  25


What I have tried:

Java
import java.util.Scanner ;

public class TimesTables {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in) ;

        System.out.println("Please enter a number: ") ;
        int num = input.nextInt();


        //Your code here

        // use nested loops
        int z = 0;
            System.out.printf("    |");        
        for (int r=1;r<=num;r++){
            System.out.printf("%4d",r );
            z = z+4;
        }
            System.out.println();
        for (int r=0;r<=z+4;r++){
            System.out.printf("-",r);
        }
              
        System.out.println();           
        for (int r=1;r <= num; r++){
            System.out.printf("%4d|", r);
            for(int c=1;c <= num; c++){
                if(r <= c){
                    System.out.printf("%4d", c*r);
                }
            }
                System.out.println("");
        }
        
        
        //TimesTablesPrinter.print(multiples);
    }
}
Posted
Updated 3-Apr-23 1:13am
v2
Comments
Mike Hankey 3-Apr-23 6:43am    
What's the problem? It's not clear what where your having troubles.
Tarini Sunkara 3-Apr-23 7:31am    
I need to got the output which i have shown at the top. But I'm getting the output i've showed below

1 solution

If I run your code, and enter the same value as you, what I get is the right numbers:
Please enter a number:
5
    |   1   2   3   4   5
-------------------------
   1|   1   2   3   4   5
   2|   4   6   8  10
   3|   9  12  15
   4|  16  20
   5|  25

All that is wrong is the formatting - and that's because you don't allow for "empty columns" in a row before your value output.

I'd have a row number that went from 0 to N - 1, and for each row I'd prefix that number of blank columns before I started outputting actual data.
Think about how you would do it manually, and you'll see what I mean.
 
Share this answer
 
v2
Comments
Tarini Sunkara 3-Apr-23 7:28am    
I do not get it where am i supposed to change the code
OriginalGriff 3-Apr-23 8:08am    
Where do you think?
You wrote it after all!
Tarini Sunkara 3-Apr-23 7:30am    
Please enter a number:
5
| 1 2 3 4 5
-------------------------
1| 1
2| 2 4
3| 3 6 9
4| 4 8 12 16
5| 5 10 15 20 25

The output i got
OriginalGriff 3-Apr-23 8:09am    
Not from the code you showed, you didn't.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900