### Having problems understanding loops

closed account (iAk3T05o)
Like the title says, i'm having problems understanding loops (do, for and while).
I joined this forum days ago to ask for help on a coding problem but luckily, i figured it out all by myself :). I am using the pdf tutorial of this site and i understand how to use everything in the tutorial before loops. I've even made a kind of game (or q&a) program depending on how you look at it.:) If i don't get this, it could disrupt my learning because of the way i'm learning. I read on a new topic in the pdf (say stringstream) and then make a new console project using vc++. I then use the new topic + the old topics to make a bigger program with more functionality and make sure it works or don't learn anything else and this helps me understand the concepts. All i know about loops is that it repeats stuff. My question now is what are loops for. Can you show me a program using loops. What purpose do/could they serve in a program. What purpose could they serve in a game and game engine (i'm learning c++ for these). Thanks
Last edited on
Example:
If you have a list of items, you will not know the actual size of the list before you are running the program, and you have to do the same operation for each of the items, then a loop is quite necessary.
Loops are extremely important and you'll naturally start needing them while you go through tutorials. For example here's a simple game that has you guess a random number. Don't concentrate on how it works, just think of the logic of the loop. Why is the loop needed? It needed to keep getting input from the user.
 ``12345678910111213141516171819202122232425262728`` ``````#include // cout, cin #include // srand, rand #include // time using namespace std; int main () { int iSecret, iGuess; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; do { cout << "Guess the number (1 to 10): "; cin >> iGuess; if (iSecretiGuess) cout << "The secret number is higher" << endl; } while (iSecret!=iGuess); cout << "Congratulations!" << endl; return 0; }``````

We can edit this code to make the game restart automatically so you can play again. Just put another loop in.

 ``123456789101112131415161718192021222324252627282930313233`` ``````#include // cout, cin #include // srand, rand #include // time using namespace std; int main () { int iSecret, iGuess; char ans; /* initialize random seed: */ srand (time(NULL)); do { /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; do { cout << "Guess the number (1 to 10): "; cin >> iGuess; if (iSecretiGuess) cout << "The secret number is higher" << endl; } while (iSecret!=iGuess); cout << "Congratulations! Play again? (y/n)" << endl; cin >> ans; } while('y' == ans); return 0; }``````

As keskiverto said, you may also need loops to iterate through lists. Have you studied arrays yet? Say you want to find the prime factors of a natural number. You'll need a couple loops for this:

 ``1234567891011121314151617181920212223242526272829303132333435363738`` ``````#include #include using namespace std; int main() { long num, i; bool again = true; do { i = 2; cout << "Enter in a natural number: "; cin >> num; int maxsize = static_cast(sqrt(num)); int array[maxsize]; int currentsize = 0; cout << "The prime factors are: "; while (i < num) { if (num % i == 0) { array[currentsize] = i; currentsize++; num = num / i; } else i++; } array[currentsize] = i; currentsize++; for(int i=0; i

The do-while loop keeps the program running so you can try as many numbers as you'd like. The while loop is the one that finds all the prime factors. The for loop iterates through the array that stores all the prime factors and outputs it.
closed account (iAk3T05o)
@Dem7w2: thanks a lot. I think i now understand do loops but i'll need more practice.
I only understand the first two code examples. I know of everything in the first two code examples except the #include <stdlib.h>, <time.h>, srand and NULL. I'll learn them when i get there.
I haven't learned arrays yet so the last code example is confusing. Don't tell me what arrays do as it the next topic after loops and i'll like to learn it by myself. If then i don't understand, i'll ask (no offence) :).
What of for loops. (without arrays).
Last edited on
Here's a simple example that helps explain the difference between the different loop types.

This simple for loop creates 5 stars. The first part of the for loop dictates the variable used to control the loop, in this case i. The second part says that the loop operates as long as i>0, and the third says to lower the value of i after each time the loop is executed. Note that the three parts are separated by semicolons, not commas.
 ``1234`` `````` int stars=5; for (int i=stars;i>0;i--) cout<<"*";``````

The while loop and do/while loop are more similar to each other. This while loop does the same thing as the previous for loop, and continues to repeat as long as stars>0.
 ``1234567`` `````` int stars=5; while(stars>0) { cout<<"*"; stars--; }``````

Lastly, the do/while loop works the exact same as the while loop, except for the fact that the first time it will run even when the condition specified is not true. The condition, in that case, only dictates when the loop should repeat.
 ``1234567`` `````` int stars=5; do { cout<<"*"; stars--; } while (stars>0);``````

All three loops shown here will result in the same behavior. Depending on what you are attempting, you may find it easier to use a particular type of loop in your program. It is fairly common to use loop types together, so for loops tend to use other for loops inside them, and while loops tend to use while loops inside them. Nested loops and the concept involved can seem confusing when trying to grasp the basics, but here's a simple example of the potential uses of double loops.
 ``123456789101112`` `````` int stars=5; //outer loop for (int j=0;j<5;j++) { //inner loop for (int i=stars;i>0;i--) cout<<"*"; //outer loop commands cout<

Here, you can see that the inner loop is used to output stars, while the outer loop is used to alter the quantity of stars and ensure the next execution of the loops occur on the next line.

Lastly, there's another couple important details about loops. You can set the condition used to control the loop to true or 1 to have it run no matter what.
 ``12345`` `````` while (true) { cout<<"*"; }``````

Now, you would probably ask why anyone would want to do that, but there's another convenient feature; the ability to break out of the loop when desired. Here's a simple example so you can see how I broke out of the loop after ten stars.
 ``123456789`` `````` int count=0; while (true) { cout<<"*"; count++; if (count==10) break; }``````

There is more to learn, but this covers the basics and involves examples simple enough for a beginner to grasp. Hopefully it helps.
Last edited on
Topic archived. No new replies allowed.