37 : C Program to Swap two numbers using a temperory variable

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

This program accepts two integers A and B and Swaps their values. This is done using a temp variable.

This can be done in 3 steps :

1. Move value of variable A to temp Variable

2. Assign Value of var A to variable B

3. Assign temp var value to variable B

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.

3. temp: Datatype int : Temp variable.

Swampping Logic

   temp = number_a;  //move number_a to temp variable
   number_a = number_b; // move number_b to number_a
   number_b = temp; //move temp that holds value of number_a to number_b

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
 * 37_swap_two_numbers_using_temp_variable.c
 *  Created on: Oct 20, 2014
 *  Author: Code2care.org


void main() {

   int number_a;
   int number_b;
   int temp;

//    clrscr();

    printf("C Program to Swap values to two variables 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);
   //Swampping logic
   temp = number_a;
   number_a = number_b;
   number_b = temp;
    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.