C Books Guide and List
C++ Books Guide and List
Best Java Books

C program to swap two numbers using a temporary third variable.

+1 vote
4,625 views asked Jul 13, 2011 by Smita Advisor (7,140 points)

3 Answers

+1 vote
Example:
if x=5 and y=8, consider a temporary variable temp.
           step1: temp=x=5;
           step2: x=y=8;      
           step3: y=temp=5;
Thus the values of the variables x and y are interchanged.

Program:
#include <stdio.h>
int main()
{
 int a, b, temp;
 printf("Enter the value of a and b: \n");
 scanf("%d %d", &a, &b);
 printf("Before swapping a=%d, b=%d \n", a, b);

 /*Swapping logic */
 temp = a;
 a = b;
 b = temp;

 printf("After swapping a=%d, b=%d", a, b);
 return 0;
}


Output:
Enter the values of a and b: 2 3
Before swapping a=2, b=3
After swapping a=3, b=2
answered Jul 19, 2011 by sagar Expert (12,340 points)
0 votes
#include<stdio.h>
#include<conio.h>
void main()
{
 int a,b,c;            // a,b and c  are integers
 clrscr();        // this is a function that used to clear the previos output
 printf("enter any two numbres\n");
 scanf("%d%d",&a,&b);
 printf("value of a before Swap = %d\n",a);
 printf("value of b before Swap = %d\n",b);
/*************Logic to swap***********************/
  c=a;      // value of a given to c
  a=b;      // value of b given to a
  b=c;     // value of c given to b
  printf("value of a after Swap = %d\n",a);
  printf("value of b after Swap = %d\n",b);

 getch();
}
answered Dec 11, 2011 by Anand Hooda Sr Member (2,730 points)
0 votes
Swapping interchanges the values of two given variables.

Logic:

step1: temp=x;

step2: x=y;

step3: y=temp;

Example:

if x=5 and y=8, consider a temporary variable temp.

step1: temp=x=5;

step2: x=y=8;

step3: y=temp=5;

Thus the values of the variables x and y are interchanged.

Program:

#include <stdio.h>

int main() {

int a, b, temp;

printf("Enter the value of a and b: \n");

scanf("%d %d", &a, &b);

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

/*Swapping logic */

temp = a;

a = b;

b = temp;

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

return 0;

}

Output:

Enter the values of a and b: 2 3

Before swapping a=2, b=3

After swapping a=3, b=2
answered Jan 8 by keem Expert (13,240 points)

Related questions

0 votes
1 answer 31,383 views
0 votes
4 answers 2,914 views
2,914 views asked May 29, 2011 by Abigail Jr Member (240 points)
0 votes
1 answer 746 views
0 votes
2 answers 10 views
...