Ex: write a C program for swap two numbers. How to write a C program which swaps values of the two numbers. C program to swap two numbers.
Input from user:
Enter the no1: 10
Enter the no1: 20
Expected Output:
Values after swaping:
no1=20
no2=10
Input from user:
Enter the no1: 10
Enter the no1: 20
Expected Output:
Values after swaping:
no1=20
no2=10
Step by step logic to swap values of two variable's:
1. First we will declare the variables for swap two variable's value.
2. We declare no1, no2 and temp. where no1 for accepting 1st number from user and no2 for accepting 2nd number from user and temp is third varible which will help to swap no1 and no2 values.
3. In the logic :
- we will store no1(which is 10) value in the temp variable (temp=10).
- After that we will store no2(which is 20) value in no1 variable (no1=20).
- In the last we will give temp(which is 10) variable value to the no2 variable (no2=10).
4. After that we will display swaped values of no1 and no2 (no1=20 and no2=10).
Program for accept two numbers and swap there values:
#include<stdio.h>
void main()
{
int no1,no2,temp;
printf("Enter the no1:\n");
scanf("%d",&no1);
printf("Enter the no2:\n");
scanf("%d",&no2);
temp=no1;
no1=no2;
no2=temp;
printf("Values after swaping:\nno1=%d\nno2=%d",no1,no2);
}
Above program shows the following output:
No comments:
Post a Comment
If you have any doubts, please discuss here...👇