Search code examples
cloopsfor-loopnested-loops

My nested loop is printing one row less than wanted/expected


I need to prompt user to pick h and use h to print out that much number of rows where each row is incremented by 1. So I do understand this part and I have nested my loops but when I pick exmp: h=4 it prints 3 rows. I am beginner in programming and been breaking my head over this for some days now :P

I prefer you to give me some tips how to solve this by myself not only to get the anwser. thank you!

for (int i = 0; i < h; i++)
{
          for( int j = 0; j < i; j++)
          {
              printf("#");
          }
     printf("\n");
}
   }

Solution

  • In the first loop iteration i and j will both take the value 0. The second loop won't be entered because j<i is false.

    In the last iteration, i will take the value h-1 and j will iterate from 0 to h-2, thus printing h-1 #s.

    Consider changing the first loop to the following :

    for (int i = 0; i <= h; i++)