2. Create a program that determines the number of the smallest element of a given one-dimensional array.
using System;
namespace ConsoleAppNumberOfTheSmallestElement
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the elements of the one - dimensional array separated by commas.");
string enteredString = Console.ReadLine();
try
{
string[] arrayString = enteredString.Split(',');
int[] numbers = new int[arrayString.Length];
for (int i = 0; i < arrayString.Length; i++)
{
if(!int.TryParse(arrayString[i], out numbers[i]))
{
Console.WriteLine("Incorrect data entered.");
break;
}
}
Console.WriteLine(FindNumberOfTheSmallestElement(numbers));
}
catch(Exception ex)
{
Console.WriteLine("Incorrect data entered.");
}
Console.ReadKey();
}
static int FindNumberOfTheSmallestElement(int[] arr)
{
int indexOfSmallestElement = 0;
for(int i=0; i<arr.Length; i++)
{
if (arr[i] < arr[indexOfSmallestElement]) //check if the current index points to a smaller element
indexOfSmallestElement = i; //change the index to the current one
}
return indexOfSmallestElement+1;
}
}
}
Comments
Leave a comment