Search This Blog

Monday, January 10, 2011

c# part 4

Lesson 4: Control Statements - Loops
The information in this lesson will teach you the proper way to execute iterative logic with the various C# looping statements. Its goal is to meet the following objectives:
  • Learn the while loop.
  • Learn the do loop.
  • Learn the for loop.
  • Learn the foreach loop.
  • Complete your knowledge of the break statement.
  • Teach you how to use the continue statement.

C# Simple Loops

looping is very necessary because it relieves the programmer from time consuming tasks. Developers are able to execute statements repeatedly millions of times if they need to. Tedious calculations can also benefit from loops as well. Lets see how loops can make our job easier.
Lets print the numbers from 1 to 10
Example 1:
using System;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(1);
        Console.WriteLine(2);
        Console.WriteLine(3);
        Console.WriteLine(4);
        Console.WriteLine(5);
        Console.WriteLine(6);
        Console.WriteLine(7);
        Console.WriteLine(8);
        Console.WriteLine(9);
        Console.WriteLine(10);

        Console.Read();
    }
}
Output
1
2
3
4
5
6
7
8
9
10
A grueling way to print from 1 to 10. Lets examine a more efficient way to do basic counting using goto.
Example 2
using System;
class Program
{
    static void Main(string[] args)
    {
        int x = 0;

    LoopLabel:
        x += 1;     //Equivalent to x = x + 1
        Console.WriteLine(x);

        if (x < 10) //if x is less than 10 then goto LoopLabel
            goto LoopLabel;

        Console.Read();
    }
}
Output:
1
2
3
4
5
6
7
8
9
10
This is a much more efficient way to count from 1 to 10 or even a thousand or 1 million

The while Loop
A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a Boolean value of true. Its syntax is as follows:
while (<boolean expression>) { <statements> }.
OR
while(''condition'')
{
     <code to be executed if ''condition'' is true>
}
The statements can be any valid C# statements. The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the while loop to check the boolean expression again.
When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state. During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to. Listing 4-1 shows how to implement a while loop.
Listing 4-1. The While Loop: WhileLoop.cs
using System;

class WhileLoop
{
    public static void Main()
    {
        int myInt = 0;

        while (myInt < 10)
        {
            Console.Write("{0} ", myInt);
            myInt++;
        }
        Console.WriteLine();
    }
}
Listing 4-1 shows a simple while loop. It begins with the keyword while, followed by a boolean expression. All control statements use boolean expressions as their condition for entering/continuing the loop. This means that the expression must evaluate to either a true or false value. In this case we are checking the myInt variable to see if it is less than (<) 10. Since myInt was initialized to 0, the boolean expression will return true the first time it is evaluated. When the boolean expression evaluates to true, the block immediately following the boolean expression will be executed.
Within the while block we print the number and a space to the console. Then we increment (++) myInt to the next integer. Once the statements in the while block have executed, the boolean expression is evaluated again. This sequence will continue until the boolean expression evaluates to false. Once the boolean expression is evaluated as false, program control will jump to the first statement following the while block. In this case, we will write the numbers 0 through 9 to the console, exit the while block, and print a new line to the console.
The do Loop
A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time. On the other hand, a while loop evaluates its boolean expression at the beginning and there is generally no guarantee that the statements inside the loop will be executed, unless you program the code to explicitly do so.
Example.
The following example will increment x at least one time. It will continue to increment x until the condition is false.
using System;
class Program
{
    static void Main(string[] args)
    {
        int x = 0;
        do
        {
            ++x;
        } while (x < 10);
        Console.WriteLine(x);
        Console.Read();
    }
}
One reason you may want to use a do loop instead of a while loop is to present a message or menu such as the one in Listing 4-2 and then retrieve input from a user.
Listing 4-2. The Do Loop: DoLoop.cs
using System;

class DoLoop
{
    public static void Main()
    {
        string myChoice;

        do

       {
            // Print A Menu
            Console.WriteLine("My Address Book\n");

            Console.WriteLine("A - Add New Address");
            Console.WriteLine("D - Delete Address");
            Console.WriteLine("M - Modify Address");
            Console.WriteLine("V - View Addresses");
            Console.WriteLine("Q - Quit\n");

            Console.WriteLine("Choice (A,D,M,V,or Q): ");

            // Retrieve the user's choice
            myChoice = Console.ReadLine();

            // Make a decision based on the user's choice
            switch(myChoice)
            {
                case "A":
                case "a":
                    Console.WriteLine("You wish to add an address.");
                    break;
                case "D":
                case "d":
                    Console.WriteLine("You wish to delete an address.");
                    break;
                case "M":
                case "m":
                    Console.WriteLine("You wish to modify an address.");
                    break;
                case "V":
                case "v":
                    Console.WriteLine("You wish to view the address list.");
                    break;
                case "Q":
                case "q":
                    Console.WriteLine("Bye.");
                    break;
                default:
                    Console.WriteLine("{0} is not a valid choice", myChoice);
                    break;
            }

            // Pause to allow the user to see the results
            Console.Write("press Enter key to continue...");
            Console.ReadLine();
            Console.WriteLine();
        } while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit
    }
}
Listing 4-2 shows a do loop in action. The syntax of the do loop is
do { <statements> } while (<boolean expression>);.
The statements can be any valid C# programming statements you like. The boolean expression is the same as all others we've encountered so far. It returns either true or false.
In the Main method, we declare the variable myChoice of type string. Then we print a series of statement to the console. This is a menu of choices for the user. We must get input from the user, which is in the form of a Console.ReadLine method which returns the user's value into the myChoice variable. We must take the user's input and process it. A very efficient way to do this is with a switch statement. Notice that we've placed matching upper and lower case letters together to obtain the same functionality. This is the only legal way to have automatic fall through between cases. If you were to place any statements between two cases, you would not be able to fall through.
The for Loop
A for loop is a much better way to loop through statements then the previous techniques. using the goto statement breaks the flow of the program and can get very confusing when nesting goto loops. The for loop loops a certain number of times which is defined in the for loop declaration.
 
A for loop has its own internal counting system but the programmer must declare and initialize the loop variables.
 
for(<initialization>; <condition>; <increment>)
{
     //code to loop through
}
Example.
1.       using System;
2.       class Program
3.       {
4.           static void Main(string[] args)
5.           {
6.               for (int x = 0; x <= 10; ++x)
7.               {
8.                   Console.WriteLine(x);
9.               }
10.          Console.Read();
11.      }
12.  }
Line 6: This line is where the counting operations take place.
·            int x = 0 is where x is initialized
·            x <= 10 says continue to loop while x is smaller than or equal to 10. If this statement were absent the loop would never stop.
·            ++x is equivilant to x = x + 1. It simply increments x by 1.
Loops that are used to count from 0 to 10 you should use x <= 10 because x < 10 produces an "off by one error". Instead of counting from 0 to 10, x < 10 will count from 0 to 9.

Question:
what is (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15)
Before we give you the answer try solving this yourself.
Answer:
using System;
class Program
{
    static void Main(string[] args)
    {
        int sum = 0;

        for (int x = 0; x <= 15; ++x)
        {
            sum += x;   //Equivalent to sum = sum + x
        }
        Console.WriteLine(sum);
        Console.Read();
    }
}
A for loop works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons
(<initializer list>; <boolean expression>; <iterator list>) { <statements> }
The initializer list is a comma separated list of expressions. These expressions are evaluated only once during the lifetime of the for loop. This is a one-time operation, before loop execution. This section is commonly used to initialize an integer to be used as a counter.
Once the initializer list has been evaluated, the for loop gives control to its second section, the boolean expression. There is only one boolean expression, but it can be as complicated as you like as long as the result evaluates to true or false. The boolean expression is commonly used to verify the status of a counter variable.
When the boolean expression evaluates to true, the statements within the curly braces of the for loop are executed. After executing for loop statements, control moves to the top of loop and executes the iterator list, which is normally used to increment or decrement a counter. The iterator list can contain a comma separated list of statements, but is generally only one statement. Listing 4-3 shows how to implement a for loop. The purpose of the program is to  print only odd numbers less than 10.
Listing 4-3. The For Loop: ForLoop.cs
using System;

class ForLoop
{
    public static void Main()
    {
        for (int i=0; i < 20; i++)
        {
            if (i == 10)
                break;

            if (i % 2 == 0)
                continue;

            Console.Write("{0} ", i);
        }
        Console.WriteLine();
    }
}
Normally, for loop statements execute from the opening curly brace to the closing curly brace without interruption. However, in Listing 4-3, we've made a couple exceptions. There are a couple if statements disrupting the flow of control within the for block.
The first if statement checks to see if i is equal to 10. Now you see another use of the break statement. Its behavior is similar to the selection statements, as discussed in Lesson 3: Control Statements - Selection. It simply breaks out of the loop at that point and transfers control to the first statement following the end of the for block.
The second if statement uses the remainder operator to see if i is a multiple of 2. This will evaluate to true when i is divided by 2 with a remainder equal to zero, (0). When true, the continue statement is executed, causing control to skip over the remaining statements in the loop and transfer back to the iterator list. By arranging the statements within a block properly, you can conditionally execute them based upon whatever condition you need.
When program control reaches either a continue statement or end of block, it transfers to the third section within the for loop parentheses, the iterator list. This is a comma separated list of actions that are executed after the statements in the for block have been executed. Listing 4-3 is a typical action, incrementing the counter. Once this is complete, control transfers to the boolean expression for evaluation.
Similar to the while loop, a for loop will continue as long as the boolean expression is true. When the boolean expression becomes false, control is transferred to the first statement following the for block.
For this tutorial, I chose to implement break and continue statements in Listing 4-3 only. However, they may be used in any of the loop statements.

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.
\begin{displaymath}1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots + \frac{1}{n}\end{displaymath}
14) Write a program to produce the sum of the series where n is entered by a user.
\begin{displaymath}1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \cdots \frac{1}{n}\end{displaymath}
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.

No comments:

Post a Comment