0

I have searched the forum for an answer to my question but the code from others confused me. My pyramid keeps printing upside down and I'm not really sure why. I am not looking for an answer but rather an explanation to lead me in the right direction. Below is my code -

enter image description here

2
  • Hi. While screen shots can sometimes be useful when showing output or results, it's far better to cut and paste from the IDE to the question. It's far easier for others to test your code if they can then cut and paste it into their IDE. In the future, please don't use screen shots. Nobody wants to transcribe code. Too many issues involved. – Cliff B Jul 8 '18 at 20:57
  • Will do! thanks for that! – Alonso Martinez Jul 8 '18 at 21:58
1

Think about what the for loops and i and j are doing. The outer loop is counting the rows from 0 to n-1, which is ok. But look at the inner loop:

for (j= i; j < n; j++)

Now, say that n = 5. On the first outer loop, i=0. That means that j starts at 0 and counts to 4, so it'll print 5 hashes. Next pass, 1 to 4 and so on. That's why the pyramid is upside down.

The inner loop, the number of hashes on a given line depends only on the line number and has nothing to do with the total number of lines.

On the other hand, the number of leading spaces depends completely on both the line number and the total number of lines! Think about that! ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

22
  • Thanks! Im still having a hard time understanding.. any other pointer you could give me? I've been trying to look at your comment for the past hour and changing my inner loop on the line number and nothing :( Sorry if this sounds dumb! I'm my first time coding :( – Alonso Martinez Jul 8 '18 at 21:55
  • It's not dumb. It's just lack of experience. ;-) Here's one hint, and if you still don't get it, well, .... In the inner loop, just count from 0 to the line number! Now, what var contains the current line number? – Cliff B Jul 8 '18 at 22:05
  • Thanks! So I did - for (int j = 0; j < n; j++) – Alonso Martinez Jul 8 '18 at 22:07
  • soooo close! J is the TOTAL number of lines, not the current line number. – Cliff B Jul 8 '18 at 22:08
  • Here's another hint. When you're using nested loops, the outer loop is usually limited by a fixed target, while the inner loop is usually limited by a moving target from the outer loop, in this case, the current line number. – Cliff B Jul 8 '18 at 22:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .