Search code examples
c#arraysshortest

C# finding the shortest and longest word in a array


I am trying to find the shortest and longest string value based on length and im getting stuck. As of now the script exits after the writeline. I think the code needs some help, I dont think a for loop can work on its own. Any assistance would be appreciated.

        for (int i = 5; i <0; i++)
        {
            string[] word = new string[5];
           Console.WriteLine("Type in a word");
            word[i] = Console.ReadLine();

             int length = word[i].Length;
             int min = word[0].Length;
             int max = word[0].Length;
             string maxx;
             string minn;


              if (length > max)
                 {
                   maxx = word[i];
                   Console.Write("Shortest");
                  }
             if (length < min) 
              {
                 minn = word[i];
                Console.Write("Longest");
              }



         }
        Console.ReadKey(true);
    }

Solution

  • string[] word = new string[5];
    for (int i = 0; i <= word.Length; i++)
    {
    
        Console.WriteLine("Type in a word");
        word[i] = Console.ReadLine();
    }
    int min = word[0].Length;
    int max = word[0].Length;
    string maxx = word[0];
    string minn = word[0];
    for (int i = 1; i <= word.Length; i++)
    {
        int length = word[i].Length;
        if (length > max)
        {
            maxx = word[i];
            max = length;
        }
        if (length < min)
        {
            minn = word[i];
            min = length;
            Console.Write("Longest");
        }
    }
    Console.Write("Shortest:" + maxx);
    Console.Write("Longest" + minn);
    Console.ReadKey(true);