This lab serves multiple goals:
- To introduce you to
foreach
loops, - To introduce you to their use cases,
- To compare
for
loops andforeach
loops by converting between them, and - To illustrate how
foreach
can be useful in conjunction with classes.
Practicing foreach
Loops
Warm-up
Create a new project, and replace the content of the Main
method with
the following code:
Execute the code. You should see the elements of the array primes (the prime numbers less than 20) in the console.
Next rewrite the code using a foreach statement, then answer the following questions:
- Identify two differences between the
for
andforeach
versions. - Which one is easier to understand?
- Which one needs fewer variables?
Answers:
The code simply becomes:
- The differences are the keyword (obviously!), the fact that
foreach
does not need indices nor to use theLength
property, and the absence of an update or condition in the header. - This is a matter of taste, but
foreach
generally seems more intuitive. - Both use one additional variable (
i
in thefor
case,val
in theforeach
case).
Converting from for
to foreach
(1/2)
Can you rewrite the following code with a foreach
statement? Why?
Converting from for
to foreach
(2/2)
Can you rewrite the following code with a foreach
statement? Why?
Conversion between for
and foreach
- Can you think of any loops that can be implemented with foreach but not with for? If so, write an example.
- Can you think of any loops that can be implemented with for but not with foreach? If so, write an example.
Mixing foreach
With Classes
Download the Library project, extract it, and open it with your IDE.
Observe the program and its two classes:
- The
Book
class represents a single book. Program
creates an array of 10 books.
Next modify the code in Program.cs
to perform the following steps:
- Write a
foreach
loop that displays all the books. - Add statements where you ask the user to enter a year, then modify
the
foreach
loop to display only books published on or after the year the user entered. - Write a
for
loop implementation that performs the same task of displaying books published on or after the year user entered.
Which one do you prefer to implement the above search? Explain your answer.