C program to swap two numbers utilizing macro

[ad_1]

Write a C program to swap two numbers utilizing macro. How swap two numbers with out utilizing third variable utilizing macro in C program. Logic to swap two quantity with out utilizing third variable utilizing macro.

 

Swapping values of two variables is a typical downside. We already mentioned a number of methods to swap two variables all through the course of C programming tutorial.

Swap two numbers using macros
Swap two numbers utilizing macros

On this put up we are going to proceed our macro train. Right here I’ll clarify how one can rework swapping logic to macro.

Required data

Primary C programming, Macros, Bitwise operator

The right way to swap two numbers utilizing macro

Earlier than transferring forward, I assume that you’re conscious with macro syntax, how one can outline and use.

For this put up I’ll swap two numbers with out utilizing third variable. I’ll make use of bitwise operator. You probably have any associated to bitwise operator logic please learn how one can swap two numbers utilizing bitwise operator.

Allow us to get began and outline a macro that accepts two arguments say SWAP(x, y). The macro will swap the values of x and y.

Instance:

#outline SWAP(x, y) (x ^= y ^= x)

Program to swap two numbers utilizing macro

/**
 * C program to swap two numbers utilizing macro
 */

#embrace <stdio.h>

// Outline macro to swap two numbers
#outline SWAP(x, y) (x ^= y ^= x ^= y)

int essential()
{
    int num1, num2;

    // Enter two numbers from customers
    printf("Enter any two quantity to swap: ");
    scanf("%dpercentd", &num1, &num2);

    printf("Values earlier than swappingn");
    printf("num1 = %d, num2 = %dnn", num1, num2);

    SWAP(num1, num2);

    printf("Values after swappingn");
    printf("num1 = %d, num2 = %dn", num1, num2);

    return 0;
}
Enter any two quantity to swap: 10 20
Values earlier than swapping
num1 = 10, num2 = 20

Values after swapping
num1 = 20, num2 = 10

Joyful coding ?

[ad_2]

Leave a Reply

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