
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdf
|
array are also known as array elements. Each array element can |
|
be accessed individually by using its index. |
|
§ Delegate type: The delegate data types reference either to a |
|
static method or an object instance method. |
Note |
To an extent, you can compare the delegate data type to a function |
pointer in C or C++. |
Looping Structures
You can use the looping statements to repeatedly execute a section of a program as long as the specified condition remains true. When the condition becomes false, the loop ends and the control is passed to the statement immediately following the loop.
Note The looping structures are also commonly referred to as iteration statements.
Most of the looping structures offered by C# are similar to those available earlier in C or C++. These include:
§while statement
§do statement
§for statement
§foreach statement
while statement
The while statement executes a set of statements conditionally until the evaluating condition becomes false. As a result, these statements can either be executed n number of times or never be executed. The evaluating condition is a logical (Boolean) expression that returns either false or true. The syntax of the while statement is as follows:
Caution In ASP.NET, you need to create a new project to write this class. If you would like to continue using the project you created earlier for the HelloWorld class, you would have to make the entire HelloWorld class commented. This is because, the HelloWorld class already has a Main method, and in a project, there can be only one Main method.
while (Boolean_expression)
{
statements;
}
For example:
using System;
class eval
{
static void Main()
{
int Num = 0;
while (Num < 100)
{
Console.WriteLine("{0}", Num);
Num = Num + 10;

}
Console.WriteLine("We are out of the while loop.");
string s1;
s1=Console.ReadLine();
}
}
In this code, Num is an int type variable, which has been initialized to zero. The evaluating expression, Num < 100, checks whether the value of Num is less than 100. If the value of Num is less than 100, the condition returns true and the while loop is executed. Console.WriteLine ("{0}", Num) displays the value of Num. The next line increments the current value of Num by ten and the loop restarts. This continues until Num's value becomes 100. Here, the loop stops executing because 100 is not less than 100. After the execution of the loop stops, the control is transferred to the statement immediately next to the loop, which is Console.WriteLine ("We are out of the while loop."). The last statement s1=Console.ReadLine() waits for user input. This way, you can pause the execution of the console in the Command line. The result of the execution of the code is shown in Figure D-5.
Figure D-5: Output of the while code
do...while statement
The execution of the do...while structure is similar to the while structure. It is repeatedly executed until the evaluating condition becomes false. The main difference between the while and the do...while structures is that the while loop may never be executed if the evaluating condition returns false the first time it is tested. In that case, the loop is ignored and the control is passed to the statement immediately next to the loop. However, the do...while loop is executed at least once, even if the evaluating condition returns false the first time it is tested. The syntax of the do...while structure is as follows:
do
{
statements;
} while(Boolean_expression);
For example:
using System;
class eval
{
static void Main()
{

int Num = 11;
do
{
Console.WriteLine("{0}", Num);
Num = Num + 1;
} while (Num < 10);
Console.WriteLine("We are out of the loop.");
}
}
In this code, the loop has already been executed once before the condition is checked. Therefore, even though the value of the variable Num is 11, the loop will display its value. After the value of Num is displayed for the first time, when the condition is evaluated, it returns false and the loop is not executed again. The output of the code is shown in Figure D-6.
Figure D-6: Output of the do...while code
for statement
You can use this looping structure to compactly specify the statements that control the repeated execution of a loop. In this looping structure, the control statements (initialization expression, test expression, and change expression) are not specified within the loop. Rather, they are specified right at the beginning of the loop. Programmers use the for statement for easy readability and understandability. The syntax for the for looping structure is as follows:
for(initialization_expr, test_expr, change_expr)
{
statements;
}
For example:
using System;
class eval
{
static void Main()
{
int Num;
for(Num = 0; Num < 10; Num++)

{
Console.WriteLine("{0}", Num);
}
Console.WriteLine("We are out of the for loop.");
}
}
In this code, the variable Num is initialized to 0 and its value is checked before the for block statements are executed. If the evaluating condition returns true (the value of Num is less than 10), the value of Num is displayed on the console. The execution of the loop is repeated until the value of Num becomes 10, after which the evaluating condition returns false and the message "We are out of the for loop." is displayed on the console. The output of the execution of the code is shown in Figure D-7.
Figure D-7: Output of the for code
Note The initialization expression is executed only once, when the control is passed to the loop for the first time. The test expression is executed each time the loop runs. The statements in the loop's body are executed only if the test expression returns true. The change expression is always executed when the control returns to the beginning of the loop.
foreach statement
You can use the foreach structure to repeatedly execute a set of statements for each number of array elements or a collection of objects. In other words, the statements of the foreach block are executed for each element in the array or collection. In this way, you can use the foreach structure to count (or enumerate) the elements of a collection or an array. After all the elements of the collection or the array are traversed, the control is transferred to the statement immediately following the foreach block. The syntax of the foreach structure is as follows:
foreach(datatype variable_name in expression)
{
statements;
}
For example:
using System;
class eval
{
static void Main()
{

int counter = 0;
int [] Numbers = new int []{9, 8, 16, 11, 4,
0, 3, 15, 35,2};
foreach(int Num in Numbers)
{
if(Num < 5)
counter++;
}
Console.WriteLine("{0} numbers less than
5 were found.", counter);
}
}
This code counts the number of elements in the Numbers array that are less than 5. The foreach loop continues to run until it traverses to the last element of the Numbers array. Whenever it finds a number less than 5, the counter is incremented by one. The Console.WriteLine statement in the end displays the number of characters found that are less than 5. Figure D-8 displays the output of the code.
Figure D-8: Output of the foreach code
Note You can use the break and continue statements in a loop. The break statement causes the execution of a loop to abruptly end and pass the control to the statement immediately next to the loop. The continue statement in a loop, on the other hand, returns the control to the beginning of the loop. Both statements cause the loop statements after them to be skipped.
Decision Structures
In addition to making decisions in daily life, you can incorporate the ability of decision making in the C# codes by using decision structures. The decision structures determine the sequence in which the statements of a program are executed. Hence, you can control the flow of a program, because they selectively execute the program statements depending on the value of expressions either associated with them or passed to them.
Note The decision structures are also known as conditional constructs.
The decision structures are quite similar to those available in C or C++. These include:
§if...else statement
§switch...case statement
if...else statement
In the if...else decision structure, the if construct is always followed by an evaluating condition. This evaluating condition is a Boolean expression, which always involves comparison of data. Any decision is made based on the result of this comparison. If the evaluating expression after if returns true (the value is non-zero), the statements in the immediate block are executed. However, if the evaluating expression returns false, the control is then transferred to the block immediately after the else construct. The syntax of this decision structure is as follows:
if(Boolean_expression)
{

statements;
}
else
{
statements;
}
For example:
using System;
class eval
{
static void Main()
{
int Num = 11;
if (Num > 10)
{
Console.WriteLine("{0}", Num);
Console.WriteLine("You are in the if block.");
}
else
{
Console.WriteLine("{0}", Num);
Console.WriteLine("You are in the else block.");
}
}
}
In this code, Num is initialized to 11. In the if construct, when the value of Num is evaluated, it returns true because 11 is greater than 10. As a result, the statements of the if block are executed and 11 is displayed. A line is also displayed to the effect that "You are in the if block." Figure D-9 displays the output of the code.
Figure D-9: Output ofthe if...else code
Note In the preceding code, initialize the value of Num to 0. Save the code and build it. Because 0 is not greater than 10, the evaluating expression returns false and the control is transferred to the else block. As a result of this, 0 is displayed on the console. A line is also displayed to the effect that "You are in the else block."
switch...case statement
You can use the switch...case structure if a variable can have multiple values. When the switch statement is executed, the condition-variable is evaluated and compared with each constant specified with the case statement. If the variable value is equal to any of the case constants, control is passed to the block following that case statement. If no match is found for the condition-variable value, control is passed to the block following the default label. However, if no case matches and there is no default label, then all the statements in the switch block are ignored and the control is passed to the statement immediately next to the switch block. The syntax of the switch...case structure is as follows:
switch(condition_variable)
{
case constant_expression_1:
statements;
break;
case constant_expression_2:
statements;
break;
............
case constant_expression_n:
statements;
break;
default:
statements;
break;
}
For example:
using System;
class eval
{
static void Main()
{
char Reply;
Console.WriteLine("Enter an alphabet in lower case.");
String s = Console.ReadLine();
Reply = char.Parse(s);
switch(Reply)
{
case 'a':

Console.WriteLine("You entered the vowel a.");
break;
case 'e':
Console.WriteLine("You entered the vowel e.");
break;
case 'i':
Console.WriteLine("You entered the vowel i.");
break;
case 'o':
Console.WriteLine("You entered the vowel o.");
break;
case 'u':
Console.WriteLine("You entered the vowel u.");
break;
default:
Console.WriteLine("You entered a consonant.");
break;
}
}
}
In this code, the user is prompted to enter a character in lowercase. When the user enters the character, it is read using Console.ReadLine() and is stored in the string variable s. Reply = char.FromString(s) converts the read character back to char type and stores it in the variable, Reply. This character is then matched with a, e, i, o, or u. If the character entered is a vowel, the message "You entered the vowel vowel_name." is displayed on the console. If the entered character was a consonant (b, c, d, f, and so on), the message "You entered a consonant." is displayed. The output of the code is displayed in Figure D-10.
Figure D-10: Output of the switch...case code
}
catch( exception object)
{
statements (error-handling code);
}
The finally block
When an exception is thrown, the rest of the statements in the try block are ignored. Sometimes, it is imperative that certain statements are processed irrespective of whether or not an exception was raised. For example, you might open a file for writing to it. However, when you write to the file, it throws an exception. In this case, you must close the file regardless of whether or not an exception was raised. You can use the finally block for this purpose, which follows the catch block. The code in the finally block is executed regardless of the occurrence of an exception. You can have only one finally block for an exception handler. However, it is not mandatory to have a finally block. The syntax of the finally block is as follows:
try
{
statements;
}
catch( exception object)
{
statements;
}
finally
{
statements (that need to be executed whether or not an exception was raised);
}
For example:
using System;
class eval
{