1

my code for mario less comfortable is correct. But I got the answer by trying out different value multiple times. And after I finally got the correct answer, I do not understand the logic behind it. My code looks like this:

My code looks like this:

I could not figure out why do k>i-n+1 and j

1 Answer 1

1

I'll try and explain this in the most beginner-friendly way possible. Take note that I did make some assumptions because you did not include the full code:

  • The outer for loop first declares the integer variable named i. It's to run for as long as this value is less than another int named n. I assume that this variable states the total number of rows to be made, correct? And after each iteration, i will simply be added by 1, meaning that a row has been made.

  • The first inner for loop declares an int named k. Now pay close attention, this is to run for as long as k is greater than i, the row number, minus n, which is the total number of rows, and added by 1 as an additional offset, because there is always one space in the first row. After which k will be decreased by 1, meaning that there is one less space, which is to be replaced by a pound sign. I assume that you already understand what the code inside does.

  • Finally, the second inner for loop declares an int named j. This is pretty much the same as before, but with a few operator inversions since you increment by 1, and not -1 as with the loop before. This is to run until j is less than the row number added by 2 as an additional offset, because there are always 2 hashes in the first row. Now why not subtract it by n? This is because since you are counting up, there's basically no need to keep track of which row number you're supposed to be in, because j will already be equal to it in every iteration!

Now, I don't expect you to completely understand this simplified explanation because I am typing this in text form. If you do want to truly visualize the logic, I suggest you use debug50. It's a super-helpful tool that's given to you by the course if you want to do some in-depth monitoring of how your code's doing. You're supposed to use that in week 2 though, so until you're accustomed to using it, you should proceed and come back when you've got the hang of it.

1
  • Thank you for your answer! It helped me understand it more. I will definitely check out debug50!
    – Issa
    Commented Jul 16, 2018 at 18:10

You must log in to answer this question.

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