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.
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;
}
}
}
}
}
}
Comments
Leave a comment