C Program to swap two numbers without using third variable

In this article, I will show you how you can write a C Program to swap two numbers without using third variable. I will explain the algorithm, concepts and then help you to write C Program to swap two numbers without using third variable.

1. Program Outline

In this article, we will be writing a C Program to swap two numbers without a third variable. Generally, we take three variables to swap the values of two numbers. But it cost us an additional space in memory. If we work on a big program and we will use the old approach we’ll end up with huge space and more server costs. So, this program to swap two numbers without using a third variable will help us in the future to solve big problems and optimize our C Program.

I will explain to you the concept of this program and guide you through that algorithm we will use to swap two numbers without a third variable. After explaining the algorithm we will write the program that will help us to swap two numbers without using a third variable. At the end, I will provide a output and the resources so, you can try this program on your device or computer. So, Let’s begin with this program.

2. Concepts

To write this C Program to swap two numbers without using third variable, you need to learn the following concepts of C Programming:

  1. Input: To write this program, you must know, how to take input in a C program from the end-user.
  2. Arithmetic Operations: To swap these two numbers without using the third variable we need to have knowledge of how to use Arithmetic operators in the C Program.
  3. Output: After swapping two numbers without a third variable, you need to output the result. So, you must have knowledge about how to output result in C Program

3. Algorithm

To write this C program to swap two numbers without using third variable, we’ll use this Algorithm:

STEP 1: START
STEP 2: INPUT A,B
STEP 3: OUTPUT A,B
STEP 4: A = A + B
STEP 5: B = A - B
STEP 6: A = A - B
STEP 7: OUTPUT A,B
STEP 8: STOP

4. Program

Here’s the C Program to swap two numbers without using third variable:

#include <stdio.h>
int main()
{
   int a, b;
    
   printf("Enter two numbers (a & b) to swap without using third variable:\n");
   scanf("%d%d", &a, &b);
   /* Program by codewin.org */
   a = a + b;
   b = a - b;
   a = a - b;
 
   printf("Here are the swapped values without using third variable: a = %d\nb = %d\n",a,b);
   printf("CodeWin.org - Winning Hearts of Coders!!!");
   return 0;
}

5. Output

Here’s the output of the above C Program:

C Program to swap two numbers without using third variable
groot
groot

Leave a Reply

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