Unit 6 Arrays
Unit 6 Arrays
number[2]
number[3]
number[4]
number[0] = 3;
number[1] = 4;
number[2] = 2;
number[3] = 5;
number[4] = 1;
3 number[0]
4 number[1]
2 number[2]
5 number[3]
1 number[4]
class Program
{
static void Main(string[] args)
{
int[] A = { 2,7,1,5,6,9,12,15,11,10 };
int i;
for (i=1;i<10;i++)
Console.Write(A[i]+" ");
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
int[] A = { 2,7,1,5,6,9,12,15,11,10 };
int i;
for (i=1;i<10;i++)
if(A[i]%2 == 0)
Console.Write(A[i]+" ");
Console.ReadLine();
}
}
If(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
Console.WriteLine(“Sorted List”);
for(int i=0;i<n;i++)
{
Console.WriteLine(“ “+number[i]);
}
Console.WriteLine( “ “);
}
}
Output:
Given List 55 40 10 5 2
Sorted List 2 5 10 40 55
class Program
{
static void printarray(int[] a)
{
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i] + " ");
}
}
static void Main(string[] args)
{
int[] P = new int[] {1,2,3,4,5};
printarray(P); //Array P is passed to the method
Console.ReadLine();
}
} // This program will print the array elements.
class Program
{
static void addnum(ref int[] a)
{ for (int i = 0; i < a.Length; i++)
{
a[i]=a[i]+2; //The array elements are updated
Console.WriteLine(a[i] + " ");
} }
static void Main(string[] args)
{
int[] P = new int[] {1,2,3,4,5};
addnum(ref P); //Array P is passed as reference to the method
Console.ReadLine();
}
}
//This program will update (add 2) the array elements and print the new elements.
Method/Property Purpose
Clear() Sets a range of elements to empty
values
CopyTo() Copies elements from the source
array into the destination array
GetLength () Gives the number of elements in a
given dimension of the array
Length Gives the length of an array
GetValue() Gets the value for a given index in
the array
SetValue ( ) Sets the value for a given index in
the array
Reverse () Reverses the contents of a one-
dimensional -array
Sort() Sorts the elements in one
Methods/Property Purpose
Add() Adds an object to a list
Clear() Removes all the elements from the
list
Contains() Determines if an element is in the
list
CopyTo() Copies a list to another
Insert() Inserts an element into the list
Remove() Removes the first occurrence of an
element
RemoveAt() Removes the element at the
specified place
RemoveRange() Removes a range of elements
Sort() Sorts the elements
Capacity Gets or sets the number of elements
in the list
Count Gets the number of elements
Previous Program produces the following output:
capacity = 16
Elements present = 5
Anand
Bombay
Calcutta
Delhi
Madras
Anand
Bombay
Calcutta
Delhi
This chapter explains:-
› One dimensional arrays.
› Two dimensional arrays.
› Array and ArrayList class.