Swap two numbers without using third variable

SWAPPING TWO NUMBERS WITHOUT USING A THIRD VARIABLE

There are two common ways to swap two numbers without using a third variable:

PROGRAM 1 (Using addition and Subtraction):

#include <stdio.h>

int main()

{

    int a,b;

    printf("enter the value of a: ");

    scanf("%d",&a);

    printf("enter the value of b: ");

    scanf("%d",&b);

    printf("Before swapping, a=%d b=%d.",a,b);

    a=a+b;

    b=a-b;

    a=a-b;

    printf("\nAfter swapping, a=%d b=%d.",a,b);

    return 0;

}




PROGRAM 2 (Using Bitwise XOR):

#include <stdio.h>

int main()
{

    int a,b;

    printf("enter the value of a: ");

    scanf("%d",&a);

    printf("enter the value of b: ");

    scanf("%d",&b);

    printf("Before swapping, a=%d b=%d.",a,b);

    a=a^b;

    b=a^b;

    a=a^b;

    printf("\nAfter swapping, a=%d b=%d.",a,b);

    return 0;

}




TIME COMPLEXITY:

The time complexity is O(1) because the code performs a fixed number of operations  regardless of the size of the input. This means the time taken to execute the code remains constant, even if the input values increase.


SPACE COMPLEXITY:

The space complexity is O(1) because only a constant amount of extra space is used to store the variables a and b. The space usage does not grow with the size of the input, so it remains constant.


Comments

Popular posts from this blog

Program to check leap year

Check a number is palindrome or not