Home > database >  Find unique number in array in fill list with this unique numbers using for loops
Find unique number in array in fill list with this unique numbers using for loops

Time:12-29

I'm trying to use for loop inside for loop but it doesn't working i also tried while loop but...

int[] numArray = new int[10] {1,2,2,3,3,4,4,5,5,9};
List<Int32> uNum = new List<Int32>();
/*Random rnd = new Random();

for (int i = 0; i < numArray.Length; i  )
{
    int randomNumber = rnd.Next(0, 10);
    numArray[i] = randomNumber;
}*/
for (int i = 0; i < numArray.Length; i  )
{
    if (numArray[i] != numArray[i])
    {
        for (int j = 0; j < numArray.Length-1; j  )
        {
            if (numArray[i] != numArray[j])
            {
                uNum.Add(numArray[i]);
            }
        }
    }
}

CodePudding user response:

You have an error in this line:

if (numArray[i] != numArray[i])

This condition will always return False because a number is always equal to itself.

Do something like this:

    for (int i=0; i<numArray.Length; i  )
    {
        int j;
        for (j=0; i<numArray.Length; j  ){
         if (i != j){
            if (numArray[i] != numArray[j])
             {
                uNum.Add(numArray[i]);
             }
          }
        }
          
    }

CodePudding user response:

int[] numArray = new int[10];
List<Int32> uNum = new List<Int32>();
Random rnd = new Random();
for (int i = 0; i < numArray.Length; i  )
{
    int randomNumber = rnd.Next(0, 10);
    numArray[i] = randomNumber;
}
for (int i = 0; i < numArray.Length; i  )
{
    int num = numArray[i];
    int count = 0;
    for (int j = 0; j < numArray.Length; j  )
    {
        if (numArray[j] == num)
        {
            count  ;
        }
    }
    if (count == 1)
    {
        uNum.Add(num);
    }
}
  • Related