How to assing value to tab by variable c#

282 Views Asked by At

I'm trying to make program to sort tabs but I can't make working table. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SorotwanieTablic
{
    class Program
    {
        static int NumberOfObjectInTab;

        static void Numb(int NumberOfObjectInTab)
        {
            do
            {
                Console.WriteLine("Wprowadź  liczbę  elementów do posortowania <1 .. 10>: ");

                Program.NumberOfObjectInTab = int.Parse(Console.ReadLine());
            }
            while (NumberOfObjectInTab < 0 || NumberOfObjectInTab > 10);

        }

static int[] tab = new int[NumberOfObjectInTab];

        static void InsertValuesToTab(int[] tab)

        {
           for (int i=0; i < tab.Length; i++)
            {
                Console.WriteLine("Wprowadź  liczbę  [{0}] ", i);
                tab[i] = int.Parse(Console.ReadLine());
            }           
        }




        static void Main(string[] args)
        {
            Numb(NumberOfObjectInTab);
            InsertValuesToTab(tab);
            Console.WriteLine("\nprzed sortowaniem ");
            foreach (int i in tab) Console.Write(+i + " ");
            Array.Sort(tab);
            Console.WriteLine("\nPO Posortowaniu ");
            foreach (int i in tab) Console.Write( + i + " ");


            Console.Read();

        }
    }
}

How user can enter the size of tab from keyboard? I dunno what to do. I tried return NumberOfObjectInTab but nothing changes. With void and with int there is still same value to tab. It sort if I change to static int[] tab = new int[5]; (for example) but... I must have size of tab defined by user, not by code.

1

There are 1 best solutions below

1
James On BEST ANSWER

Break your application down into the functions it needs to perform the desired work. Maybe start with non-implementation first. The create the implementations.

 static int sizeOfTab;
 static int[] tab;



static void Main(string[] args)
{
        CollectSizeOfTab(args);

        CreateTab();

        InsertValuesToTab(tab);

        Sort(tab);

}

static void CollectSizeOfTab(string[] args)
{
    do
    {
      Console.WriteLine("Wprowadź  liczbę  elementów do posortowania <1 .. 10>: ");

      sizeOfTab = int.Parse(Console.ReadLine());
    }while (sizeOfTab < 0 || sizeOfTab > 10);
}

static void CreateTab(){tab = new int[sizeOfTab];}
static void InsertValuesToTab(int[] tab){...}
static void Sort(int[] tab){...}

How user can enter the size of tab from keyboard?

Console.Write("Enter size of tab:");
var response = Console.ReadLine();