Write a C program to input two numbers from user and swap these numbers using pointers. Let's have a look at the below step by step descriptive logic how to swap two number using pointers.
Required knowledge-
Swapping two numbers using pointers:
1) When we pass address (also known as reference) of variables as an actual arguments while calling a function then this is known as function call by reference.
2) In call by reference, the address of the actual parameters is copied into the formal parameters.
Here is the step by step logic for swapping two numbers using pointers:
- Create a user defined function for swapping two numbers using pointer For Example: void swapTwoNumbers(int *n1, int *n2)
- Inside the main function, Take input of two numbers 10 and 20 from user and store it in some variables like: num1 and num2.
- To swap these numbers, you need to call user defined function by passing reference (Address) of variables like this: swapTwoNumbers(&num1, &num2);
- At last print the values of 'num1 and num2' that's it.
#include <stdio.h>
int swapTwoNumbers(int*, int*); //function declaration
int main(){
int num1, num2;
/*Taking inputs form user*/
printf("Enter num1: ");
scanf("%d", num1);
printf("Enter num2: ");
scanf("%d", num2);
/*Displaying numbers before swapping*/
printf("Before swapping: num1 = %d, num2 = %d", num1, num2);
/*Function call by passing reference*/
swapTwoNumbers(&num1, &num2);
/*Displaying numbers after swapping*/
printf("After swapping: num1 = %d, num2 = %d", num1, num2);
return 0;
}
/*Function definition*/
void swapTwoNumbers(int *n1, int *n2){
int temp;
/*Swapping two numbers*/
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
When the above code will compile and run following output will be produced.
Input:
Enter num1: 10
Enter num2: 20
Output:
Before swapping: num1 = 10, num2 = 20
After swapping: num1 = 20, num2 = 10
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.