Write a c program to perform Swapping on two number

Swap two number

C program to swapping two number

In this program, you will show how to write a program to swapping on two numbers. Swapping means to interchanging. For example, if in your C program you have taken two variables c and d. Where c = 25 and d = 35, then before swapping c = 25, d = 35, after swapping c = 35, d = 25. 

Swapping of two number in C program

#include <stdio.h>

int main()
{
  int c, d, t;

  printf("Enter Two Integers\n");
  scanf("%d%d", &c, &d);

  printf("Before Swapping\n First Integer = %d\n Second Integer = %d\n", c, d);

  t = c;
  c = d;
  d = t;

  printf("After Swapping\n First Integer = %d\n Second Integer = %d\n", c, d);

  return 0;
}

Output of Program:


Swapping Program






Swapping  two number without third variable


You can also be swapping two numbers without using the third variable. In that case, you will be as follows the C program:


#include <stdio.h>

int main()
{
   int c, d;
   
   printf("Enter Two Integer Number:\n");
   
   scanf("%d%d", &c, &d);
   
   c = c + d;
   d = c - d;
   c = c - d;

   printf("c = %d\n d = %d\n ",c,d);
   return 0;
}



Output of Program:

Swap Without Third Variable





Swap two numbers using pointers variable


In this program, you can also swap two numbers using the pointer variable. You will follow the C program.


#include <stdio.h>
int main()
{
   int x, y, *a, *b, temp;
   printf("Enter the value of x and y\n");
   scanf("%d%d", &x, &y);
   printf("Before Swapping\n x = %d\n y = %d\n", x, y);
   
   a = &x;
   b = &y;
   
   temp = *b;
   *b   = *a;
   *a   = temp;
   printf("After Swapping\n x = %d\n y = %d\n", x, y);
   
   return 0;
}



Output of Program:

Swapping two number using pointers






Post a Comment

0 Comments