### For loops

I have a huge beginners problem here. I am currently working on for loops. I understand the three parts contained within a for loop; variable=something;compare variable to something (execute code block); update variable; compare variable to something again (as long as true execute code block); update variable and so on until condition evaluates false.....I get all that....Here is where my problem lies. Say I am given a problem that says print a triangle to the screen using for loops. That absolutely baffles me. I dont know why? I understand the concept of the for loop. I understand its parts but when asked to write a little code using it I am lost. My grey area lies between the problem to solve and the for loop implementation. Gosh....any help is greatly appreciated...I am at a university now and i really need to get this concept down. Thank you
I don't think the problem here is the for loop, rather it is the triangle. You need to understand what it is that you are trying to achieve, and see how it is structured, what rules you can identify to describe the triangle (or whatever it is). Only after you have thoroughly understood that, should you turn to the task of trying to write any code.
The sintaxis of for loop is following:
 ``12`` ``````for ( init-expression ; cond-expression ; loop-expression ) statement ``````

It can be represented using while loop:
 ``1234567`` ``````{ init-expression while(cond-expression){ statement loop-expression } }``````

If you understand while loops maybe this helps you. know, that you can omit any part of the for loop:
 ``123456789`` ``````for (; cond-expression;) statement //equals to: while(cond-expression) statement for(;;); //equals to while(true){}``````
Chervil---Thats it...I feel like you hit the nail on the head. Say I want to print a triangle to the screen that looks like this: (minus the /)
////// *
/////***
////*****

I first say in my mind " how do I break this up?" I have to account for the spaces in the first line then print a star....then I have to get to the next line account for those spaces and print three stars.....then finally get to the last line and print 5 stars....After this I get a brain cramp because I dont know where to start. I have to use for loops because thats what Dr. Professor said to do and rightfully so because he has us doing many other problems using for loops like write a calendar for example, and if I dont figure this out soon I will be a week behind. I really need to tear down this mental block I have with this. Thanks for you help
For loop is not the problem - You just need to understand the logic. Understand that you'd have to use two loops to print triangle (Sometimes even more to print some difficult shapes..). Say, if you want to print right angle triangle of size 5. You need to run the outer loop 5 times and inner loops 5,4,3,2,1 times..so this way it would print something like this
*****
****
***
**
*
I hope this helps.Its somewhat difficult concept but once you get hold of it you it will be quite easy.
awesome...can you expand a little on that?
Hey, Well I don't really know if this helps you but if you wanted it to be like that here it is.
 ``12345678910111213141516171819202122232425262728293031`` ``````#include using namespace std; int main() { cout << "Printing triangle!" << endl; int left=5; int right=5; for(int i=0; i<4; i++) { for(int j=0; j<10; j++) { if (j>=left && j<=right) { cout << "*" ; } else if(j>right) { cout <<"\\"; } else cout << "/"; } left--; right++; cout << endl; } return 0; }``````

Now, what I can suggest you is to watch what does change with each move, each time.
 ``` * *** *****```

When I look at a shape like this, I consider in terms of rows first of all. So I would have an outer for-loop going from 1 to 3 (or maybe 0 to 2). That's a kind of high-level consideration that doesn't take too much effort.

But then I look at each row. How many asterisks are there on each row? 1, 3, 5.
I see a progression there. A series of odd numbers, differs by 2 each time, so I think of an expression like 2*x.

Then how many spaces are there? 2, 1, 0. A progression which simply counts down.

Now the real trick is to try to find some way of relating these numbers to the loop counter of the outer loop.

I put this program together using a little bit of thinking, and I will admit, some trial and error. Years ago I would have planned it all out on paper and written code that would probably be correct first time. That's a good method, as you really get to understand in great detail how everything works. But it may take longer that way.

On the other hand, I see some code on these forums which uses repeated trial-and-error but never gets any closer to a solution. That's a sure sign that the design needs more thought and planning.
 ``123456789101112131415161718192021`` ``````#include using namespace std; int main() { int size = 10; for (int row = 0; row < size; row++) { for (int col = 1; col < size - row; col++) cout << ' '; for (int col = 0; col <= 2*row; col++) cout << '*'; cout << endl; } return 0; }``````

Of course there are many different ways to solve a problem. Sometimes students are required to do things a certain way, and not all methods may be acceptable. Using std::string for the asterisks and output manipulators to control the layout, it can be done like this. Here the key is the expression `size+row` which sets the width of each line and `2*row + 1` which specifies the number of asterisks.

 ``123456789101112131415`` ``````#include #include #include using namespace std; int main() { int size = 10; for (int row = 0; row < size; row++) cout << right << setw(size+row) << string(2*row + 1, '*') << endl; return 0; }``````
Last edited on
Try writing down the algorithm in words first, and do it as simple as possible to start with. For example, the following is also a triangle:
*
**
***
****
*****

So, how to print this. What do I need to do?
In the first iteration I need to print one *
In the second iteration I need to print two *
...
In the last iteration I need to print five *

Ok, but what does that mean:
In the first iteration I need to make a call to cout one time, if I place the call to cout in the inner loop that means I only want the inner loop to run once and then exit to the outer loop again.
In the second iteration, then I want the inner loop to run twice in order to make the call to cout twice.
This is where I start sensing a pattern (or maybe after a few steps more):

1:th time for outer loop -> 1 run of the inner loop. 2:nd time for the outer loop -> 2 runs of the inner loop.

This means I can probably use the counter for the outer loop in the condition for the inner loop.
Then try it, and if it does not behave correctly - go back and write down your thoughts step by step again.
 ``1234567`` ``````for (int outer = 0; outer < 5; outer++) { for(int inner = 0; inner < (outer+1); inner++) { cout << '*'; } }``````

It turns out this code only prints a straight line of *'s. I forgott to include the endl-prints. Where should I put them?

If put it in the inner loop, then there will be a new line before (or after) every print of a *. That's not what I want. So it must be in the outer loop and it should be the last thing I do after printing all the * on the current line. So I should place a call, cout << endl; , just before the outer loop starts a new iteration.
 ``12345678`` ``````for (int outer = 0; outer < 5; outer++) { for(int inner = 0; inner < (outer+1); inner++) { cout << '*'; } cout << endl; }``````

(I haven't compiled this so I can't say for 100% that it works as I expect)

That's how I think - more or less - when I break down problems, regardless if it is programming or math or whatever. Break it down and put words on what each step should include. Hope it it helps.
Last edited on
All of you have been a huge help with this. I really appreciate everything :) For this particular I can see the solution....I have many others to work on but using what you all have told me I should be able to work through it all.. Thanks again
Topic archived. No new replies allowed.