Skip to content
doubtly

2 answers

Best answer

Answer: Swap with a temporary variable (t = a; a = b; b = t;) or without one (a = a + b; b = a - b; a = a - b;).

Logic:

  • Using a third variable: store a in t, copy b into a, then copy t into b.
  • Without a third variable: a becomes the sum a + b; then b = (a + b) - b gives the old a, and a = (a + b) - old a gives the old b.

Program:

#include <stdio.h>

int main()
{
    int a, b, t;

    /* (i) Using a third variable */
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    printf("Before swapping: a = %d, b = %d\n", a, b);
    t = a;
    a = b;
    b = t;
    printf("After swapping (using third variable): a = %d, b = %d\n", a, b);

    /* (ii) Without using a third variable */
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    printf("Before swapping: a = %d, b = %d\n", a, b);
    a = a + b;
    b = a - b;
    a = a - b;
    printf("After swapping (without third variable): a = %d, b = %d\n", a, b);

    return 0;
}

Sample output (actual run):

Enter two integers: 5 9
Before swapping: a = 5, b = 9
After swapping (using third variable): a = 9, b = 5
Enter two integers: 12 7
Before swapping: a = 12, b = 7
After swapping (without third variable): a = 7, b = 12
Doubtly · 23 Apr 2022 Report
Was this answer helpful?

Answer: two programs below swap two integers, one with a third variable and one without.

(a) Using a third variable

#include <stdio.h>

int main() {
    int a, b, temp;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    temp = a;   /* save a */
    a = b;      /* copy b into a */
    b = temp;   /* old a into b */

    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

(b) Without a third variable

#include <stdio.h>

int main() {
    int a, b;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    a = a + b;  /* a holds the sum   */
    b = a - b;  /* (a+b) - b = old a */
    a = a - b;  /* (a+b) - old a = old b */

    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

Example: input 5 and 9. In (b), a = 14, then b = 14 − 9 = 5, then a = 14 − 5 = 9. Output: a = 9, b = 5.

(The sum method can overflow for very large numbers; the XOR trick a ^= b; b ^= a; a ^= b; avoids that.)

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.