Watching Sky

Swapping

  • C
  • BASIC
C

/* SWAP TWO VARIABLES USING THIRD VARIABLE */

#include<stdio.h>

#include<conio.h>

void main()

{

    clrscr();

    int a,b,temp;

    printf("Enter the value of a:");

    scanf("%d",&a);

    printf("\nEnter the value of b:");

    scanf("%d",&b);

    printf("Before swapping, a="%d" and b="%d",a,b);

    temp=a; a=b; b=temp;

    printf("\nAfter swapping, a=%d and b=%d",a,b);

    getch();

}


/* SWAPPING TWO VARIABLES WITHOUT USING THIRD VARIABLE */

#include<stdio.h>

#include<conio.h>

void main()

{

    clrscr();

    int a,b;

    printf("Enter the value of a:");

    scanf("%d",&a);

    printf("\nEnter the value of b:");

    scanf("%d",&b);

    printf("Before swapping, a=%d" and b=%d",a,b);

    a=a+b; b=a-b; a=a-b;

    printf("\nAfter swapping, a=%d and b=%d",a,b);

    getch();

}


/* PASSING THE SUM OF TWO VARIABLES IN A 3-VARIABLE SET TO THE THIRD VARIABLE OF THE SAME SET */

#include<stdio.h>

#include<conio.h>

void main()

{

    clrscr();

    int a,b,c;

    printf("Enter the value of a:");

    scanf("%d",&a);

    printf("\nEnter the value of b:");

    scanf("%d",&b);

    printf("\nEnter the value of c:");

    scanf("%d",&c);

    printf("Before passing, a=%d, b=%d and c=%d",a,b,c);

    a=a+b+c; b=a-b; c=a-c; a=2*a-(b+c);

    printf("\nAfter passing, a=%d, b=%d and c=%d",a,b,c);

    getch();

}


BASIC