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”.
Implementation of Arrays:
Single Dimensional Arrays:
Array declaration:
Without initialization:
datatype[] arrayname = new datatype[size];
With initialization:
datatype[] arrayname = {val1,val2,val3,…..};
Accessing the elements:
arrayname[index]
Double Dimensional Arrays:
Array declaration:
Without initialization:
datatype[,] arrayname = new datatype[rows size,columns size];
With initialization:
datatype[,] arrayname = {{val1,val2,…}, {val1,val2,…},…};
Accessing the elements:
arrayname[row index,column index]
Multi Dimensional Arrays:
Same as “Double” dimensional arrays, but increase the no. of dimensions.
Demo on Single Dim Arrays
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArrayDemo
{
//Demo on Single-Dim Array.
class Program
{
static void Main(string[] args)
{
//read the no. of students
int n;
Console.Write("Enter no. of students: ");
n = Convert.ToInt32(Console.ReadLine());
//check n value whether it is greater than 0 or not.
if (n > 0)
{
//declare the arrays
string[] Names = new string[n];
int[] Marks = new int[n];
string[] Result = new string[n];
//read student names
Console.WriteLine("\nEnter " + n + " students names:");
for (int i = 0; i < n; i++)
{
Console.Write((i + 1) + ": ");
Names[i] = Console.ReadLine();
}
//read student marks
Console.WriteLine("\nEnter " + n + " students marks:");
for (int i = 0; i < n; i++)
{
Console.Write((i + 1) + ": ");
Marks[i] = Convert.ToInt32(Console.ReadLine());
}
//calculate results
for (int i = 0; i < n; i++)
{
if (Marks[i] >= 0 && Marks[i] <= 100)
{
if (Marks[i] >= 80)
Result[i] = "Distinction";
else if (Marks[i] >= 60)
Result[i] = "First Class";
else if (Marks[i] >= 50)
Result[i] = "Second Class";
else if (Marks[i]>= 35)
Result[i] = "Third Class";
else
Result[i] = "Fail";
}
else
Result[i] = "Invalid";
}
//display the student names and marks
Console.WriteLine("\n\nStudent Details:");
for (int i = 0; i < n; i++)
Console.WriteLine((i + 1) + ". " + Names[i] + " - " + Marks[i] + " - " + Result[i]);
}
else
Console.WriteLine("N value can't be zero.");
Console.Read();
}
}
}