Saturday 10 November 2012

C Program to Swap Two Variables With and Without Temporoary Variable

By
Write a C Program to swap two variables using (i) third variable and (ii) without using
a third variable.


(i) Swap two Variables using Third Variable

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,t;
clrscr();
printf("|****************************|");
printf("\nwww.flintgroups.com\n");
printf("|****************************|\n");
printf("Enter the Value A:");
scanf("%d",&a);
printf("enter the value B:");
scanf("%d",&b);
printf("\nThe Values Before Swapping\n");
printf("The Value of A:%d",a);
printf("\nThe Value of B:%d",b);
t=a;
a=b;
b=t;
printf("\nThe Values After Swapping\n");
printf("The Value of A:%d",a);
printf("\nThe Value of B:%d",b);
getch();
}


(ii) Swap two Variables without using Third Variable

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("|****************************|");
printf("\nwww.flintgroups.com\n");
printf("|****************************|\n");
printf("Enter the Value A:");
scanf("%d",&a);
printf("enter the value B:");
scanf("%d",&b);
printf("\nThe Values Before Swapping\n");
printf("The Value of A:%d",a);
printf("\nThe Value of B:%d",b);
a=a+b;

b=a-b;
a=a-b;
printf("\nThe Values After Swapping\n");
printf("The Value of A:%d",a);
printf("\nThe Value of B:%d",b);
getch();
}


Sample Output for this prgram is shown below.

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Labels