C Program to swap two numbers without using third variable

swapping without third variable
     Below there is simple and easy program to swap two elements without using third variable along with its flowchart algorithm and output. Let assume there are 2 variable 'a' and 'b'. first we add both the numbers and store it in first variable that is 'a'. Now we subtract 'b' from 'a' (addition of a and b) and store it in b thus we swap b into a. Similarly we do for another variable.


a = a + b
b = a - b
a = a - b


Program:

#include <stdio.h>
#include <conio.h>
/* Swap numbers without using temporary variable By SlashMyCode.com*/
int main()
{
  int a,b;
  printf("Enter value for A= ");
  scanf("%d",&a);

  printf("Enter value for B= ");
  scanf("%d",&b);
  // Code to swap 'a' and 'b'
  a = a + b;
  b = a - b;  // b becomes a
  a = a - b;  // a becomes b

  printf("\n After Swapping: \n\n A= %d, B= %d \n", a, b);
/* Swap numbers without using temporary variable By SlashMyCode.com*/
  getch();
  return 0;

}



Output:

Output of C program to swapping without third variable



Flowchart:
Flowchart of C program to swapping without third variable



Algorithm:

  1. Start
  2. Declare variable a and b.
  3. Accept values for a and b.
  4. a = a + b; 
  5. b = a - b;
  6. a = a - b;
  7. Print values of a and b.
  8. Stop





No comments:

Post a Comment

Feel free to ask us any question regarding this post