LouieV1994
LouieV1994

Reputation: 11

Operations within one Vector C++

Ok, so I have this bit of code:

 for(i=0; i<listSize; i++)
 {
      for(j=0; j<listSize; j++)
      {

              if(i != j)
              {
                 remainder = numList[i] % numList[j];
              }
              if( numList[i] % numList[j] == 0)
              {
                  cout<< numList[i] << " " << numList[j]<<endl;
              }
      }
}

How can I perform a modulus comparison without comparing an element against itself? The 1st if statement is not achieving this.

Upvotes: 0

Views: 53

Answers (2)

ciamej
ciamej

Reputation: 7068

If the numbers in numList are not unique, you need to check if two elements of the list with a different index have the same value. Otherwise, you'd get a division by zero.

for(i=0; i<listSize; i++)
{
    for(j=0; j<listSize; j++)
    {
        if(numList[i] != numList[j])
        {
            remainder = numList[i] % numList[j];
            if(remainder == 0)
            {
                cout<< numList[i] << " " << numList[j]<<endl;
            }
        }
    }
}

Upvotes: 0

nicomp
nicomp

Reputation: 4647

     for(i=0; i<listSize; i++)
      {
          for(j=0; j<listSize; j++)
          {

              if(i != j)
              {
                 remainder = numList[i] % numList[j];

                  if( numList[i] % numList[j] == 0)
                  {
                      cout<< numList[i] << " " << numList[j]<<endl;
                  }
              }
          }

Upvotes: 2

Related Questions