Originally Posted by
blackwolf
which type of loop would i use to achieve that?
It depends on your goal, but I would suggest a while loop.
at the moment there seems to be so many different ways to code the exact same thing, some more efficient then others.
There is a reason for this, and it is because each loop has something different to offer.
To be clear, the basic loop structure is while. Once you understand how it works, then you can make literally every loop into a while if you wanted.
do-while's claim to fame is that it will run exactly once. This is because of the body, which appears first, is also executed first, then the condition is checked. So, say your goal was to generate a number between 1 and 100. Well, you know that you will need to call rand() at least once, so this could lead to code like:
Code:
// Call rand() repeatedly until we get a number we want.
do {
result = rand();
} while (result < 1 || result > 100);
(Advantage of this is that it works with rand()'s actual period to get a number, at the cost of time, instead of faster smooshing of the result, which is often implemented poorly. See here. )
When you write enough while loops, you begin to notice a pattern:
Code:
size_t i = 0; // initialize a starting point
while ( i < arrayN ) { // work until this is satisfied
printf("array[%2d] = %d\n", i, array[i]);
++i; // update your initial variable
}
This is a pattern that happens frequently in code. You are either counting something, or maybe something needs to be done at every step along the way (for some vague notion of a step.) The for loop was invented to highlight this in the first line and leave the actual work in the body.
Code:
for (size_t i = 0; i < arrayN; ++i) {
printf("array[%2d] = %d\n", i, array[i]);
}
Eventually when you get used to programming a little bit, you will focus on writing the easiest loops to read. You will notice what you are doing and be able to choose between while and for and do-while. But if you write a while because it's easy, no one is going to be too bothered by it. They might just show you the format they would have used instead.
I'm sure this is covered in other places like the tutorials, but maybe this helped a little more.