
Originally Posted by
PhantomJoe
I know I need to incorporate the logic you laid out to get the correct number of asterisks (row*2-1) but because I'm unsure of how to implement that I've just been trying to insert it in different places in the inner loop.
In the below example I've used it in the inner loop in the test condition portion and that produces an infinite loop.
Code:
int main()
{
int row;
int col;
for (row = 1; row <= 4; row++) //rows
{
for (col = 1; col = row*2-1; col++) //columns
{
printf_s("*");
}
printf_s("\n");
}
return 0;
}
When I use it in the initiate location of the inner loop I get just a single asterisk (code below):
Code:
int main()
{
int row;
int col;
for (row = 1; row <= 4; row++) //rows
{
for (col = row*2-1; col <= row; col++) //columns
{
printf_s("*");
}
printf_s("\n");
}
return 0;
}
I also want to say thank you for your help and I'm trying to not get frustrated but as this is my first ever exposure to programming I sometimes feel like I'm in over my head.
I think you are doing just fine, in the above example you are just mistaking the loop condition:
Code:
for (col = 1; col = row*2-1; col++)
The '=' is the assignment opeartion, that means that your condition is an assignment. Remember '=' is not the same as '=='
'=' : Assignment.
'==' : Equivalence operator.
Code:
int a;
// Assign 3 to a
a = 3;
// Compare 3 to a
a == 3; // This returns true or false (a boolean expression).
As you know, considering you've done the above code, when you printed asterisks before, this was your condition:
Code:
for(col = 1; col <= row; col++)
Here, when row = 1, then:
Code:
col = 1
col <= row?
1 <= 1 >> TRUE
enter loop
print asterisk
col = col + 1 (col++)
col = 2
col <= row?
2 <= 1 >> FALSE
exit loop
Ammount of asterisks printed: 1
I think you can see that everytime row increases, then there is an additional asterisk printed.
Our example when looping "against" the condition 2*row-1 is the same as the example above.
As for your second code, see that:
Code:
for (col = row*2-1; col <= row; col++)
You are mistaking the condition, which refers to the ammount of asterisks to print depending on what the row is (this is the function that generalizes to 2n-1 where n is row qty), with the initial value to start looping!
Code:
for(initial value; condition; increment)*
- The initial value will be set only at the start of the loop (not of EVERY iteration).
- The condition will be looked upon after every iteration, if true then the loop continues, if false then we exit the loop.
- The increment is used to increment the value, so that the value in the condition CHANGES, if it does not, then the condition will always remain TRUE, because it is the same condition as before.
(*): This explanation is not general for every for loop but to the ones used by the OP.
If you have doubts with anything that I tried to explain please feel free to ask again.