0% found this document useful (0 votes)
4 views14 pages

Visual Programming Unit 3

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)
4 views14 pages

Visual Programming Unit 3

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/ 14

UNIT-3

ARRAYS

3.1 Introduction to array


3.2 Declaration and initialization of array
3.3 Accessing data from an array
3.4 Multi-dimensional arrays
3.5 Jagged arrays, param arrays and array class

Array
An array stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type stored at contiguous
memory locations.

Advantages of Array:
● Code Optimization (less code).
● Random Access.
● Easy to traverse data.
● Easy to manipulate data.
● Easy to sort data etc.

Declaring Arrays
To declare an array in C#, you can use the following syntax −
datatype[] arrayName;
where,
● datatype is used to specify the type of elements in the array.
● [ ] specifies the rank of the array. The rank specifies the size of the array.
● arrayName specifies the name of the array.

For example,
int[] balance;

C# Array Example: Declaration and Initialization at same time


There are 3 ways to initialize an array at the time of declaration.
int[] arr = new int[5]{ 10, 20, 30, 40, 50 };

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


1
We can omit the size of array.
int[] arr = new int[]{ 10, 20, 30, 40, 50 };

We can omit the new operator also.


int[] arr = { 10, 20, 30, 40, 50 };

Let's see the example of array where we are declaring and initializing array at the
same time.
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = { 10, 20, 30, 40, 50 };
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]+" ");
}
}
}
Output:
10 20 30 40 50

Accessing data from an array:


You can access the data of an array by using an index.
For example:
public class A
{
public static void Main(string[] args)
{
string[] days = { "Sun", "Mon", "Tue"};
Console.WriteLine(days[0]);
Console.WriteLine(days[1]);
Console.WriteLine(days[2]);
}
}

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


2
OUTPUT:
Sun
Mon
Tue

Examples:
Write a c# program to input 5 numbers in an array and find the sum.
public class A
{
public static void Main(string[] args)
{
int[] num= new int[5];
int sum = 0;
for(int i=1; i<=5; i++)
{
Console.WriteLine("Enter Number "+i);
num[i]=Convert.ToInt32(Console.ReadLine());
sum+= num[i];
}
Console.WriteLine("Sum="+sum);
}
}

OUTPUT
Enter Number 1
2
Enter Number 2
3
Enter Number 3
1
Enter Number 4
2
Enter Number 5
3
Sum=11

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


3
C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. The data
is stored in tabular form (row * column) which is also known as matrix. To create
a multidimensional array, we need to use commas inside the square brackets.
For example:
1. int[,] arr=new int[3,3];
2. int[,,] arr=new int[3,3,3];

C# Multidimensional Array Example


Let's see a simple example of multidimensional array in C# which declares,
initializes and traverses two dimensional array.

public class MultiArrayExample


{
public static void Main(string[] args)
{
int[,] arr=new int[3,3];
arr[0,1]=10;
arr[1,2]=20;
arr[2,0]=30;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();
}
}
}

Output:
0 10 0
0 0 20
30 0 0

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


4
C# Multidimensional Array Example: Declaration and initialization at same time
There are 3 ways to initialize multidimensional array in C# while declaration.
int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
We can omit the array size.
int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
We can omit the new operator also.
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

Let's see a simple example of a multidimensional array which initializes an array


at the time of declaration.

public class MultiArrayExample


{
public static void Main(string[] args)
{
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();
}
}
}

Output:
1 2 3
4 5 6
7 8 9

Example-1: Write a C# program to take 2✕2 matrix from user and display that.
public class MultiArrayExample
{
public static void Main(string[] args)
{

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


5
int[,] a = new int[2, 2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("Enter element: A{0}{1}", i + 1, j + 1);
a[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Entered matrix is :");
for (int i = 0; i <2; i++)
{
for (int j = 0; j <2; j++)
{
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
}
}

Example2: Write a c# program to take two 2✕2 matrix from user and display
their sum.

public class MultiArrayExample


{
public static void Main(string[] args)
{
int[,] a = new int[2, 2];
int[,] b = new int[2, 2];
int[,] c = new int[2, 2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("Enter element: A{0}{1}", i + 1, j + 1);
a[i, j] = Convert.ToInt32(Console.ReadLine());

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


6
}
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("Enter element: B{0}{1}", i + 1, j + 1);
b[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Sum of A and B matrix is :");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
c[i, j] = a[i, j] + b[i, j];
Console.Write(c[i, j] + " ");
}
Console.WriteLine();
}
}
}

Jagged Arrays
A jagged array is an array whose elements are arrays, possibly of different sizes.
A jagged array is sometimes called an "array of arrays." The following examples
show how to declare, initialise, and access jagged arrays.

The following is a declaration of a single-dimensional array that has three


elements, each of which is a single-dimensional array of integers:
int[][] jaggedArray = new int[3][];
Before you can use jaggedArray, its elements must be initialized. You can
initialize the elements like this:
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


7
Each of the elements is a single-dimensional array of integers. The first element
is an array of 5 integers, the second is an array of 4 integers, and the third is an
array of 2 integers.

It is also possible to use initializers to fill the array elements with values, in which
case you do not need the array size. For example:
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

You can also initialize the array upon declaration like this:
int[][] jaggedArray2 = new int[][]
{
new int[] { 1, 3, 5, 7, 9 },
new int[] { 0, 2, 4, 6 },
new int[] { 11, 22 }
};

You can use the following shorthand form. Notice that you cannot omit the new
operator from the elements initialization because there is no default initialization
for the elements:
int[][] jaggedArray3 =
{
new int[] { 1, 3, 5, 7, 9 },
new int[] { 0, 2, 4, 6 },
new int[] { 11, 22 }
};

You can access individual array elements like these examples:

// Assign 77 to the second element ([1]) of the first array ([0]):


jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):


jaggedArray3[2][1] = 88;

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


8
Example

This example builds an array whose elements are themselves arrays. Each one of
the array elements has a different size.
class a
{
static void Main()
{ int[][] arr = new int[2][];
arr[0] = new int[5] { 1, 3, 5, 7, 9 };
arr[1] = new int[4] { 2, 4, 6, 8 };
for (int i = 0; i < arr.Length; i++)
{ Console.Write("Element({0}): ", i+1);
for (int j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j]+" ");
}
Console.WriteLine();
}
}
}
Output
Element(1): 1 3 5 7 9
Element(2): 2 4 6 8

C# Params Array
Sometimes, you are not assured about a number of parameters or you want to
create a method that can accept n number of parameters at runtime. This situation
can be handled with params type array in C#. The params keyword creates an
array at runtime that receives and holds n number of parameters.
static int add (params int[] allnumber)
In the preceding line, the allnumber variable can holds n number of parameters at
runtime because it is declared with params keyword.

Programming example of params array in c#


In this example, we are creating a function add() that will receive any number of
integer parameters at runtime and returns the sum of all those numbers. We will
use params array to achieve this goal in C#.

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


9
class Program
{
static int add(params int[] a)
{
int sum = 0;
for(int i=0; i<a.Length;i++)
{
sum = sum + a[i];
}
return sum;
}
static void Main(string[] args)
{
int sum;
sum = Program.add(1, 2, 3);
Console.WriteLine("Sum of 1,2,3 is:\t{0}",sum);
sum = Program.add(3, 5, 2, 6, 2);
Console.WriteLine("Sum of 3,5,2,6,2 is:\t{0}", sum);
}
}
Output
Sum of 1,2,3 is: 6
Sum of 3,5,2,6,2 is: 18

Array Class
The Array class gives methods for creating, manipulating, searching, and sorting
arrays. The Array class is the base class for language implementations that
support arrays.

Characteristics of Array Class:


● In Array, the elements are the value of the array and the length of the array is
the total number of items present in the array.
● The lower bound of an Array is the index of its first element and the default
value of the lower bound is 0.
● The default size of an Array is 2GB.

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


10
Properties:
Length: Gets the total number of elements in all the dimensions of the Array.
Rank: Gets the rank (number of dimensions) of the Array. For example, a one-
dimensional array returns 1, a two-dimensional array returns 2, and so on.

Example 1: Length
class sample
{
public static void Main()
{
string[] name;
name = new string[] { "ram", "Sita", "Sam", "Ravi" };
Console.WriteLine("Length of the array name:" + name.Length);
}
}
Output:
Length of the array name:4

Example 2: Rank
class sample
{
public static void Main()
{
string[] name;
name = new string[] { "ram", "Sita", "Sam", "Ravi" };
Console.WriteLine("Rank of the array name:" + name.Rank);
}
}
Output:
Rank of the array name:1

Methods:
BinarySearch(): Searches a one-dimensional sorted Array for a value, using a
binary search algorithm.

Clear(): Sets a range of elements in an array to the default value of each


element type.

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


11
Copy(): Copies a range of elements in one Array to another Array and performs
type casting and boxing as required.

Equals(): Determines whether the specified object is equal to the current object.

Find(): Searches for an element that matches the conditions defined by the
specified predicate, and returns the first occurrence within the entire Array.

Resize(): Changes the number of elements of a one-dimensional array to the


specified new size.

Reverse(): Reverses the order of the elements in a one-dimensional Array or in


a portion of the Array.

Sort(): Sorts the elements in a one-dimensional array.

Example 1: Reverse
class sample
{
public static void Main()
{
string[] names;
names = new string[] { "ram", "sita", "hari", "gita" };
Console.WriteLine("Before reverse Namelist:");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}

Array.Reverse(names);
Console.WriteLine("\nAfter reverse Namelist:");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
}
}

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


12
Output:
Before reverse Namelist:
ram
sita
hari
gita

After reverse Namelist:


gita
hari
sita
ram

Example 2: Sort
class sample
{
public static void Main()
{
string[] names;
names = new string[] { "ram", "sita", "hari", "gita" };
Console.WriteLine("Namelist:");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
Array.Sort(names);
Console.WriteLine("\nNamelist after sort:");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
}
}

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


13
Output:
Namelist:
ram
sita
hari
gita

Namelist after sort:


gita
hari
ram
sita

Er Ranjeet Kumar Singh @Visual Programming (Unit-3)


14

You might also like