C Program to swap two numbers

This answer is restricted. Please login to view the answer of this question.

Login Now

To swap any two numbers, there are many ways using c programming language.

  1. Using Temporary Variables
  2. Without using Temporary Variables

1. Using Temporary Variables

In this program, First we will assign first variable to temporary variable. Then we will assign second variable to first variable. And finally assign temporary variable to  second variable.

#include<stdio.h> 
int main() {
    double first, second, temp;

    printf("Enter first number: ");
    scanf("%lf", &first);

    printf("Enter second number: ");
    scanf("%lf", &second);

    temp = first;
    first = second;
    second = temp;

    printf("\nAfter swapping, first number = %.2lf\n", first);
    printf("After swapping, second number = %.2lf", second);
    return 0;
}

2. Without Using Temporary Variables

#include <stdio.h>
int main() {
    double a, b;
    printf("Enter a: ");
    scanf("%lf", &a);
    printf("Enter b: "); 
    scanf("%lf", &b);

    a = a - b;   
    b = a + b;
    a = b - a;
    
    printf("After swapping, a = %.2lf\n", a);
    printf("After swapping, b = %.2lf", b);

    return 0;
}

 

If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .