31.5k views
2 votes
C programming ..

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
My problem is the whitespace after number 3. How can I fix it ?
this is the code I entered:
#include
int main(void) {
int userNum = 0;
int i = 0;
int j = 0;
for (i=0;i<=userNum;++i) {
printf("%d",i);
for (j=0;j<=i;++j) {
printf(" ");
}
}
return 0;
}
Thanks

1 Answer

6 votes

Answer:

The code you posted adds a whitespace after the number because you are using the printf(" ") statement inside the inner loop, which is printing a space after each number. To fix this, you can move the printf("\\") statement inside the inner loop, like this:

#include <stdio.h>

int main(void) {

int userNum = 3;

int i = 0;

int j = 0;

for (i=0; i<=userNum; ++i) {

for (j=0; j<=i; ++j) {

printf(" ");

}

printf("%d\\", i);

}

return 0;

}

This will print the numbers with the desired indentation and will not add any extra whitespace after each number.

Hope this helps!

User Mark Burgoyne
by
8.0k points