Answers for "swapping two values in c"

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 for swapping of two numbers using temporary variable

#include <stdio.h>
int main()
{
    int a, b, temp;
    printf("enter the values of a and b: n");
    scanf("%d%d", &a, &b );
    printf("current values are:n a=%dn b=%dn", a, b);
    temp=a;
    a=b;
    b=temp;
    printf("After swapping:n a=%dn b=%dn", a, b);
}
Posted by: Guest on April-19-2021

Code answers related to "swapping two values in c"

Code answers related to "C"

Browse Popular Code Answers by Language