Write a C program to swap values!

Yes, Let’s write a C program to swap values. This post is useful for school students and those who are learning C programming themselves.

Swapping values are not so difficult, all you have to do is store one of the value in a temp variable and then interchange the values.

See the below small snippet of how to swap two values:

//swap the values
temp = a;
a = b;
b = temp;

Now let’s write a complete C program on how to get the values and swap them.

#include <stdio.h>
int main()
{
  int a, b, temp;

  printf("Original Values:\n");
      
  //get value a
  printf("a: ");
  scanf("%d", &a);
  
  //get value b
  printf("b: ");
  scanf("%d", &b);
  
  //swap the values
  temp = a;
  a = b;
  b = temp;
  
  //now print the swapped values
  printf("\nSwapped Values:\n");
  printf("a: %d\n", a);
  printf("b: %d\n", b); 
  
  return 0;
}

The output of the above program will be:

Original Values:
a: 30
b: 50

Swapped Values:
a: 50
b: 30

Enjoy learning!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top