# Loops

• 10-23-2004
Dt7
Loops
I'm doing the beginners C++ tutorial on this site, and i was wondering what loops are actually used for in programs? I think I've figured out how to use them but i'm not sure what to use them for.
• 10-23-2004
Epo
Say I wanted to add up all the numbers from 0 to 10. I could do:
Code:

int main(void)
{
int Total = 0;

Total = Total + 1;
Total = Total + 2;
Total = Total + 3;
Total = Total + 4;
Total = Total + 5;
Total = Total + 6;
Total = Total + 7;
Total = Total + 8;
Total = Total + 9;
Total = Total + 10;

printf("The total from 0 to 10 is %d", Total);

return 0;
}

But, maybe I'd need the sum of all the numbers up to 100000. Now that could be a problem.

So, a loop would come in handy (either a For Loop or a While Loop) because it would take 100000 lines of code and condense it into:
Code:

int main(void)
{
int Total = 0;

for(int Counter = 0; Counter <= 100000; Counter++)
{
Total = Total + Counter;
}

printf("The total from 0 to 100000 is %d", Total);

return 0;
}

Or a similar While Loop.

Now, it's not every day you'll need to add up the numbers from 0 to 100000. But say you're reading a text file line by line, instead of writing out "fscanf..." an unknown number of times. You'd use a Loop with a condition that kicks you out once you reach the end of the file.

Loops are also good for initializing arrays of variables. For example. int MyArray[1000]. And I want everything to start off as 0. I hope you can see why a loop would be useful.

There are tons of uses for them though, much deeper than the examples above. Pretty much any time you need to repeat code, a loop will handle the job for you nicely with a limited amount of stress.
• 10-23-2004
Prelude
>i'm not sure what to use them for.
You use them for doing the same thing over and over. When you need to do something over and over, a loop might be in order. :)
• 10-23-2004
Xipher
And it is quite common to be doing the same thing over, and over, and over. There are alot of programs that just sit in one continous loop all the time (games for one). Also, many servers (such as HTTP,FTP) will use a loop of something like (in pseudo code)
Code:

Listen for incoming connection
recieve connection
send any needed info for the client to get started
loop starts here
get command from client
process command