In this tutorial, we will write a C# program to find the length of an array entered by the user, we have used while loop and try–catch block for the exception
Question:
Write a C# program to find the length of an Array.
Solution:
Here first we take the arrays from the user and to exit from an array user need to enter –999 at last. -999 is an exit value that is defined at the beginning of the program.
To take the user input, while loop is used inside which try-and catch blocks are executed. lastly array.Length is used to get how many elements the user entered.
C# Program to find the length of an Array.
It can also be done without the use of try-catch block
Source Code
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] arg)
{
//CONSTANT VALUE TO EXIT
const int EXIT_VALUE = -999;
List<int> numbers = new List<int> ();
Console.WriteLine("Enter the number and press -999 at the end:");
while (true)
{
try
{
var input = Console.ReadLine();
int i = int.Parse(input);
if (i == EXIT_VALUE) break;
numbers.Add(i);
}
catch (System.Exception ex)
{
Console.WriteLine("Invalid Input!!");
}
}
int[] array = numbers.ToArray();
Console.WriteLine("Length of an Array is:{0}", array.Length);
}
}
Output:
