Program for Swapping Numbers

Swapping of Given Numbers

We will write a C program to display the swapping of the given numbers and the number will be entered by the user. This will help to understand the basic structure of programming. In this program , we will display the swapping of given numbers easily by using proper syntax and algorithms.

Program for Swapping Numbers

Working of Program :

In the program, we will require some numbers from the user to display the swapping of the given numbers.

Important Note :

  • Swapping of numbers refers to the interchange of the position of value.
  • Let us assume if a variable ‘A’ stores the value which is equal to 500 and another variable ‘B’ stores the value which is equal to 1000. Then after swapping these values, variable ‘A’ stores the value that will be equal to 1000 and ‘B’ stores the value that will be equal to 500. i.e. Before swapping A=500 and B=1000 , After swapping A=1000 and B=500

Problem 1

Write a program to swap two numbers using third variable.

  • Firstly, we have to enter the any number.
  • Then print the swapped number.

Code

Run
#include<stdio.h>
int main ()
{
  int a, b, c;
  printf ("Enter the number a & b = ");
  scanf ("%d%d", &a, &b);
  c = a;
  a = b;
  b = c;
  printf ("a=%d", a);
  printf ("\nb=%d", b);
  return 0;
}

Output

Enter the number a & b = 45
89
a=89
b=45

Note:

In the following program we will swap the given number without using third variable.

Problem 2

Write a program to swap the given number without using third variable.

  • Firstly, we have to enter the any number.
  • Then print the swapped number.

Code

Run
#include<stdio.h>
int main ()
{
  int a, b;
  printf ("Enter the number a & b = ");
  scanf ("%d%d", &a, &b);
  a = a + b;
  b = a - b;
  a = a - b;
  printf ("After swapping the value of a = %d", a);
  printf ("\nAfter swapping the value of b = %d", b);
  return 0;
}

Output

Enter the number a & b = 500
1000
After swapping the value of a = 1000
After swapping the value of b = 500

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription