ah, the single loop was not so bad with the extra variable. I was thinking of the one liner for loop when I said it was messy.
I don't know of a guide that will tell you the big picture so I will give you a short crack at it:
1) there are several kinds of loops, 4 types with variations on those.
2) the 4 kinds of loops are all interchangeable. The only reason there are 4 types is to make it easier to express the code.
the 4 types are: while, for, do-while, and ranged-for.
when to use them, in simple terms:
the while loop is used when you want to loop 0 or more times and all you need is one condition.
while(something < 10) for example. if something is 42, it will not enter the loop body at all, it will just skip it, because it is not less than 10.
the for loop is used when you need to control a variable as part of the activity. Your problem is a good example -- its a form of a multiplication table. Consider the multiples of 5, for example:
for(int i = 5; i <= 100; i+=5) //5,10,15,20,25,... 100. This is the most complex loop type: you can set up multiple variables and the action on the end does not *have* to just control the loop variables but can also do the work of the loop. This gets ugly and hackity looking in a hurry so use this power judiciously so that your code is still easy to read and maintain etc. You can put that information aside for now, but be aware of it because someday you will need to do this.
the do-while forces the loop body to execute once. It is a great tool for things like getting user input and making them enter the value again and again if they are not putting in valid responses.
1 2 3 4 5
|
do
{
cout << "enter something\n"; //this always happens once
cin >> response; //this always happens once
} while( !isvalid(response); //and they will happen again if condition is not met.
|
the do-while is messy to replace with other loop types because you have to 'seed' the 'happens one time no matter what' part.
the above as a for loop:
//do it one time out of the loop
cout << "enter something\n"; //this always happens once
cin >> response; //this always happens once
for(; !isvalid(response);) //if the response is no good, loop until they get it right
{
cout << "enter something\n"; //this always happens once
cin >> response; //this always happens once
}
if you find yourself doing it once outside the loop and again inside, then you should have used the do-while.
the ranged based for loop is used with containers, to touch every item in them. You can ignore this type for now, and an example would take more explaining than I care to do right now assuming you have not even seen a vector yet...