The foreach Loop
A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace. The syntax of a foreach loop is
foreach (<type> <iteration variable> in <list>) { <statements> }.
The type is the type of item contained in the list. For example, if the type of the list was int[] then the type would be int.
The iteration variable is an identifier that you choose, which could be anything but should be meaningful. For example, if the list contained an array of people's ages, then a meaningful name for item name would be age.
The in keyword is required.
As mentioned earlier, the list could be either an array or a collection.
While iterating through the items of a list with a foreach loop, the list is read-only. This means that you can't modify the iteration variable within a foreach loop. There is a subtlety here; Later, you'll learn how to create custom types, called class and struct, that can contain multiple fields. You can change the fields of the class or struct, but not the iteration variable for the class or struct itself in a foreach loop.
On each iteration through a foreach loop the list is queried for a new value. As long as the list can return a value, this value will be put into the read-only iteration variable, causing the statements in the foreach block to be executed. When the collection has been fully traversed, control will transfer to the first executable statement following the end of the foreach block. Listing 4-4 demonstrates how to use a foreach loop.
Listing 4-4. The ForEach Loop: ForEachLoop.Cs
using System; class ForEachLoop { public static void Main() { string[] names = {"Cheryl", "Joe", "Matt", "Robert"};
foreach (string person in names) { Console.WriteLine("{0} ", person); } } }
In Listing 4-4, the first thing we've done inside the Main method is declare and initialize the names array with 4 strings. This is the list used in the foreachloop.
In the foreach loop, we've used a string variable, person, as the item name, to hold each element of the names array. As long as there are names in the array that have not been returned, the Console.WriteLine method will print each value of the person variable to the screen.
Variants task1
1) The moon’s gravity is about 17 percent that of the Earth. Write a program to display a table that shows Earth pounds and their equivalent moon weight. Make the table run from 1 to 100 pounds. Output a newline every 25 pounds.
2) The increment expression in a for loop need not always alter the loop control variable by a fixed amount. Instead, the loop control variable can change in an arbitrary way. With the help of this concept, write a program that uses a for loop to generate and display the progression 1, 2, 4, 8, 16, 32, and so on.
3) Write a program that reads in characters from the keyboard until a $ is typed. Have the program count the number of periods. Report the total at the end of the program.
4) Write a C++ program using a while statement to print n asterisks at the beginning of a new line.
5) Write a C++ program using a while statement to evaluate n!, i.e. 1*2*3*...*n, where 0! is 1.
6) Write a program that will add up all the integers from 1 to the integer that was scanned into the variable j. Store the sum in the variable called sum and use i to increment the integers from 1 to j. Print only sum. For example, if 5 were read into j, then sum would be 1 + 2 + 3 + 4 + 5 or 15. A sample output is given below.
---------Output----------------
Give an integer: 6
Sum of integers from 1 to 6 is 24.
7) Write a program that asks a user to type in all the integers between 8 and 23 (both included) using a for loop.
8) Use the following information to write a loop: (i=1; i <= count; i = i + 1). Write a program that will first read in a variable count as a data item, then many more data items and print their total. For example, if the data were 3, 40, 20, 50; count would become 3 and the sum of the following 3 data items would be calculated as 110.
9) Write a program that asks a user to type in all the integers between 8 and 23 (both included) using a while loop.
10) Write a program that asks a user to type in the value of N and computes N! with using for loop.
11) Write a program that asks a user to type in an integer N and computes the sum of the cubes from 53 to N3.
12) Write a program that asks a user to type in 10 integers and writes how many times the biggest value occur.
13) Write a program to produce the sum of the series where n is entered by a user.
14) Write a program to produce the sum of the series where n is entered by a user.
15) Write a program that will ask a user to give three integers. Call these integers start, step_by and stop. After these three integers are scanned in, set up the for-loop that will start i at the value of start, make it increase by the value given by step_by and make it stop at the value stored in stop. Print these values as shown in the following output sample.
-----------Output---------------
Enter three integers: 23 3 32
23 26 29 32
16) Use the following information to write a loop - (int i=1; i <= num; i++). Write a program that will first reads in a variable num as a data item, then many more data items and print their average. For example, if the data were 3, 30, 10, 50; num would become 3 and the average of the following 3 data items would be calculated as 30.
17) Write a program that asks a user to enter a value for n and finds value of expression 1*1+2*2+...+n*n.
18) Write a program that asks a user to enter a value for n and finds value of expression 1+2+...+n.
19) Write a program that asks a user to type in n integers and prints out a number of negative numbers and the numbers themselves on the next line.
20) Write a program to read in numbers until the number -999 is encountered. The sum of all number read until this point should be printed out.
21) Read in a positive integer value, and compute the following sequence: If the number is even, halve it; if it's odd, multiply by 3 and add 1. Repeat this procedure until the value is 1, printing out each value. Finally print out how many of these operations you performed.
22) Write a program that prints out the multiplication table for a value n.
-----------Output---------------
Enter a value: 5
1*5 = 5
2*5 = 10
……..
9*5 = 45
23)
Write a program that: 1) prints out the column for values from 20 to
35 (20 and 35 are included); 2) prints out the column for square
numbers of all integers from 10 to b (
).
24)
Write a program that: 1) prints out the column of third power for
values from a to 50 (a is printed from the keyboard,
);
2) prints out the column for all integers from c to b (c and b are
entered from the keyboard).
25) Write a program that prints out the column of numbers in the following form:
a) b)
10 10.4 25 25.5 24.8
11 11.4 26 26.5 25.8
.......… ………….
25 25.4 35 35.5 34.8
26) Write a program that prints out the column of numbers in the following form:
a) b)
21 19.2 45 44.5 44.2
20 18.2 44 43.5 43.2
.......… ………….
10 8.2 25 24.5 24.2
27) One item costs 30$. Write a program that prints out the cost’s column for 2, 3,…,20 items.
28) Write a program that converts a sum of money given as an integer number of pence into a floating point value representing the equivalent number of pounds. Print out the column of numbers for 4 to 20 (365 pence would be 3.65 pounds).
29) Write a program that converts a sum of money given as an integer number of dollars into grivnas and prints out a column of results. Currency converter must be entered from the keyboard.
30) Write a program that calculates y expression for x (x=4, 5,…,28):
.
