C Program to Swap Two Numbers Using Pointer and User Defined Function
Question: write a program in C to swap two numbers using pointer and user defined function.
C Source Code: Swap Numbers - Call by Reference
#include<stdio.h>
/* Function prototype */
void swap(int *p, int *q);
/* Main function */
int main()
{
int first_number, second_number;
/* Reading two numbers */
printf("Enter first number: ");
scanf("%d", &first_number);
printf("Enter second number: ");
scanf("%d", &second_number);
printf("Before swapping: first_number = %d and second_number = %d\n", first_number, second_number);
/* Function call, call-by-reference */
swap(&first_number, &second_number);
printf("After swapping: first_number = %d and second_number = %d\n", first_number, second_number);
return 0;
}
/* Function definition */
void swap(int *p, int *q)
{
int temp;
/* Swapping */
temp = *p;
*p = *q;
*q = temp;
}
Output
The output of the above program is:
Enter first number: 10 Enter second number: 20 Before swapping: first_number = 10 and second_number = 20 After swapping: first_number = 20 and second_number = 10