In this post we will learn how to write a C program that swap two numbers with temp variable.Given two numbers and swap these numbers in this program with using 3rd (temporary) variable.
a = b;
b = c;
Input firstnumber=35
Input secondnumber=53
After swapping
Output firstnumber=53
Output secondnumber=35
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("\n Enter the first number: ");
scanf("%d",&a);
printf("\n Enter the second number: ");
scanf("%d",&b);
printf("\n The values of a is %d
and b is %d before swaping\n",a,b);
c=a;
a=b;
b=c;
printf("\n The values of a is %d
and b is %d after swaping\n",a,b);
getch();
}
In first output,the value of input first and second number is 35 and 53
After swapping
The value of first number 53 and second number 35
In second output,the value of input first and second number is 25 and 32
After swapping
The value of first number 32 and second number 25
Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.
Solution
- In this program we will use three variables as a, b and c for two numbers swapping.
- We will use integer data type in this program.
- We will use some logics as:-
a = b;
b = c;
- After it we will print the numbers using printf statements.
Example:-
Input secondnumber=53
After swapping
Output firstnumber=53
Output secondnumber=35
C program code
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("\n Enter the first number: ");
scanf("%d",&a);
printf("\n Enter the second number: ");
scanf("%d",&b);
printf("\n The values of a is %d
and b is %d before swaping\n",a,b);
c=a;
a=b;
b=c;
printf("\n The values of a is %d
and b is %d after swaping\n",a,b);
getch();
}
OUTPUT 1:
OUTPUT 2:
In first output,the value of input first and second number is 35 and 53
After swapping
The value of first number 53 and second number 35
In second output,the value of input first and second number is 25 and 32
After swapping
The value of first number 32 and second number 25
Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.
Created by-- HARSH CHAUHAN
No comments:
Post a Comment