Arrays
Arrays
Method-1:
int[4] myNumbers;
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Method-2:
int[] myNumbers = {25, 50, 75, 100};
Console.WriteLine(cars[0]);
Change an Array Element
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
Array Length
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);
Declaration and Initialization of Array
// Create an array of four elements, and add values later
Console.WriteLine(cars[i]);
}
There is also a foreach loop, which is used exclusively to loop through elements in an array:
Syntax:
foreach (type variableName in arrayName)
{
// code block to be executed
}
Example:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
Console.WriteLine(i);
}
using System;
using System.Linq;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[] myNumbers = {5, 1, 8, 9};
Console.WriteLine(myNumbers.Max()); // returns the largest value
Console.WriteLine(myNumbers.Min()); // returns the smallest value
Console.WriteLine(myNumbers.Sum()); // returns the sum of elements
}
Multidimensional Arrays
❖ A multidimensional array is basically an array of arrays.
❖ Arrays can have any number of dimensions.
❖ A 2D array is also known as a matrix (a table of rows and columns).
}
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Console.WriteLine(numbers[i, j]);