NO

Author Topic: for loop  (Read 2415 times)

nuha

  • Guest
for loop
« 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  :)

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Re: for loop
« Reply #1 on: November 29, 2013, 12:31:17 PM »
try this one:
Code: [Select]
#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

Offline jj2007

  • Member
  • *
  • Posts: 536
Re: for loop
« Reply #2 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

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: for loop
« Reply #3 on: November 30, 2013, 02:34:30 AM »
Well, expanding on timovjl's example, to make it even more clear:
Code: [Select]
#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