0

I think I have got everything right except when my program is run it prints an extra line without any hashes, can anybody point out or correct my arithmetic (or the code)? Here's the code:

#include<stdio.h>
#include<cs50.h>

int main (void)

{
    int n;
    do
    {
        n=get_int("Put in a value of 1 to 8, both inclusive: \n");
    }
    while(n<1 || n>8);
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (i+j<= n-1)
            printf("");
            else 
            printf("#");
        }
        printf("\n");
    }
}

It is printing an extra line here.
Terminal

~/pset1/ $ ./mario4
Put in a value of 1 to 8, both inclusive: 
9
Put in a value of 1 to 8, both inclusive: 
7
       
      #
     ##
    ###
   ####
  #####
 ######

The problem becomes visible when I put a dot instead of space.
Terminal

~/pset1/ $ ./mario4
Put in a value of 1 to 8, both inclusive: 
7
.......
......#
.....##
....###
...####
..#####
.######

What's wrong here?

2

The problem is in your nested for loop. It prints a space all the way up until i + j <= n - 1. Once this is no longer true, your program exits the loop.

Let's look at this in a little more detail:

If n = 7 and i = 0, the if statement in the nested loop will continue printing spaces until i + j > n - 1, meaning when j = 7. As soon as that happens, though, (since j is incremented at the end of the loop) your loop stops because it fails the condition j < n.

You can fix this by either decreasing the check in your if statement or increasing the check in the loop.

3
  • @YoungPhysists yes, I made my own logic error when reading through the question--should pause to take that third read when coming from my own projects! Jan 15 at 14:04
  • Thanks! I just corrected my if statement. It should've been if (i+j<= n-2) instead of (i+j<= n-1) Jan 15 at 14:30
  • Glad I was able to help! You actually made the fix I did to check that my brain had started working. : ) Jan 15 at 14:33
0

You should use j < n + 1 in the second for loop. This will remove the extra line.

Hope this helps. If it does then please check the tickmark.

You must log in to answer this question.

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