C

Simplified tutorials to learn the popular basic language C

VB.Net

Learn the basic desktop development application language

CodeIgniter

One of the popular PHP three tier (MVC) framework

C Program to Swap the Values of Two Numbers


Abstraction:
        This C program accepts two integer numbers into two variables and interchange their values


Swapping means the interchanging of two values. There are several ways to swap two values if we look as a little advance like using pointer, using xor etc. 

Here we are taking normal and simple method of swapping.
Method: 

If we have two cups of water, how can we swap the water? That is, getting the water of first cup to second and water in second cup will be on first class. We need another free cup and spill free cup with the water of first cup and spill the second cup water into first cup and refill the second cup from extra cup.

Look at the image:

Like this, in C, we use a temporary variable to interchange the value. Let us see the program:

C program to swap the values of two given integer numbers :


#include <stdio.h>
#include <stdlib.h>
void main()
{
   int num1,num2,temp;
   printf("Enter the first number : ");
   scanf("%d",&num1);
   printf("Enter the second number : ");
   scanf("%d",&num2);
   printf("Number before swap is:\n first: %d \n Second: %d ",num1,num2);
   temp = num1;
   num1 = num2;
   num2 = temp;
   printf("\nNumber after swap is:\n first: %d \n Second: %d ",num1,num2);

Code Explanation: 
int num1,num2,temp; 
Declaring two numbers named num1 and num2. temp is a variable which use temporary value.
printf(" Enter the first number : "); 

scanf("%d",&num1); 
printf(" Enter the second number : "); 
scanf("%d",&num2); 
Accepting two numbers one by one and saved to num1 and num2.
printf("Number before swap is:\n first: %d \n Second: %d",num1,num2); 
This shows both numbers before swapping

Suppose num1 is 10 and num2 is 20.
temp = num1; 
Now the value of temp = 10, num1 = 10, num2 = 20.
num1 = num2; 
Now the value of temp = 10, num1 = 20, num2 = 20.
num2 = temp; 
Now the value of temp = 10, num1 = 20, num2 = 10.

Now let us look at the values of num1 and num2; values are interchanged. temp has a value of 10. No need to bother, we no need its value.
printf("\nNumber after swap is:\n first: %d \n Second: %d ",num1,num2); 
This shown numbers after interchanging their values.

Sample Output: 

interchange between two values

Above programs leans use of temporary variable and how to use them. If you have any doubts, you may print the values of num1, num2 and temp often in between interchanging steps (using printf).

Feel free to ask your doubts ...

No comments:

Post a Comment