Answer to Question #301237 in C# for Dave

Question #301237

Write a program named SortWords that includes a method named SortAndDisplayWords that accepts any number of words from the user, sorts them in alphabetical order, and displays the sorted words separated by spaces. Test using two, five, or ten words.

1
Expert's answer
2022-02-22T12:13:13-0500


using System;
using System.Collections.Generic;
using System.Globalization;


namespace App
{
    class Program
    {


        static void Main(string[] args)
        {


            Console.Write("How many words to you want to sort?: ");
            int n = int.Parse(Console.ReadLine());
            string[] words = new string[n];


            for (int i = 0; i < n; i++)
            {
                Console.Write("Enter word {0}: ", (i+1));
                words[i] = Console.ReadLine();
            }


            SortAndDisplayWords(words);


            Console.Write("\n\nAfter sorting: \n");
            for (int i = 0; i < words.Length; i++)
            {
                Console.Write(words[i] + " ");
            }


            Console.ReadLine();
        }


        private static void SortAndDisplayWords(string[] words)
        {
            for (int i = 0; i < words.Length; i++)
            {
                for (int j = 0; j < words.Length - 1; j++)
                {
                    if (words[j].CompareTo(words[j + 1]) > 0)
                    {
                        string temp = words[j];
                        words[j] = words[j + 1];
                        words[j + 1] = temp;
                    }
                }
            }


        }
    }
}

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