The address of memory location num1 and num2 are passed to function and the pointers *a and *b accept those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the value of pointer is changed, the value in memory location also changed correspondingly. Write a program to swap the values in num1 and num2 using *a and *b. Use + and - operator for swapping
Runtime Input :
5
6
8
Output :
5
#include <stdio.h>
void swapping_numbers(int *a,int *b);
int main(){
//Initializing num1 to 100 and num2 to 90
int num1=100,num2=90;
printf("Before swapping\n");
printf("The first number is: %d\n",num1);
printf("The second number is: %d\n",num2);
swapping_numbers(&num1,&num2);
printf("After swapping\n");
printf("The first number is: = %d\n",num1);
printf("The second number is: = %d\n",num2);
return 0;
}
void swapping_numbers(int *a,int *b){
*a = *a + *b;
*b=*a - *b;
*a=*a - *b;
}
Comments
Leave a comment