Answer to Question #273680 in C# for Holik

Question #273680

2. Create a program that determines the number of the smallest element of a given one-dimensional array.

1
Expert's answer
2021-11-30T18:41:04-0500
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;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS