C Program To Swap Two Numbers Using Call By Reference
It's straightforward and fundamental to swap two numbers. To swap two numbers, you don't need to be an expert in rocket science. Three stages can be used to complete a simple swap:
- Copy the first number's value, let's say a, to a temporary variable, let's say temp.
- Copy the value of number two, let's say b, to number one. Hence, a = b.
- Restore the first number's value from temporary storage to the second number. This is temp = b.
Implementing swaping of two numbers by using call by reference :-
#include <stdio.h>
// C program to swap two number using call by reference
#include <stdio.h>
//Swap function declaration
void swap(int * a, int * b);
int main()
{
int a, b;
// Input numbers
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
// Print original values of a and b
printf("Before swapping in main \n");
printf("Value of a = %d \n", a);
printf("Value of b = %d \n", b);
// Pass the addresses of a and b
swap(&a, &b);
// Print the swapped values of a and b printf("After swapping in main \n"); printf("Value of a = %d \n", a); printf("Value of a = %d \n", b); return 0; } // Function to swap two numbers void swap(int * a, int * b) { int temp; // Copy the value of a to some temp variable temp = *a; // Copy the value of b to a *a= *b; // Copy the value of num1 stored in temp to b *b= temp; printf("After swapping in swap function\n"); printf("Value of a = %d \n", *a); printf("Value of b = %d \n\n", *b); }
OUTPUT:
![C Program To Swap Two Numbers Using Call By Reference](https://static.tutorialandexample.com/c/c-program-to-swap-two-numbers-using-call-by-reference1.png)