Program to swap two numbers without using third variable

Write a program to swap two numbers without using a third variable.

Approach 1:

C Program

#include <stdio.h>
int main()
{
    int firstNumsecondNum;
    printf("Enter first number : ");
    scanf("%d", &firstNum);
    printf("Enter second number : ");
    scanf("%d", &secondNum);
    printf("Numbers before swap is first= %d, second= %d\n"firstNumsecondNum);
    firstNum = firstNum + secondNum;
    secondNum = firstNum - secondNum;
    firstNum = firstNum - secondNum;
    printf("Numbers after swap is first= %d, second= %d\n"firstNumsecondNum);
    return 0;
}
Approach 2: Any number will not be 0.
C Program

#include <stdio.h>
int main()
{
    int firstNumsecondNum;
    printf("Enter first number : ");
    scanf("%d", &firstNum);
    printf("Enter second number : ");
    scanf("%d", &secondNum);
    printf("Numbers before swap is first= %d, second= %d\n"firstNumsecondNum);
    firstNum = firstNum * secondNum;
    secondNum = firstNum / secondNum;
    firstNum = firstNum / secondNum;
    printf("Numbers after swap is first= %d, second= %d\n"firstNumsecondNum);
    return 0;
}


Input:

Enter first number : 10
Enter second number : 20
Output:

Numbers before swap is first= 10, second= 20
Numbers after swap is first= 20, second= 10


No comments:

Post a Comment