Many things in computing can be difficult to get your head round to start with: it needs your to think in a different, more analytical way than you are probably used to (For some, it's the first time they have ever had to actually
think and they have even worse problems than you do!)
Loops are pretty simple, really - they are just a way of doing the same thing many times. For example, you are reading a book to learn about C# - so the process is:
1) Open the book at the start of chapter 6
2) Read the page.
3) Turn to the next page.
4) Is that the end of the chapter?
4.1) No - go back to 2.
4.2) Yes - you have finished chapter 6, now do the exercises.
That's simple - it's something you do every day: reading a chapter (or part of a chpter perhaps).
In computer terms, it's the same thing:
1) Initialize the loop - Open the book at the start of chapter 6
2) Body of the loop - Read the page.
3) Prepare for next iteration - Turn to the next page.
4) Check for completion - Is that the end of the chapter?
4.1) No - Loop round again - go back to 2.
4.2) Yes - Exit the loop - you have finished chapter 6, now do the exercises.
We can write that as a C#
for
loop:
for (int pageNo = chapterStart[5]; pageno < chapterstart[7]; pageNo++)
{
ReadPage(pageNo);
}
Or a
foreach
loop:
foreach Page page in Chapters[6])
{
page.Read();
}
Or a
while
loop:
int pageNo = chapterStart[5];
while (pageno < chapterstart[7])
{
ReadPage(pageNo++);
}
Or even a
do ... while
loop:
int pageNo = chapterStart[5];
do
{
ReadPage(pageNo++);
} while (pageno < chapterstart[7]);
THink about that for a moment, and it may be a little clearer - try comparing loops to "real world" events, and you'll find they are a pretty good match in most cases!