Nested Loops trouble.

Hey cplusplus world,
I'm new to this forum and am currently studying computer science where I've taking a very huge liking too. Although, a lot of classes are online and hard to get feedback from my professor at times without physically going up to the school and hoping he is here.
I'm not asking anybody to do any of the problems I post, just simply help me with what I'm doing wrong. Thank you.

Here is my instruction:
Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints:

0
1
2
3

( these are suppose to have a space concurrent to the number, i.e. One space for 1, two for 2, etc. I don't know why it isn't showing correctly on here. )

I got it to finally start printing in the form I want, but I get like 3 or 4 extra whitespaces on a new line under the 3 and can't figure it out, if somebody can help me it would be much appreciated.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <stdio.h>

int main(void) {
   int userNum  = 0;
   int i = 0;
   int j = 0;
   

   while (i <= userNum ){
      printf("%i\n", i);
      
      ++i;
      for (j = 0; j != i && i && j <userNum; ++j ){
         printf(" ");
   }
   }
   return 0;
}
Last edited on
I just ran the code and this was the result:

1
2
3
4
0
 1
  2
   3


Are you not getting this result? Is this not what you are looking for?
When I run the program on the website through their little program where it gets graded, under the 3 their is an extra line with like 3 extra spaces which causes it to reply that I am getting 3 extra whitespaces.
Last edited on
I'm sorry, understand your question now. The logic of your second loop is incorrect. Try simplifying what you are trying to do in the condition of the second for loop. If you step through the problem yourself, you can see why the condition statement is wrong.

It is important to note that the nested for-loop is executed after the number is printed. You either need to set up a condition to make sure this is not executed in the last loop or rethink your loop logic entirely.

If you want to rewrite the loop logic, here is a Hint:
-the space(s) is/are printed before the number is printed, so having your code follow this condition will be easier and more readable
Last edited on
Thank You PrivateRyan for taking the time to look at this and give me a little direction. Now I realize I had the space printing after the number.
Topic archived. No new replies allowed.