Exchanging 2 integer's value, exclude 3. integer (in C programming)

Discussion in 'Programming' started by Malatya, May 29, 2010.

  1. #1
    Hi, the question is simple but the answer isnt.)
    Exchange 2 integer's value except the third integer.For ex, x=10, y=20 we have to make x=20 and y=10 but we banned to use a 3. integer like integer z. I use pointers for it.
    
    #include <stdio.h>
    #include <stdlib.h>
    int main(){
    int *p,*q,x=10,y=20; //first values
    *q=x;
    *p=y;
    x=*q;
    y=*p;	
    printf("new x %d and y %d",x,y); //final values
    system("PAUSE");
    return 0;
    }
    
    
    Code (markup):
    Help me solving either finding a way.
     
    Malatya, May 29, 2010 IP
  2. lmtiger47

    lmtiger47 Peon

    Messages:
    31
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Much easier:

    
    
    
    void main()
    
    {
    
    int a,b;
    
    clrscr();
    
    printf("\n\n\t\tenter any two nos...");
    
    scanf("%d%d",&a,&b);
    
    a=a+b;
    
    b=a-b;
    
    a=a-b;
    
    printf("\n\n\t\tvalue of a=",a);
    
    printf("\n\n\t\tvalue of b=",b);
    
    getch();
    
    } 
    
    Code (markup):
     
    lmtiger47, May 31, 2010 IP
  3. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #3
    Do not use any temp variable or pointer. Use XOR '^' operation to do that for you.

    y = x ^ y;
    x = y ^ x;
    y = x ^ y;


    regards
     
    Vooler, Jun 1, 2010 IP
  4. ccoonen

    ccoonen Well-Known Member

    Messages:
    1,606
    Likes Received:
    71
    Best Answers:
    0
    Trophy Points:
    160
    #4
    That is rediculous Imtiger47... lol
     
    ccoonen, Jun 1, 2010 IP