Arrays
- An array is the collection of similar type of values.
- Each value in the array is to be called as an element.
- The total no. of array elements is called as ―Array size‖.
1. Single Dimensional Arrays:
- Array declaration:
Without initialization:
datatype[] arrayname = new datatype[size];
With initialization:
datatype[] arrayname = {val1,val2,val3,…..};
- Accessing the elements:
arrayname[index]
2. Double Dimensional Arrays:- Array declaration:
datatype[,] arrayname = new datatype[rows size,columns size];
With initialization:
datatype[,] arrayname = {{val1,val2,…}, {val1,val2,…},…};
- Accessing the elements:
Same as ―Double‖ dimensional arrays, but increase the no. of dimensions
Download above code of Demo of Single Dim Array : Download Links
Download above code of Demo of Multiple Dim Array : Download Links
foreach Loop
- One of the most common usages of the ―for‖ loop is to iterate through a collection of values (array).
- C# offers a simplified and easier syntax of for loop called ―foreach loop‖, designed only for such kind of array iterations.
- Syntax:
{ ;
;
}
- In the above syntax, the loop will be executed once for each value in the array. For every iteration, the values of the array will be assigned to the variable.
- For example, you take the following for loop.
for (int i = 0;i < nums.Length; i++)
{
Console.WriteLine(nums[i]));
}
- You can re-write the above example with ―foreach‖ syntax as follows:
foreach (int n in nums)
{
Console.WriteLine(n);
}
Note: The arrayname.Length‖ property gets the size of the array. We discuss about the "Array"
class in future.
Jagged Arrays
- A two-dimensional array is of rectangular size always.
- But the jagged arrays are more flexible in sizing them.
- They may not be rectangular size.
- To declare them, declare the array size in one brackets [size] and then give empty brackets, because different no. of elements can be stored in each row
No comments:
Post a Comment