Wednesday, September 28, 2022
HomeC ProgrammingC program to swap two numbers utilizing macro

C program to swap two numbers utilizing macro


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 standard drawback. We already mentioned a number of methods to swap two variables all through the course of C programming tutorial.

Swap two numbers utilizing macros

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

Required information

Fundamental C programming, Macros, Bitwise operator

How you can swap two numbers utilizing macro

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

For this publish I’ll swap two numbers with out utilizing third variable. I’ll make use of bitwise operator. When you’ve got 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
 */

#embody <stdio.h>

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

int major()
{
    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 😉

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments