Sunday, August 23, 2009

The if statement

1.7.5 The if statement
An if statement selects a statement for execution based on the value of a boolean expression. An if statement may optionally include an else clause that executes if the boolean expression is false.
The example
using System;
class Test
{
static void Main(string[] args) {
if (args.Length == 0)
Console.WriteLine("No arguments were provided");
else
Console.WriteLine("Arguments were provided");
}
}
shows a program that uses an if statement to write out two different messages depending on whether command-line arguments were provided or not.
1.7.6 The switch statement
A switch statement executes the statements that are associated with the value of a given expression, or a default of statements if no match exists.
The example
using System;
class Test
{
static void Main(string[] args) {
switch (args.Length) {
case 0:
Console.WriteLine("No arguments were provided");
break;
case 1:
Console.WriteLine("One arguments was provided");
break;
default:
Console.WriteLine("{0} arguments were provided");
break;
}
}
}
switches on the number of arguments provided.
1.7.7 The while statement
A while statement conditionally executes a statement zero or more times – as long as a boolean test is true.
using System;
class Test
{
static int Find(int value, int[] arr) {
int i = 0;
while (arr[i] != value) {
if (++i > arr.Length)
throw new ArgumentException();
}
return i;
}
static void Main() {
Console.WriteLine(Find(3, new int[] {5, 4, 3, 2, 1}));
}
}
uses a while statement to find the first occurrence of a value in an array.
1.7.8 The do statement
A do statement conditionally executes a statement one or more times.
The example
using System;
class Test
{
static void Main() {
string s;
do {
s = Console.ReadLine();
}
while (!string.Equals(s, "Exit"));
}
}
reads from the console until the user types “Exit” and presses the enter key.
1.7.9 The for statement
A for statement evaluates a sequence of initialization expressions and then, while a condition is true, repeatedly executes a statement and evaluates a sequence of iteration expressions.
The example
using System;
class Test
{
static void Main() {
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
}
}
uses a for statement to write out the integer values 1 through 10.
1.7.10 The foreach statement
A foreach statement enumerates the elements of a collection, executing a statement for each element of the collection.
The example
using System;
using System.Collections;
class Test
{
static void WriteList(ArrayList list) {
foreach (object o in list)
Console.WriteLine(o);
}
static void Main() {
ArrayList list = new ArrayList();
for (int i = 0; i < 10; i++)
list.Add(i);
WriteList(list);
}
}
uses a foreach statement to iterate over the elements of a list.

No comments: