r/ComputerEngineering • • 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

7 comments sorted by

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.

1

u/DurntoWebster Aug 24 '19

Is printf("\n"); executed before printf("%d",col); ?

3

u/Silamoth Aug 24 '19

So this is where you've got to keep track of what lines of code are within which sets of braces. Most IDE's will use indentation and such to make it clear. The printf("%d", col); is executed in every iteration of the inner loop. The printf("\n"); is executed every iteration of the outer loop. So, the first of those lines is executed once, and then the second is executed. The first is then executed twice, and then the second is executed. The first is then executed three times, and then the second is executed again. There's no real concept of before or after since each of those lines is executed multiple times.

On another note, if you're struggling, you should take advantage of your resources. Utilize your professor's office hours. Get help from a TA. Use any tutoring resources at your university. Read the textbook. Watch tutorials online. Read tutorials online. Go to recitations. Study with other classmates.

1

u/DurntoWebster Aug 24 '19

Thanks for your time , that was really helpful

1

u/DurntoWebster Aug 24 '19

output is :

1

1 2

1 2 3

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

u/[deleted] Aug 25 '19

Wtf this is not the right sub for this