pTutorial

New way to learn C programming

C Program to swap two numbers

C program to swapping of two number with and without third variable. For example you have two variable x=5; and y=15; then before wapping the value of x=5; and the value of y=15; after swapping the value of x=15 and the value of y=5;

C program to Swap two number using third variable


//C Program for swapping
#include <stdio.h>

#include <conio.h>

void main()

{
    int x,y,temp_var;
    printf("Enter value for x & y: ");
    scanf("%d%d",&x,&y);
    printf(" Before swapping \n the value of x: %d",x);
    printf("\nThe value of y: %d\n",y);
    temp_var=x;
    x=y;
    y=temp_var;
    printf(" After swapping \n the value of x: %d",x);
    printf("\n The value of y: %d",y);
    getch();
}

Download swapping program

In this example take third variable to swap numbers, first value of x assign to the third variable, assign x on the y and at the last asign third variable on y. .

Output of swapping program

Swapping of two number

C program to swap two number without using third variable

//C Program for swapping

#include <stdio.h>

#include <conio.h>

void main()

{
int x,y;
	printf("Enter value for x & y: ");
	scanf("%d%d",&x,&y);
	printf(" Before swapping \n the value of x: %d",x);
	printf("\nThe value of y: %d\n",y);
	x=x+y;
	y=x-y;
	x=x-y;
	printf(" After swapping \n the value of x: %d",x);
	printf("\n The value of y: %d",y);
	getch();
}

Download C swapping program

You can also perform the swapping without using any third or teporary variable as shown above.

See Also

Java example   |   Php5 self and parent   |   Php5 classes

QUOTES OF THE DAY

Well-begun is half done.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER