Sudent
Sudent

Reputation: 15

Find all possible pairs in an array c

I have a an int array num[] = { 1,2,3,} and I want to show all the possible pairs, but not the one that repeat to itself like 1 1 or 2 2 example:

1 2, 
1 3,
2 1,
2 3, 
3 1, 
....

this is what i have

int numb1[4] = {  1, 2,3,4,};

int i = 0;
int k = 0;

for(i ; i < 4 ; i++)
{
  for( k; k < 4; k++)
  {
     if(k != i)
     {
       printf("%d ",numb1[i]);
       printf("%d", numb1[k]);
     }
  }
}

my output is 12 13 14 I am programming in C.

Upvotes: 0

Views: 916

Answers (3)

Siva Makani
Siva Makani

Reputation: 216

Your code looks fine.

    # include <stdio.h>

    int main()
    {
    int numb1[4] = {  1, 2,3,4,};

    int i = 0;
    int k = 0;

    for(i ; i < 4 ; i++)
    {
      for( k=0; k < 4; k++)    // Modified
      {
         if(k != i)
         {
            printf("%d ",numb1[i]);
            printf("%d,\n", numb1[k]);   // Delimmiters
         }
      }
    }
    }

Upvotes: 3

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

in the second for loop, you need to initialize k to 0, like this for(k = 0; k < .....)

Upvotes: 0

Nathan Fellman
Nathan Fellman

Reputation: 127578

You're not initializing the loop variable k, which is used in the inner loop at each iteration of i.

Upvotes: 2

Related Questions