This code:
for (unsigned int i=1;i<=counter;++i)
{ printf("The i is %d and the sum is %d\n",i,sum1);
sum1 =0;// 2 iteration sum =0;
printf("The i is %d and the sum is %d\n",i,sum1);
for(unsigned int j=1;j<=i;++j)
sum1 =sum1+j;// 1 iteration sum=1;
printf("The i is %d and the sum is %d\n\n",i,sum1);}
is equivalent to:
for (unsigned int i=1;i<=counter;++i) {
printf("The i is %d and the sum is %d\n",i,sum1);
sum1 =0;// 2 iteration sum =0;
printf("The i is %d and the sum is %d\n",i,sum1);
for(unsigned int j=1;j<=i;++j) {
sum1 =sum1+j;// 1 iteration sum=1;
}
printf("The i is %d and the sum is %d\n\n",i,sum1);
}
This is because in for-loop
s without braces, only the very next line is included in the loop.
Now in the first iteration, you will get:
"The i is 1 and the sum is 0"
"The i is 1 and the sum is 0"
"The i is 1 and the sum is 1" //Enters inner for-loop
Second:
"The i is 2 and the sum is 1" //Hasn't reset yet
"The i is 2 and the sum is 0" //Reset
"The i is 2 and the sum is 3" //Sum was 0, then added 1 when j was 1,
//then added 2 when j was 2
Now, the reason you can't print j, is because your printf
statements are all outside of your inner for-loop
, so j
is not defined :)