In C#, a cluster can be announced with a fixed size length and a variable length. Here and there it’s necessary that we have to have a variety of fixed length.
In this instructional exercise, we will figure out how to proclaim a variety of fixed size length, how to pronounce an exhibit with a variable length, for example, input cluster length at run time, how to print exhibit length (utilizing Array.Length property),
how to include cluster components at run time and how to print exhibit components?
Syntax
<data_type>[] array_name = new <data_type>[size];
Example:
int[] arr = new int[10];
1) C# example to declare a fixed-size array, input and print array element
using System;
using System.Text;
using System.Collections;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//declaring a 10 elements integer array
int[] arr = new int[10];
//printing size
Console.WriteLine("Array size is: " + arr.Length);
//printing array
Console.WriteLine("Array elements...");
foreach (int item in arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
//input and assigning elements to the array
for (int i = 0; i < arr.Length; i++)
{
Console.Write("Enter " + i + " element: ");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
//printing array
Console.WriteLine("Array elements...");
foreach (int item in arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
Array size is: 10
Array elements...
0 0 0 0 0 0 0 0 0 0
Enter 0 element: 10
Enter 1 element: 20
Enter 2 element: 30
Enter 3 element: 40
Enter 4 element: 50
Enter 5 element: 60
Enter 6 element: 60
Enter 7 element: 80
Enter 8 element: 90
Enter 9 element: 55
Array elements...
10 20 30 40 50 60 60 80 90 55
2) C# example to Input length, declare an array at run time
using System;
using System.Text;
using System.Collections;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//variable to store length
int len = 0;
//input array length
Console.Write("Enter array length: ");
len = Convert.ToInt32(Console.ReadLine());
//declaring array of len size at run time
int[] arr = new int[len];
//printing size
Console.WriteLine("Array size is: " + arr.Length);
//printing array
Console.WriteLine("Array elements...");
foreach (int item in arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
//input and assigning elements to the array
for (int i = 0; i < arr.Length; i++)
{
Console.Write("Enter " + i + " element: ");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
//printing array
Console.WriteLine("Array elements...");
foreach (int item in arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
Enter array length: 5
Array size is: 5
Array elements...
0 0 0 0 0
Enter 0 element: 100
Enter 1 element: 200
Enter 2 element: 300
Enter 3 element: 400
Enter 4 element: 500
Array elements...
100 200 300 400 500