Answers for "swap two var c"

C
1

swap two numbers in c

#include <stdio.h>
int main() {
    double a, b;
    printf("Enter a: ");
    scanf("%lf", &a);
    printf("Enter b: ");
    scanf("%lf", &b);

    // Swapping

    // a = (initial_a - initial_b)
    a = a - b;   
  
    // b = (initial_a - initial_b) + initial_b = initial_a
    b = a + b;

    // a = initial_a - (initial_a - initial_b) = initial_b
    a = b - a;

    printf("After swapping, a = %.2lf\n", a);
    printf("After swapping, b = %.2lf", b);
    return 0;
}
Posted by: Guest on March-26-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=%d\n b=%d\n", a, b);
    temp=a;
    a=b;
    b=temp;
    printf("After swapping:\n a=%d\n b=%d\n", a, b);
}
Posted by: Guest on April-19-2021
2

how to swap values in variables in c

#include <stdio.h>
#include <stdlib.h>

int main()
{
  	//initialize variables
	int num1 = 10;
	int num2 = 9;
  	int tmp;
  	
  	//create the variables needed to store the address of the variables
  	//that we want to swap values
  	int *p_num1 = &num1;
  	int *p_num2 = &num2;
  
  	//print what the values are before the swap
  	printf("num1: %i\n", num1);
    printf("num2: %i\n", num2);
  
  	//store one of the variables in tmp so we can access it later
  	//gives the value we stored in another variable the new value
  	//give the other variable the value of tmp
  	tmp = num1;
  	*p_num1 = num2;
  	*p_num2 = tmp;

  	//print the values after swap has occured
   	printf("num1: %i\n", num1);
    printf("num2: %i\n", num2);
  	
	return 0;
}
Posted by: Guest on October-16-2020
0

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 = %d\n", 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 = %d\n", a, b);
  	//a = 5 / b = 10
  	return 0;
}
Posted by: Guest on August-09-2021

Code answers related to "C"

Browse Popular Code Answers by Language