News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

for loop

Started by nuha, November 29, 2013, 12:04:46 PM

Previous topic - Next topic

nuha

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  :)

TimoVJL

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");
}
}
May the source be with you

jj2007

In case you still can't see it: 1*0+2*1+3*2+4*3=21

Bitbeisser

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