Can someone help me with a program in SHarpdevelop to save non-repeated numbers with an array? [duplicate]

-1
public static void Main(string[] args)
        {
            int[] elementos=new int [10];
            int i=1;//que empieze a guardar desde 0
            int numero=0;

            while (i<11)
            {
                Console.WriteLine("Proporcione un elemento {0}",i);
                numero=Convert.ToInt32(Console.ReadLine());

            i++;


            }


            Console.ReadKey(true);
        }
    }
}
    
asked by rosa 15.04.2018 в 06:53
source

2 answers

0

In the example I changed the type of the variable elements . Instead of being an array of integers, it is now an ArrayList. This I have done because it has the 'Contains' method, which returns a boolean depending on whether the indicated value is inside the arraylist or not.

As you can see, the only thing I added inside the loop is the following condition:

    if (!elementos.Contains(numero))
        elementos.Add(numero);

What it does is add the number selected by the user as long as it does not already exist in the arraylist.

    static void Main(string[] args)
    {
        //int[] elementos = new int[10];
        ArrayList elementos = new ArrayList();
        int i = 1;//que empieze a guardar desde 0
        int numero = 0;

        while (i < 11)
        {
            Console.WriteLine("Proporcione un elemento {0}", i);
            numero = Convert.ToInt32(Console.ReadLine());

            if (!elementos.Contains(numero))
                elementos.Add(numero);

            i++;
        }

        Console.ReadKey(true);
    }
    
answered by 15.04.2018 в 09:36
0

my method is similar to how zeross solved it, however I still use the int [] elements:

using System.Linq; //nota: Es importante agregar esto, de lo contrario no funciona.

static void Main(string[] args)
{
    int[] elementos = new int[10];        
    int i = 1;//que empieze a guardar desde 0
    int numero = 0;

    while (i < 11)
    {
        Console.WriteLine("Proporcione un elemento {0}", i);
        numero = Convert.ToInt32(Console.ReadLine());

        if (!elementos.Contains<int>(numero))
        {
             elementos[i] = numero;
             i++;
        }            
    }

    Console.ReadKey(true);
}

In this way the Contains method is used < > that comes from System.Linq and by putting the i ++ inside the if it ensures that the number is requested again since the one that was entered is repeated.

    
answered by 16.04.2018 в 16:43