Pelles C forum

C language => Beginner questions => Topic started by: nuha on November 29, 2013, 12:04:46 PM

Title: for loop
Post by: nuha on November 29, 2013, 12:04:46 PM
Quote#include<stdio.h>
int main(void )
{
for (int b=0;b<=5;b++)
for (int a=0;a<=b;a++)
printf("*\n");
}




I dont know why this code executes 21 "*" line by line
I mean why it prints 21 particular ?



thank you  :)
Title: Re: for loop
Post by: TimoVJL on November 29, 2013, 12:31:17 PM
try this one:
#include<stdio.h>
int main(void)
{
for (int b = 0; b <= 5; b++) {
for (int a = 0; a <= b; a++)
printf("\t%d,%d",a,b);
printf("\n");
}
}
Title: Re: for loop
Post by: jj2007 on November 29, 2013, 02:59:34 PM
In case you still can't see it: 1*0+2*1+3*2+4*3=21
Title: Re: for loop
Post by: Bitbeisser on November 30, 2013, 02:34:30 AM
Well, expanding on timovjl's example, to make it even more clear:
#include<stdio.h>
int main(void)
{
int count = 0;
for (int b = 0; b <= 5; b++)
{
for (int a = 0; a <= b; a++)
{
printf("%2d:%2d,%2d\n",++count,b,a);
}
}
}
adding a counter for each output and reversing the output order of the loop variables...

Ralf