38 : C Program to Swap two numbers without using a temperory variable

Check out the complete list of c-programs : C Program List    



Last program we saw how to swap two numbers, now lets see how to swap them without using a temp variable.

This can be done in 3 steps :

1. Add both number_a and number_b and store it in number_a variable.

2. Subtract number_b from number_a and store it in number_b (number_b has value of number_a)

3. Now, subtract number_b from number_a and store it in number_a (number_a now has value of

Variables :

1. number_a : Datatype int : Holds value of number A inputted by the user.

2. number_b : Datatype int : Holds value of number B inputted by the user.



Functions :

printf() : is used to display something on the console/screen. Format specifier %d in printf function is used to display a int variable on screen and %f for float. \n is used to add a newline

scanf() : is used to fetch data inputted by the user on the console/screen using keyboard. %d in scanf is indicates that inputted text is of type int.








/*
 * 1000+ C programs + tutorials
 *
 * 
 * 34_swap_two_numbers_without_using_temp_variable.c
 *
 *
 *  Created on: Oct 20, 2014
 *  Author: Code2care.org
 */

#include 
//#include 



void main() {

   int number_a;
   int number_b;
  

//    clrscr();

    printf("C Program to Swap values to two variables without without using temp variable :  ");

    printf("\n\n Enter value for variable A  : ");
    scanf("%i", &number_a);
    
   
    printf("\n\n Enter value for variable B  : ");
    scanf("%i", &number_b);
    
     printf("\n\n Before Swapping => Value A : %i    B : %i ",  number_a,number_b);
     
     
   //Swapping logic
   
   number_a = number_a + number_b;
   number_b = number_a - number_b;
   number_a = number_a - number_b;
   
    printf("\n\n After Swapping => Value A : %i    B : %i ",  number_a,number_b);
  


//	getch();



}









The best way to learn C programming is to practice more and more of programs . Code2care C Programming tutorials provide 1000+ programs in C that you can study and become an expert in the language. Programs are divided into categories depending upon type and complexity.

BSc. IT, BSc. Computer Science, BSc. IT, MSc. IT, MSc. Computer Science, MCA, BTech IT & BTech Engineers may find these programs very useful.