Program execution control Statements
If...Then...Else Statements
An If...Then...Else statement is the basic conditional statement. If the expression in the If statement is True, the statements enclosed by the If block are executed. If the expression is False, each of the ElseIf expressions is evaluated.
Syntax :
if (expression)
statement1
[else
statement2]
Example :
using System;
namespace SyntaxCS
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int iNumber;
System.Console.WriteLine("Enter a number");
iNumber=Convert.ToInt32(System.Console.ReadLine());
if((iNumber%2)==0)
{
System.Console.WriteLine("Number is even");
}
else
{
System.Console.WriteLine("Number is odd");
}
}
}
}
Select Case
A Select Case statement executes statements based on the value of an expression.
Syntax :
switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
jump-statement]
}
Example :
using System;
namespaceSyntaxCS
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
char cLetter;
System.Console.WriteLine("Please enter a letter");
cLetter=Convert.ToChar(System.Console.ReadLine());
switch (cLetter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.Console.WriteLine("The letter is a Vowel");
break;
default:
System.Console.WriteLine("The letter is not a Vowel");
break;
}
}
}
}
While Do While
A While or Do loop statement loops based on a Boolean expression. A While loop statement loops as long as the Boolean expression evaluates to True;
Syntax :
1) while ( )
2) do statement while ( expression);
Example :
namespace SyntaxCS
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int x;
x = 3;
while (x < 5)
{
Console.WriteLine("while x < 5");
x += 1;
}
do
{
Console.WriteLine("Do While x > 0");
x -= 1;
}while (x > 0);
}
}
For Loop
For loop enables you to evaluate a sequence of statements multiple times.
Syntax :
for ([initializers ]; [ expression]; [ iterators]) statement
Example :
using System;
namespace SyntaxCS
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int iNumber;
for(iNumber=0;iNumber<10;iNumber++)
{
System.Console.WriteLine("VC# in Easy Steps "+(iNumber+1));
}
}
}
}
For Each Loop
A For Each...Next statement loops based on the elements in an expression. A For Each statement specifies a loop control variable and an enumerator expression.
Syntax :
foreach ( type identifier in expression) statement
Example :
using System;
namespace SyntaxCS
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int iOddCount = 0, iEvenCount = 0;
int[] iNumberarray = new int [] {0,1,2,5,7,8,11};
foreach (int itreator in iNumberarray)
{
if (itreator%2 == 0)
iEvenCount++;
else
iOddCount++;
}
Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",iOddCount, iEvenCount) ;
}
}
}