So within the outer loop (before the inner loop), you need to write some spaces. That's straightforward enough, if you just know how many spaces.
i = 1: 0 spaces
i = 2: 3 spaces
i = 3: 6 spaces
i = 4: 9 spaces
i = 5: 12 spaces
So you need to write 3*(i - 1) spaces. Is that enough of a clue?
Mohammad Sufiyan Al Yousufi
posted 7 years ago
Thank you for replying. Yes, it is known how many spaces needed. But how can we put spaces. If we change n value then it should display based on the new value.
I mean, how we controle the execution to print spaces... Sorry if I sounds dump.
posted 7 years ago
If you can print out the numbers 1-n (which you're already doing), surely you can print n spaces? It just needs another loop.
There are also "neater" ways - System.out.format() gives you some interesting options if you want to investigate that.
By the way, I think the code would be a bit easier to follow if you used a for loop for the inner loop, as well as the outer. for is generally better than while if you're just counting through a set that is known at the start of the loop.
Mohammad Sufiyan Al Yousufi wrote:Thank you Matthew, really nice explaination. Your explaination helps me to understand the flow.
Rahul you are really great. I tried so much but not getting it. Really nice. How can I improve my logical skills to do these types of questions?
I am not great. I am new to java. Dont worry, find more problems and solve them. You will become better with practice. And if its logic you like, solve "good" puzzles (like in news paper)...that will sharpen you for coding !
Good luck and keep coding...and as bryan adams would like it "keep coding till the fingers bleed"
one suggestion about the code written by Rahul Sudip Bose...You should ALWAYS use curly braces on all for loops, even when only one line. If you don't, I guarantee that some day, you will put in a print statement or some other line of code in what you think is the loop body, and your code will break.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors