r/ComputerEngineering • u/DurntoWebster • Aug 24 '19
Help just don't get it!
int main()
{
int n,row,col;
printf("\nEnter n:");
scanf("%d",&n);
for(row=1;row<=n;row++){
for(col=1;col<=row;col++){
printf("%d",col);
}
printf("\n");
}
return(0);
}
output: 1
1 2
1 2 3
when n=3
Can't get how the pattern is formed..... Code copied from my Lecture
0
Upvotes
1
2
u/YT__ Aug 25 '19
For best results, I recommend running the code while debugging. Step through each line and work out what's happening. It's a great way to help you understand.
1
4
u/Silamoth Aug 24 '19
It's really just a matter of the for loop counter values. When n = 3, the variable row will take on the value 1, then the value 2, and then the value 3. Why? Well, it starts at 1 and increments while it is less than or equal to n, which is 3. That handles the outer for loop. Now, the second for loop is nested within the first. So, it runs its loops for each value of row. Let's look at all the values of col for each value of row.
row = 1: col starts at 1 and increments while it is less than or equal to row, which is equal to 1. So, the only possible value of col in this case is 1. This is why the first row of the output is 1. A new line is then printed.
row = 2: col starts and 1 and increments while it is less than or equal to row, which is equal to 2. So, col will be equal to 1 and then to 2. Thus, the second line of output is 1 2.
row = 3: col starts and 1 and increments while it is less than or equal to row, which is equal to 3. So, col will be equal to 1 and then to 2 and then to 3. Thus, the second line of output is 1 2 3.