0% found this document useful (0 votes)
17 views29 pages

C#dotnet Unit-2 LM

This document outlines the concepts of control structures, classes, and objects in .NET, focusing on control statements in C#. It covers data types, type casting, conditional and iterative statements, as well as arrays, including single-dimensional, multidimensional, and jagged arrays. The document also discusses keywords, variables, and operators in C#, providing examples and explanations for each topic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views29 pages

C#dotnet Unit-2 LM

This document outlines the concepts of control structures, classes, and objects in .NET, focusing on control statements in C#. It covers data types, type casting, conditional and iterative statements, as well as arrays, including single-dimensional, multidimensional, and jagged arrays. The document also discusses keywords, variables, and operators in C#, providing examples and explanations for each topic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT-2

Objective:
 To impart the concepts of control structures, classes, objects in .NET
Syllabus:
UNIT - II: Control Statements
Introduction to data types: Value Type - Primitive types, Arrays, Reference
Type, Keywords, variables, Operators and Literals in C#
Type Casting- Primitive type casting, Boxing and Unboxing, Special Operators
in C#
Conditional Statements- if, if-else, if-else-if ladder, nested if, switch
statements with examples
Iterative Statements- while, do-while, for, foreach, break, continue
statements with examples
Outcomes:
Students will be able to
 Understand various data types in C#
 Understand various conditional and iterative control structures
 Compose simple programs in C# using control structures
Learning Material
Introduction to data types: Value Type - Primitive types, Arrays, Reference
Type:
Data type:
 A data type is defined as a categorizing one of various types of data, such
as floating point and integer, and the operations that can done on that
type.
 Data types are especially important in C# because it is a strongly typed
language. This means that, all operations are type-checked by the
compiler for type compatibility. Illegal operations will not be compiled.
 Thus, strong type-checking helpsto prevent errors and enhances
reliability.
 To enable strong type-checking, all variables,expressions, and values
have a type (data type).

C# contains two general categories of built-in data types: value types and
reference types. The difference between the two types is what a variable
contains. For a value type, a variable holds an actual value, such 3.1416
or
212. For a reference type, a variable holds a reference to the value.
213.

Value type:
Value type variables can be assigned a value directly. Value of value type
to a variable or field or array element of value type makes a copy of the
value.They are derived from the class System.ValueType.To get the exact size
of a type or a variable use the sizeof() method. The expression sizeof(type)
yields the storage size of the object or type in bytes.
Primitive types:
A value type is a simple type, a struct type or an enum type.Assigning a
Some of the primitive (fundamental) data types:

Reference type:
 The reference data types do not contain the actual data stored in a
variable, but they contain a reference to the variables.
 If the data is changed by one of the variables, the other variable
automatically reflects this change in value.
 A reference type is a class, an interface, an array type, or a delegate
type.
Arrays: Array in C# is a group of similar types of elements that have
contiguous memory location. In C#, array is an object of base type
System.Array. In C#, array index starts from 0. We can store only fixed set of
elements in C# array.
There are 2 methods commonly used for declaring arrays. While both have
their place and usage, most programmers prefer the dynamic array that is
declared at run-time to provide the most flexibility.
The static array is great if you have a set structure that will never change.
An array that holds the days of the week, months in the year, or even the
colors in a rainbow are the static arrays. These won't change and they won't
be data driven so in this case, a static array will be best.
C# Array Properties:
Property Description
IsFixedSize It is used to get a value indicating whether the Array has a fixed
size or not.
IsReadOnly It is used to check that the Array is read-only or not.
Length It is used to get the total number of elements in all the
dimensions of the Array.
LongLength It is used to get a 64-bit integer that represents the total number
of elements in all the dimensions of the Array.
Rank It is used to get the rank (number of dimensions) of the Array.

C# Array Methods:
Method Description
Clear(Array,Int32,Int32) It is used to set a range of elements in an array to
the default value.
Clone() It is used to create a shallow copy of the Array.
Copy(Array,Array,Int32) It is used to copy elements of an array into
another array by specifying starting index.
Empty<T>() It is used to return an empty array.
Finalize() It is used to free resources and perform cleanup operations.
IndexOf(Array,Object) It is used to search for the specified object and returns
the index of its first occurrence in a one-dimensional array.
Initialize() It is used to initialize every element of the value-type Array by
calling the default constructor of the value type.
Reverse(Array) It is used to reverse the sequence of the elements in the
entire one-dimensional Array.
Sort(Array) It is used to sort the elements in an entire one-dimensional
Array.
ToString() It is used to return a string that represents the current object.
//Example program on Array properties and methods
using System;
namespaceCSharpProgram
{ class Program {
static void Main(string[] args) {
// Creating an array
int[] arr = new int[6] { 5, 8, 9, 25, 0, 7 };
// Creating an empty array
int[] arr2 = new int[6];
// Displaying length of array
Console.WriteLine("length of first array: "+arr.Length);
// Sorting array
Array.Sort(arr);
Console.Write("First array elements: ");
// Displaying sorted array
PrintArray(arr);
// Finding index of an array element
Console.WriteLine("\nIndex position of 25 is "+Array.IndexOf(arr,25));
// Coping first array to empty array
Array.Copy(arr, arr2, arr.Length);
Console.Write("Second array elements: ");
// Displaying second array
PrintArray(arr2);
Array.Reverse(arr);
Console.Write("\nFirst Array elements in reverse order: ");
PrintArray(arr);
}
// User defined method for iterating array elements
static void PrintArray(int[] arr)
{
foreach (Object elem in arr)
{
Console.Write(elem+" ");
}
}
}
}
Single Dimensional Array
 To create single dimensional array, you need to use square brackets []
after the type.
int[] arr = new int[3]{10,20,30};//creating Static array
int[] arr = { 10, 20, 30, 40, 50 }; creating Dynamic array
int[] arr = new int[]{10,20,30}; //creating Dynamic array
Let's see a simple example of C# array, where we are going to declare,
initialize and traverse array.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];//creating dynamic array
arr[0] = 10;//initializing array
arr[2] = 20;
arr[4] = 30;
//traversing array
for (int i = 0; i <arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It
can be two dimensional or three dimensional. The data is stored in tabular
form (row * column) which is also known as matrix.
To create multidimensional array, we need to use comma inside the
square brackets. For example:
int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array
There are 3 ways to initialize multidimensional array in C# while declaration.
1. int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//Static
2. We can omit the array size.
int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//Dynamic array
We can omit the new operator also.
3. int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; //Dynamic array
Let's see a simple example of multidimensional array in C# which
declares, initializes and traverse two dimensional array.
Ex:using System;
public class MultiArrayExample
{
public static void Main(string[] args)
{
int[,] arr=new int[3,3];//declaration of 2D static array
arr[0,1]=10;//initialization
arr[1,2]=20;
arr[2,0]=30;
//traversal
for(int
i=0;i<3;i++){ for(int
j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
Jagged Arrays
In C#, jagged arrayis also known as "array of arrays" because its
elements are arrays. The element size of jagged array can be different.
Declaration of Jagged array
Let's see an example to declare jagged array that has two elements.
int[][] arr = new int[2][];
Initialization of Jagged array
Let's see an example to initialize jagged array. The size of elements can be
different.
arr[0] = new int[4];
arr[1] = new int[6];
Initialization and filling elements in Jagged array
Let's see an example to initialize and fill elements in jagged array (Static).
arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };
Here, size of elements in jagged array is optional. So, you can write above
code as given below:
arr[0] = new int[] { 11, 21, 56, 78 };
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
Let's see an example to initialize the jagged array while declaration.
int[][] arr = new int[3][]
{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};
Let's see a simple example of jagged array in C# which declares, initializes, and
traverse jagged arrays.
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[2][];// Declare the Jagged array
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
// Traverse array elements
for (int i = 0; i <arr.Length; i++)
{
for (int j = 0; j <arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
} }
Keywords, variables, Operators and Literals in C#:
Keywords:
 A computer language is defined by its keywords because they determine
the features built into the language.
 C# defines two general types of keywords: reserved and contextual.
 Keywords are predefined, reserved identifiers that have special meanings
to the compiler.
 They cannot be used as identifiers in your program unless they include
@ as a prefix.
 For example, @if is a valid identifier, but if is not because if is a keyword.

 A contextual keyword is used to provide a specific meaning in certain


contexts in the code, but it is not a reserved word in C#.
 Using a contextual keyword as a variable name, can be confusing and is
considered bad practice by many programmers.
 The contextual keywords are shown in Table.

Variables:
 A variable is a name given to a storage area that our programs can
manipulate.
 Each variable in C# has a specific type.
 A variable is declared inside a method body, constructor body, or another
block statement.
 The variable can be used only in that block statement, and only after it
has been declared.
C# Naming conventions of a variable:
 May contain letters (a-z/A-Z), decimal digits (0-9), _ (underscore).
 Can start with a capital letter before the keyword
 Can use @ at beginning of any keyword
 It should not be a keyword
 White spaces ar not allowed
 Variable names can be of any length
 Variable names are case sensitive; Sum and sum are different names
Defining Variables:
Syntax for variable definition in C# is
<data_type><variable_list>;
Example: int i, j, k;int @int;
Initializing Variables:
Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is
variable_name = value; or <data_type><variable_name> = value;
Example: i=10, j=20; orint d = 3, f = 5;
Operators:
C# provides an extensive set of operators that give the programmer
detailed controlover the construction and evaluation of expressions. Most of
C#’s operators fall intothe following categories: arithmetic, bitwise, relational,
and logical.
Arithmetic operators:
// C# program to demonstrate the
working of Arithmetic Operators
using System;
namespace Arithmetic {
classsample {
static void Main(string[] args)
{ int result;
int x = 10, y = 5;
result = (x + y);
Console.WriteLine("Addition Operator: {0}", result);
result = (x - y);
Console.WriteLine("Subtraction Operator: {0}",result);
result = (x * y);
Console.WriteLine("Multiplication Operator: {0}",result);
result = (x / y);
Console.WriteLine("Division Operator: {0}",result);
result = (x % y);
Console.WriteLine("Modulo Operator: {0}",result);
}
}}
Bitwise operators: (AND, OR, XOR, and NOT)
 C# provides a set of bitwise operators that expand the types of problems
to which C# can beapplied.
 The bitwise operators act directly upon the bits of their operands.
 They are definedonly for integer operands.
 They cannot be used on bool, float, or double.
 They are called the bitwise operators because they are used to test, set,
or shift the bitsthat comprise an integer value.
 The bitwise operators AND, OR, XOR, and NOT are &, |, ^, and ~.

// Use bitwise AND to determine if a


number is odd.
using System;
classIsOdd {
static void Main() {
ushortnum;
num = 10;
if((num& 1) == 1)
Console.WriteLine("This won't display.");
num = 11;
if((num& 1) == 1)
Console.WriteLine("{0} is odd.",num);
}
}
Relational and Logical Operators:
Relational operators are used to check
the relationship between two operands. If
the relationship is true the result will be
true, otherwise it will result in false.

using System;
namespace Operator{
classRelationalOperator{
public static void Main(string[]
args){ bool result;
int f = 10, s = 20;
result = (f==s);
Console.WriteLine("{0} == {1} returns {2}",f, s, result);
result = (f>s);
Console.WriteLine("{0} > {1} returns {2}",f, s, result);
result = (f< s);
Console.WriteLine("{0} < {1} returns {2}",f, s, result);
result = (f>= s);
Console.WriteLine("{0} >= {1} returns {2}",f, s, result);
result = (f <= s);
Console.WriteLine("{0} <= {1} returns {2}",f, s, result);
result = (f != s);
Console.WriteLine("{0} != {1} returns {2}",f, s, result);
}
}}
Output: 10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True
Logical operators are used to perform logical operation such as AND, OR,
and NOT. Logical operators on boolean expressions (true and false) and returns
Boolean values. Logical operators are used in decision making and loops.
 Logical AND: The ‘&&’ operator returns true when both the conditions in
consideration are satisfied. Otherwise it returns false.
 Logical OR: The ‘||’ operator returns true when one (or both) of the
conditions in consideration is satisfied. Otherwise it returns false
 Logical NOT: The ‘!’ operator returns true the condition in consideration
is not satisfied. Otherwise it returns false.
// C# program to demonstrate the working
// of Logical Operators
using System;
namespace Logical
{ classlogicalsample{
static void Main(string[] args) {
bool a = true,b = false, result;
result = a && b;
Console.WriteLine("AND Operator: {0}",result);
result = a || b;
Console.WriteLine("OR Operator: {0}",result);
result = !a;
Console.WriteLine("NOT Operator: {0}",result);
}
}}
Literals:
Literals are value constants that are
assigned to variables in a program. C#
supports several types of literals.
Integer literals: An integer literal refers to the sequence of digits. An
integer literal can be a decimal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
Ex: 85 /* decimal */
0x4b /* hexadecimal */
Real/Floating literals:A floating-point literal has an integer part, a
decimal point, a fractional part, and an exponent part. We can represent
floating point literals either in decimal form or exponential form.
Mantissa e/E exponent
Ex: 7500 can be7.5E3//7.5x103
Character literals are enclosed in single quotes. For example, 'x' and can
be stored in a simple variable of char type. A character literal can be a
plain character (such as 'x'), an escape sequence (such as '\t').
Ex: char ch = 'a';
String literals are enclosed in double quotes "" or with @"". A string
contains characters that are similar to character literals: plain characters,
escape sequences, and universal characters.
Ex: string s1=”welcome”; string s2= @”welcome”;
Type Casting- Primitive type casting:
 Type casting refers to the conversion of a data type into another data
type. This is done in two ways 1. Implicit 2. Explicit
 Implicit conversion can be done by the system automatically.
 Explicit conversion is achieved manually by specifying the target data
type in the parenthesis before operandon the right side of an assignment
operator.
 There are many primitive types in C# that are converted implicitly by the
rule, i.e. the target type must be larger than the source type.
 The following list shows the type conversions between .NET types.
From To
sbyte (Signed 8-bit integer) short, int, long, float, double, or decimal
byte (unsigned 8-bit integer) short, ushort, int, uint, long, ulong,
float, double, or decimal
char ushort, int, uint, long, ulong, float,
double, or decimal
short (Signed 16-bit integer) int, long, float, double, or decimal
ushort(unsigned 16-bit integer) int, uint, long, ulong, float, double, or
decimal
int (Signed 32-bit integer) long, float, double, or decimal
uint (unsigned 32-bit integer) long, ulong, float, double, or decimal
long (Signed 64-bit integer) float, double, or decimal
ulong (unsigned 64-bit integer) float, double, or decimal
float double
Ex: using System;
namespace
ConsoleApplication1{ class
Program {
static public void Main(string[]
args){ int x = 10;
double d = x; //implicit conversion
float f= (float)x; // Explicit conversion
Console.WriteLine(d);
Console.ReadKey();
}
}
}

Boxing and Unboxing:


Boxing means conversion of a value type on stack to an object type on the
heap. Conversely, the conversion from an object type back to a value type is
known as Unboxing.
Boxing: Any type, value or reference can be assigned to an object without an
explicit conversion. When the compiler finds a value type where it needs a
reference type, it creates an object ‘box’ into which it places the value of value
type.
Ex:int m=100;
Object obj=m; // creates a box to hold m
Both the value type and reference types are independent of each other.
Ex: int m=100;
Object obj=m;
m=200;
Console.writeLine(m); //m=200
Console.writeLine(obj); //obj=100
When a code changes the value of m, the value of obj is not affected.
Unboxing:unboxing is the process of conversion of object type back to the
value type. Remember that we only unbox a variable that has previously been
boxed. In contrast to boxing, unboxing is an explicit operation using C-style
casting.
Ex: int m=100;
objectobj=m; //boxing; box m
int n=(int)obj; //unboxing; unbox obj back to an int
Special Operators in C#:
C# supports the following special operators.
is relational operator
as relational operator
typeof type operator
sizeof size operator
new object creator
.(dot) member-access operator
checked overflow checking
unchecked prevention of overflow checking

Conditional Statements- if, if-else, if-else-if ladder, nested if, switch


statements with examples
IF: if statement is a powerful decision making statement and is used to
control the flow of execution of statements. It allows the computer to evaluate
the expression first and then, depending on whether the value of the
expression is true or false, it transfers the control to the next statement. The
syntax of if statement in C# is:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}

The boolean-expression will return either true or false.If the boolean-


expression returns true, the statements inside the body of if will be executed.If
the boolean-expression returns false, the statements inside the body of if will
be ignored.
For example:
using System;
namespace Conditional{
classIfStatement{
public static void Main(string[]
args){ int number = 2;
if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}
Console.WriteLine("This statement is always executed.");
}
}
}
IF-ELSE:The block of code inside the else statement will be executed if the
expression is evaluated to false.
The syntax of if...else statement in C# is:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}
else
{
// statements executed if boolean-expression is false
}
Example:
using System;
namespace Conditional{
classIfElseStatement{
public static void Main(string[]
args){ int number ;
Console.WriteLine(“enter any integer number:”);
number=Convert.ToInt32(Console.ReadeLine());
if (number >=0)
{
Console.WriteLine("{0} is positive", number);
}
else
{
Console.WriteLine("{0} is negative", number);
}
Console.ReadKey();
}
}}
IF-ELSE-IF LADDER:There are multiple conditions to test and execute one of
the many blocks of code.The syntax for if...else if statement is:
if (boolean-expression-1)
{
// statements executed if boolean-expression-1 is true
}
else if (boolean-expression-2)
{
// statements executed if boolean-expression-2 is true
}
.
.
else
{
// statements executed if all above expressions are false
}
Ex: using System;
namespace Conditional{
classIfElseIfStatement {
public static void Main(string[]
args){ int number;
Console.WriteLine(“enter any integer number:”);
number=Convert.ToInt32(Console.ReadLine());
if (number <0)
{
Console.WriteLine("{0} is negative", number);
}
else if (number >0)
{
Console.WriteLine("{0} is positive", number);
}
else
{
Console.WriteLine("{0} is equal to 0");
}
Console.ReadKey();
}
}}
NESTED IF...ELSE:
An if...else statement can exist within another if...else statement. Such
statements are called nested if...else statement.
The general structure of nested if…else statement is:
if (boolean-expression)
{
if (nested-expression-1)
{
// code to be executed
}
else
{
// code to be executed
}
}
else
{
if (nested-expression-2)
{
// code to be executed
}
else
{
// code to be executed
}
}
Nested-if statements are generally used when we have to test one
condition followed by another. In a nested if statement, if the outer if statement
returns true, it enters the body to check the inner if statement.
Example:to find largest of three numbers
using System;
namespace
Conditional{ class
Nested{
public static void Main(string[]
args){ int first, second, third;
Console.WriteLine(“enter any three integer numbers:”);
first=Convert.ToInt32(Console.ReadLine());
second=Convert.ToInt32(Console.ReadLine());
third=Convert.ToInt32(Console.ReadLine());
if (first > second)
{
if (first > third)
{
Console.WriteLine("{0} is the largest", first);
}
else
{
Console.WriteLine("{0} is the largest", third);
}
}
else
{
if (second > third)
{
Console.WriteLine("{0} is the largest", second);
}
else
{
Console.WriteLine("{0} is the largest", third);
}
}
Console.ReadKey();
}
}
}
SWITCH STATEMENT: switch is a selection statement that chooses a single
switch section to execute from a list of candidates based on a pattern match
with the match expression.
Following is the definition of the switch..case statement.
switch (expression)
{
case expression_value1:
Statement
break;
case expression_value2:
Statement
break;
case expression_value3:
Statement
break;
default:
Statement
break;
}
The switch statement is often used as an alternative to an if-else
construct if a single expression is tested against three or more conditions. For
example, the following switch statement determines whether a variable of type
Color has one of three values:
Example: using System;
publicenum Color { Red, Green, Blue }
public class Example{
public static void Main() {
Color c = (Color) (new Random()).Next(0, 3);
switch (c)
{
caseColor.Red:
Console.WriteLine("The color is red");
break;
caseColor.Green:
Console.WriteLine("The color is green");
break;
caseColor.Blue:
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("The color is unknown.");
break;
}
}}
Iterative Statements- while, do-while, for, foreach, break, continue
statements with examples
WHILE: The simplest of all looping structures in C# is the whilestatement. The
basic syntax of the while statement is
Initialization;
while(test condition)
{
Body of the loop
}
Whileis an entry controlled loop statement. The test condition is evaluated
and if the condition is true, then the body of the loop is executed. After
execution of the body, the test condition is once again evaluated and if it is
true, the body is executed once again. This process of repeated execution of the
body continues until the test condition finally becomes false and the control is
transferred out of the loop.
Ex:
using System;
namespacewhileLoop{
classwhileLoopProgram{
static void Main(string[]
args){ int a=1;
while(a<=15)
{
Console.WriteLine(“{0}”,a);
a++;
}
Console.ReadKey();
}
}
}
DO-WHILE: On some occasions it might be necessary to execute the body of
the loop before the test condition is performed. Such situations can be handled
with the help of the do-while statement.
initialization;
do{
Body of the loop
}while(test condition);
 On reaching the do statement, the program proceeds to evaluate the
body of the loop first.
 At the end of the body of the loop, the test condition in the while
statement is evaluated.
 If the condition is true, the program continues to evaluate the body of the
loop once again. If the condition is false, the loop will be terminated and
control goes to the next statement.
Ex: using System;
namespacewhileLoop{
classwhileLoopProgram{
static void Main(string[]
args){ int a=1;
do{
Console.WriteLine(“{0}”,a);
a++;
}while(a<=15);
Console.ReadKey();
}
}}
FOR LOOP: for is another entry controlled loop that provides a more concise
loop control structure. The general form of the for loop is
for(initialization; test_condition;inc/dec)
{
Body of the loop
}
 Initialization of the control variable is done first.
 The value of the control variable is tested using the test condition.
 If the condition is true, then the loop will be executed. Otherwise, the loop
will be terminated and control goes to the next statement.
 Loop will be incremented or decremented based on the iterator.
Ex:using System;
namespacewhileLoop{ classw
hileLoopProgram { static void
Main(string[] args){ for(int
i=1;i<=10;i++)
{
Console.WriteLine(“{0}”,i);
}
Console.ReadKey();
}
}}
FOREACH: The foreach statement is similar to for statement but it enables us
to iterate elements in arrays and collection classes such as List and
HashTable. The general form of the foreach statement is:
foreach (typevariablein expression)
{
Body of the loop
}
 The type and variable declare the iteration variable.
 During execution, the iteration variable represents the array element for
which iteration is currently being performed. in is a keyword.
 The expression must be an array or collection type and an explicit
conversion must exist from the element type of the collection to the type
of the iteration variable.
 The advantage of the foreach over for statement is that it automatically
detects the boundaries of the collection being iterated over. Further, it
includes a built-in iterator for accessing the element in the collection.
Ex: using System;
namespacewhileLoop{ classwh
ileLoopProgram { static void
Main(string[] args) {
int[] arraylist = { 10, 20, 30, 40, 50 };
foreach(int a inarraylist)
{
Console.WriteLine(“{0}”,a);
}
Console.ReadKey();
}
}}
BREAK ANDCONTINUE:
 When abreak statement is encountered inside a loop, the loop is
terminated, and program controlresumes at the next statement following
the loop.
 Sometimes it is necessary to force an immediate exit from a loop,
bypassing any code remaining in thebody of the loop and the loop’s
conditional test, by using the break statement.
 The continue statement takes the control to the beginning of the loop
and executes the next iteration. The statements following continue are
skipped.
 The difference is that the breakstatement takes the control to end of the
loop whereas the continuestatement takes it to the beginning.
Ex: using System;
namespace whileLoop
{
class whileLoopProgram
{
static void Main(string[] args)
{
for (int i = 0; i <= 20; i++ )
{
if (i == 10)
continue;
if (i == 15)
break;
Console.WriteLine(“{0}”,i);
}
Console.ReadKey();
}
}
}

You might also like