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.