settingsAccountsettings
Menusettings

Q: How to sort unknown number of numbers in C# with array or list?

+3 votes

Hi, please help me with this task:

Write a program that reads a number n and a sequence of n integers, sorts them and prints them.

Examples:

sort numbers c# example

sort numbers in c sharp examplle

asked in C# category by user matthew44

2 Answers

+1 vote

Here is my solution with arrays and the Sort method of the Array Class:

using System;

class SortingNumbers
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        int[] arrayNumbers = new int[n];

        for (int i = 0; i < n; i++)
        {
            arrayNumbers[i] = int.Parse(Console.ReadLine());
        }

        Array.Sort(arrayNumbers);

        foreach (var VARIABLE in arrayNumbers)
        {
            Console.WriteLine(VARIABLE);
        }
    }
}

 

answered by user hues
+1 vote

My solution with List:

using System;
using System.Collections.Generic;

class SortingNumbers
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());

        List<int> input = new List<int>(n);

        for (int i = 0; i < n; i++)
        {
            int num = int.Parse(Console.ReadLine());
            input.Add(num);
        }

        input.Sort();

        foreach (var VARIABLE in input)
        {
            Console.WriteLine(VARIABLE);
        }
    }
}
answered by user Jolie Ann
edited by user golearnweb
...