Swapping two numbers is simple and a fundamental thing. You need not to know any rocket science for swapping two numbers. Simple swapping can be achieved in three steps -
- Copy the value of first number say num1 to some temporary variable say temp.
- Copy the value of second number say num2 to the first number. Which is num1 = num2.
- Copy back the value of first number stored in temp to second number. Which is num2 = temp.
#include <stdio.h>
#include<conio.h>
void swap(int * num1, int * num2);/*Function protoype*/
int main()
{
int num1, num2;
/* Input numbers */
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
/* Print original values of num1 and num2 */
printf("Before swapping in main n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);
/* Pass the addresses of num1 and num2 */
swap(&num1, &num2);/*Function Call*/
/* Print the swapped values of num1 and num2 */
printf("After swapping in main n");
printf("Value of num1 = %d \n", num1);
printf("Value of num2 = %d \n\n", num2);
return 0;
getch();
}
void swap(int * num1, int * num2)/*Function Defination*/
{
int temp;
// Copy the value of num1 to some temp variable
temp = *num1;
// Copy the value of num2 to num1
*num1= *num2;
// Copy the value of num1 stored in temp to num2
*num2= temp;
printf("After swapping in swap function n");
printf("Value of num1 = %d \n", *num1);
printf("Value of num2 = %d \n\n", *num2);
}
Run:
Previous Next
No comments:
Post a Comment