Loop learning

I am having a hard time learning loops. Like i know what every loop does but it's really tough for me to implement them to my programs..

So if you have any suggestions on how can I learn loops easier, please let me know by posting here :D

Thanks :D
Well, you are going to have to put the time in to get comfortable with them. (Seriously, it's the only way)

for loops are best when you no exactly how many times you want it to loop. You can also use several conditions and initialiaztions to make them a bit more complex.

For example:

for (bool valid = false, int i = 0; i < 10 and !valid; i++)

This loop will execute 10 times or until you set the bool valid to be true.

Do while loops are generally unnecessary and can be replaced with a while loop. While loops are great for when you are unsure about how many times you want the loop to run for.

You usually need to prime a while loop, especially for input.




Last edited on
closed account (zb0S216C)
If integrating loops into your programs is a struggle, know this: Loops can be broken down into at least two categories (possibly more):

- While something isn't yet complete
- Iterate through an array

I'll exemplify both here:

While something isn't yet complete: For example, say you had a variable that holds the current amount of seconds elapsed since the initial execution of the program, and you wanted to do something specific while the amount of seconds isn't at a certain value.

1
2
3
4
while(seconds_elapsed < 60)
{
    // Invoke functions...
}

Iterate through an array: For example, say you had an array of n integers, and you were looking for the value of x. You would iterate through the array until you found it, like so:

1
2
3
for(unsigned int item_offs(0U); item_offs < 10U; ++item_offs)
    if(my_array[item_offs] == 100)
        break;

Each loop construct is good for something. It's your job, as a coder, to determine which loop is most suitable for the task in hand.

Wazzak
Last edited on
Topic archived. No new replies allowed.