#include <stdio.h>
#include <stdlib.h>

void main()
{
    int a=5,b=10,*ptr,*pt1;
    ptr=&a;
    pt1=&b;
    b=*ptr;
    a=*pt1;
    printf("%d \n %d",a,b);



}

producing same values not swapped

you need to use an intermediate integer.

int a,b,temp;

temp = a
a = b
b = temp

And before anyone chimes in with swaps using XOR or arithmetic operators that they think are clever: your solution is bad, and you should feel bad.

commented: Nice. And correct! +14

Hi Deceptikon,

And before anyone chimes in with swaps using XOR or arithmetic operators that they think are clever: your solution is bad, and you should feel bad.

why one should not use XoR or arithmetic operation to swap number??? can you please explain it?
Then how to swap numbers without using temparory variable.

why one should not use XoR or arithmetic operation to swap number???

Because it's inferior to using a temporary variable, and the original reason for avoiding a temporary variable is totally irrelevant unless you're on a severely memory constrained platform. And by "severely", I mean so much that you actually map out your register usage and design algorithms to avoid stack or heap use. Oh, and this also assumes that you're writing your code directly in assembly because C is just too heavy.

Then how to swap numbers without using temparory variable.

http://en.wikipedia.org/wiki/XOR_swap_algorithm

 #include <stdio.h>
    #include <stdlib.h>

    void main()
    {
    int a=5,b=10,*ptr,*pt1;
   *ptr=a+b-a;
   *pt1=a+b-b;
   a=*ptr;
   b=*pt1;
   printf("%d",a);
   printf("%d",a);


  }

will this work sir????

sigh

This will work and is correct:

#include <stdio.h>

int main(void)
{
    int a = 5, b = 10;
    int temp;

    printf("%d %d\n", a, b);

    temp = a;
    a = b;
    b = temp;

    printf("%d %d\n", a, b);

    return 0;
}

will this work sir????

What part of

you need to use an intermediate integer.

int a,b,temp;

temp = a
a = b
b = temp

did you not understand?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.