Swapping of two numbers without using third variable (Take input from user) code example

Example 1: Write a program to show swap of two numbers without using third variable.

#include<stdio.h>  
 int main()    
{    
int a=10, b=20;      
printf("Before swap a=%d b=%d",a,b);      
a=a+b;//a=30 (10+20)    
b=a-b;//b=10 (30-20)    
a=a-b;//a=20 (30-10)    
printf("\nAfter swap a=%d b=%d",a,b);    
return 0;  
}

Example 2: swapping two numbers using call by reference

//swapping two numbers using call by reference....


#include<stdio.h>
void swap(int *, int *);       //function declaration
int main()
{
	int a,b;
    
    printf("Enter first number:  ");
    scanf("%d",&a);
    printf("Enter second number:  ");
    scanf("%d",&b);
    
    printf("/n/nNumber before swapping are %d and %d",a,b);
    swap(&a,&b);    //passing the address of both the variables( CALL BY REFERENCE)
	printf("/n/nNumber before swapping are %d and %d",a,b);
}
void swap(int *p,int *q)     //function defination
{
   int temp;
   temp=*p;
   *p=*q;
   *q=temp;
} //Code By Dungriyal

Tags:

Misc Example