Answers for "how to swap two numbers in c without using third variable"

C
1

swap two var c

#include <stdio.h>

int main()
{
	int a = 10;
  	int b = 5;

  	//swap start
  	a = a + b; //a = 10 + 5 = 15
    b = a - b; //b = 15 - 5 = 5
    a = a - b; //a = 15 - 5 = 10

  	printf("a = %d / b = %dn", a, b);
  	//a = 5 / b = 10
  	return 0;
}


/*You can create a function*/

void swap(int *a, int *b)
{
  	*a = *a + *b; //a = 10 + 5 = 15
    *b = *a - *b; //b = 15 - 5 = 5
    *a = *a - *b; //a = 15 - 5 = 10
}

int main()
{
	int a = 10;
  	int b = 5;

  	//call with adress of the var
	swap(&a, &b);  
  	printf("a = %d / b = %dn", a, b);
  	//a = 5 / b = 10
  	return 0;
}
Posted by: Guest on August-09-2021
0

c program to swap two numbers using call by reference

#include <stdio.h>
 
void swap(int*, int*);
 
int main()
{
   int x, y;
 
   printf("Enter the value of x and yn");
   scanf("%d%d",&x,&y);
 
   printf("Before Swappingnx = %dny = %dn", x, y);
 
   swap(&x, &y); 
 
   printf("After Swappingnx = %dny = %dn", x, y);
 
   return 0;
}
 
void swap(int *a, int *b)
{
   int temp;
 
   temp = *b;
   *b = *a;
   *a = temp;   
}
Posted by: Guest on February-18-2021
0

C Programming to swap two variables

#include <stdio.h>

int main()
{
    int x = 20, y = 30, temp;
    temp = x;
    x = y;
    y = temp;
    printf("X = %d and Y = %d", x, y);
    
    return 0;
}
Posted by: Guest on June-28-2021

Code answers related to "how to swap two numbers in c without using third variable"

Code answers related to "C"

Browse Popular Code Answers by Language