c++swap

Swapping values of two variables without using a third one- Array


I am writing a program which takes user input to determine pair of numbers and swaps values of all the pairs entered by the user.

For example:

User wants to enter 3 pairs, then he would enter 3 followed by pairs:

3 1 2 3 4 5 6

Output:

2 1 4 3 6 5

My program is giving proper output but instead of taking all pairs at once, it takes them one by one and gives the output. I have a vague idea that this can be resolved by using array but not sure how. Please help.

Here is my code:

#include <stdio.h>
int main()
{
    int x, y, p, i;
   //int a [100], b[100];
    printf ("How many pairs?\n");
    scanf ("%d", &p);
    for(i=1; i<=p; i++)
    {
       printf ("Enter two values:\n");
       scanf("%d %d",&x,&y);

       x = x + y;  
       y = x - y;  
       x = x - y;
      //a[i]=x;
      //b[i]=y;



      printf("\n");
      printf("After Swapping: x = %d, y = %d\n", x, y);
     }

     return 0;
}

Currently the output looks like:

How many pairs? 2

Enter two values: 2 3

After swapping x= 3 and y=2

Enter two values: 4 5

After swapping x= 5 and y=4. I want it to take all 4 values together and display output.


Solution

  • You can store them in an array (like you were trying to in some of the commented code), and then swap them one by one.

    #include <stdio.h>
    int main()
    {
        int x, y, p, i;
        printf ("How many pairs?\n");
        scanf ("%d", &p);
        int a[p],b[p];
        for(i=0; i<p; i++)
        {
            printf ("Enter values for pair %d:\n", i+1);
            scanf("%d %d",&a[i],&b[i]);
        }
        for(i=0; i<p; i++)
        {
            x = a[i];
            y=b[i];
            x = x + y;  
            y = x - y;  
            x = x - y;
            printf("Pair %d After Swapping: x = %d, y = %d\n", i+1, x, y);
        }
    
         return 0;
    }