Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

The foreach Loop

Читайте также:
  1. The foreach statement

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 foreach loop.

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):

.

TASK2

(make use of the information from Lesson 3)

1) A student has a percentage mark for an examination. These marks should be converted to grades as follows:

>=70 'A', 60-69 'B', 50-59 'C', 40-49 'D', 30-39 'E', <30 'F'

Write a C++ program. Use a switch statement to directly assign the appropriate grade given a percentage mark.

 

2) A student can get a grade from 'A' to 'F' for a test. Assign the following marks to these grades, 10 for 'A', 8 for 'B', 6 for 'C', 4 for 'D', 2 for 'E' and 0 for 'F'.

 

3) Using the case operator, write a C++ program. Input data should be typed in from the keyboard. Find the reminder after dividing x by 3. Calculate y:

 

4) Write a program that is able to compute some operations on an integer. The program writes the value of the integer and the following menu:

1. Add 1

2. Multiply by 2

3. Subtract 4

4. Quit

The program should ask a user to type in a value between 1 and 4. If the user types in a value from 1 to 3 the operation is computed, the integer is written and the menu is displayed again. If the user types 4, the program quits.

 

5) Write a C++ program which asks a user to enter x and y numbers. Then he/she should enter one of the symbols: +, -, *, / and the program should output the result of that operation.

 

6) Read in an integer value (m, ). Assume that it is the number of a month of the year; print out the name of that month.

 

7) Read an integer value (w, ). Assume that it is the number of a day of the week; print out the name of the day.

8) Read in an integer value (s, ). Assume that it is the number of a season of the year; print out the name of the season.

 

9) Write a C++ program employing the case operator. Input data should be typed in from the keyboard. Calculate the total area of geometric figure.

 

10) Read in an integer value (d, ). Assume that it is the number of a month of the year; print out the number of days of the month.

 

11) Write a program that reads in the first letter of the week day from the screen and prints out the name of the day.

 

12) Write a program that reads in the first letter of the month from the screen and prints out the name of the month.

 

13) Write a program that performs the following: if the value of letter (that is printed by a user) is 'A', 'E', 'I', 'O' or 'U' then numberofvowels is incremented. If the value of letter is ' ' (a space) then numberofspaces is incremented. If none of these is true then the default condition is executed, that is numberofconstants is incremented.

 

14) Write a C++ program employing the case operator. Input data should be typed in from the keyboard. You have sequence of symbols: 'a', 'b', 'c', 'd', 'e', 'v', 'x', '.', ',', ':'. Classify this symbols into:

vowels;

consonant;

punctuation marks.

Type in a symbol from the keyboard. Display the symbol and his group.

 

15) Write a C++ program which classifies symbols into:

Latin letters;

numbers;

brackets.

 

16) Write a C++ program to analyze the coordinates entered by a user. Find their location on yje plane and show a message: “coordinate point lies in the 1st quarter (X and Y - positive)”, … 'coordinate point lies in the 4th quarter (X and Y - negative)', ' coordinate point is on the X axis', etc.

 

17) Write a C++ program which will ask a user to enter a number, for example ‘244’ and will output a text ‘two four four’.

 

18) Write a program that asks a user to type in a name and prints out person’s detail (cell number, address, and nickname). Provide the information about 5 different people.

 

19) Write a program to show yuor scheduale for a day. It should ask a user to type in the time of the day and prints out particular note. Prepare additional conditions for the time that is not in the list.

 

20) Write a program that asks a user to type in a name of a student and prints out the debts for particular one. Prepare additional condition for names that are not in the list.

 

21) Write a C++ program employing the case operator. Input data should be typed in from the keyboard. ;

 

22) Write a program that prints the insurance fee to pay for a pet according to the following rules:

A dog that has been neutered costs $50.

A dog that has not been neutered costs $80.

A cat that has been neutered costs $40.

A cat that has not been neutered costs $60.

A bird or reptile costs nothing.

Any other animal generates an error message.

The program should prompt the user for the appropriate information, using a code to determine the kind of an animal (i.e. D or d represents a dog, C or c represents a cat, B or b represents a bird, R or r represents a reptile, and anything else represents some other kind of an animal). After printing the insurance fee, the program should ask the user if (s)he wants to insure another animal.

 

23) Write a C++ program which will ask a user to enter a text, for example ‘four two three’ and which will output a number ‘423’.

 

24) A company pays to its employees according to different schedules. All employees are paid an annual salary. Type 0 employees get paid every week. Type 1 employees are paid twice a month. Type 2 employees are paid once a month. Write a program that calculates the salary paid to each employee.

 

25) Write a program that calculates how much money (tips) you can give for the service. We suggest 20% of the food cost for a good service; 15% of the food cost for a bad service.

 

26) Write a program that uses a switch statement to examine the number of days for months containing less than 31 days.

 

27) Write a program that asks a user to enter the number of a month of the year and the year. For example, if the user wants to enter June, 2005, he/she would enter 6 and then 2005. The program should then display the number of days in the month. Be sure to take leap years into account.

 

28) Write a program to help balance user’s money market checking account. The program should start by asking a user for the month's opening account balance. Then it should display a menu listing the following choices: D for a deposit, C for a check, W for a withdrawal, and Q for quit. If the user selects D, ask the user to enter the amount of the deposit, and add the amount to the account balance. If the user enters C, ask the user for the amount of the check, and subtract the check amount from the balance. If the user enters W, ask the user for the amount of the withdrawal, and subtract the amount from the balance. When the user enters Q, the program should display the opening balance, the total amount deposited, the total amount withdrawn, the total amount of the checks, and the final balance. If the user enters something other than D, W, C, or Q, the program should issue an error message and redisplay the menu. Allow the user to enter either uppercase or lowercase letters.

 

29) A commodities broker requires a program to calculate brokerage commissions. Write a program that asks a user if the transaction was a sale or a purchase and then requires for the amount of the transaction. The program should then ask where the transaction was made. The user should enter E for the Commodity Exchange, C for the New York Cotton Exchange, or M for the Mercantile Exchange. If the amount was a sale, and was made at the Commodity Exchange, the commission rate is 5.0% of the amount. If a sale is made at the New York Cotton Exchange, the commission rate is 3.7% of the amount. If a sale is made at the Mercantile Exchange, the commission rate is 4.2% of the amount. If the transaction was a purchase at the Commodity Exchange, the rate commission is 6.3% of the amount. If a purchase is made at the Cotton Exchange, the commission rate is 4.3% of the amount. If a purchase is made at the Mercantile Exchange, the commission rate is 5.7% of the amount. The program should process any number of transactions.

 

30) Your city's Parking Violation Bureau wants you to write a program to compute fines for parking violations. There are four types of violation: type A claims a fine of $10, type B claims a fine of $20, type C claims a fine of $30, and type D claims a fine of $50. The program should ask for the number of the type A violations, the number of the type B violations, and so on. If the number of A, B, or C violations exceeds 10, impose an additional fine of $50 for each category that exceeds 10. If the total number of A, B, or C violations exceeds 20 but none of A, B, or C individually exceeds 10, impose an additional fine of $75. If the number of D violations exceeds three, impose an additional fine of $20 for each D violation over three. The program should display the total fine for a person and any number of people.

 


Дата добавления: 2015-11-14; просмотров: 45 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Listing 4-2. The Do Loop: DoLoop.cs| Предмет та основні поняття інформатики

mybiblioteka.su - 2015-2024 год. (0.034 сек.)