1

hey guys i want your suggestion that how can change value of two variables without 3rd one. in objective cc. is there any way so please inform me,

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
Anjan
  • 360
  • 1
  • 5
  • 20

5 Answers5

12

it can be done in any language. x and y are 2 variables and we want to swap them

{
  //lets say x , y are 1 ,2
  x = x + y; // 1+2 =3
  y = x - y; // 3 -2 = 1
  x = x -y; // 3-1 = 2;
}

you can use these equation in any language to achieve this

Arpit Agarwal
  • 3,993
  • 24
  • 30
  • 1
    +1, Simple logic for swaping two variables without using third one. logic is one you can implement in any language – Ishu Mar 10 '11 at 04:16
  • What's interesting is that it even works if x+y overflows x, provided the operation "wraps around" in that case, which is common. That makes it attractive on micro-controllers where registers and RAM are scarce and accessing RAM can be expensive (possibly more expensive than three register arithmetic operations). Nice. I'd never use it in Objective C, but still, nice. (XOR swap is probably still more efficient, but I like this.) – Rob Napier Aug 01 '11 at 15:47
7

Do you mean exchange the value of two variables, as in the XOR swap algorithm? Unless you're trying to answer a pointless interview question, programming in assembly language, or competing in the IOCCC, don't bother. A good optimizing compiler will probably handle the standard tmp = a; a = b; b = tmp; better than whatever trick you might come up with.

If you are doing one of those things (or are just curious), see the Wikipedia article for more info.

Anomie
  • 92,546
  • 13
  • 126
  • 145
1

As far as number is concerned you can swap numbers in any language without using the third one whether it's java, objective-C OR C/C++,

For more info

Potential Problem in "Swapping values of two variables without using a third variable"

Community
  • 1
  • 1
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
1

Since this is explicitly for iPhone, you can use the ARM instruction SWP, but it's almost inconceivable why you'd want to. The complier is much, much better at this kind of optimization. If you just want to avoid the temporary variable in code, write an inline function to handle it. The compiler will optimize it away if it can be done more efficiently.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
0

NSString * first = @"bharath"; NSString * second = @"raj";

first = [NSString stringWithFormat:@"%@%@",first,second];

NSRange needleRange = NSMakeRange(0,
                                  first.length - second.length);

second = [first substringWithRange:needleRange];

first = [first substringFromIndex:second.length];
NSLog(@"first---> %@, Second---> %@",first,second);
Bharrath
  • 79
  • 1
  • 5