Hi all. I'm new to C programming and I am having A LOT of trouble understanding nested for loops. Here is a program I wrote.
Code:
#include <stdio.h>
int main(void){
int userNum = 0;
int i, j;
printf("Enter an integer: "); scanf("%d", &userNum);
printf("\n");
for(i = 0; i <= userNum; ++i){
for(j = 1; j <= i; ++j){
printf(" ");
}
printf("%d", i);
printf("\n");
}
return(0);
}
The desired output is:
0
_1
__2
___3...... and so on, up to the number that was entered. (the underscores should be spaces instead)
I understand why it works for the first couple of iterations. But starting on the third line, why does the inside loop iterate twice, producing 2 spaces? Shouldn't 'j' increment and become equal to 'i', therefore only iterating once and printing one space?
I'm just trying to get a better understanding of all this. Any kind of explanation would be greatly appreciated.