Write a C Program to Swap Two Numbers Using Call by Reference

Swap Two Numbers Using Call by Reference


 

Write a C Program to Swap Two Numbers Using Call by Reference. Here’s simple Program to Swap Two Numbers Using Call by Reference in C Programming Language.


What are Pointers?


A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address.

The general form of a pointer variable declaration is

  • type *var-name;

Here, type is the pointer’s base type; it must be a valid C data type and var-name is the name of the pointer variable.

The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.

The unary or monadic operator & gives the “address of a variable'”.

The indirection or dereference operator * gives the “contents of an object pointed to by a pointer”.


Below is the source code for C Program to Swap Two Numbers Using Call by Reference which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :


 

/*  C Program to Swap Two Numbers Using Call by Reference  */

#include<stdio.h>

void cyclicSwap(int *a,int *b,int *c);

int main()
{
    int a, b, c;

    printf("Enter a :: ");
    scanf("%d",&a);
    printf("\nEnter b :: ");
    scanf("%d",&b);
    printf("\nEnter c :: ");
    scanf("%d",&c);

    printf("\nValues Before swapping :: \n");
    printf("\ta = %d\tb = %d\tc = %d\n",a,b,c);

    cyclicSwap(&a, &b, &c);

    printf("\nValues After swapping :: \n");
    printf("\ta = %d\tb = %d\tc = %d\n",a,b,c);

    return 0;
}
void cyclicSwap(int *a,int *b,int *c)
{

    int temp;

    // swapping in cyclic order
    temp = *b;
    *b = *a;
    *a = *c;
    *c = temp;
}

Output : :


/*  C Program to Swap Two Numbers Using Call by Reference  */

Enter a :: 7

Enter b :: 8

Enter c :: 9

Values Before swapping ::
        a = 7   b = 8   c = 9

Values After swapping ::
        a = 9   b = 7   c = 8

Process returned 0

Above is the source code for C Program to Swap Two Numbers Using Call by Reference which is successfully compiled and run on Windows System.The Output of the program is shown above .

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.


Thanks for reading the post….

Leave a Reply