Write a c program to swap two numbers using third variable. In this program, we are going write a code to take two input numbers from a user and swap both numbers using third or temp variable.
How to Swap Two Numbers using Third Variable
i) Take an input number from a user. Let's say user has entered two numbers 4 and 5.
first = 4;
second = 5;
ii) Declare third variable temp which holds the value.
Let's assign the value of first in temp.
temp = first;
Assign the value of second in first.
first = second;
Assign the value of temp in second.
second = temp;
Before swapping : a =4 and b = 5
After swapping : a = 5 and b = 4
Swap two numbers without using third variable
C, C++ Interview Questions
We have discussed the logic to swap two numbers using third variable. Let's write a c code to implement this logic.
Output:
Enter two numbers : 4 5
Before swapping a = 4 and b = 5
After swapping a = 5 and b = 4
Programming questions for beginners
Swap two numbers using pointers
Sorting algorithm and their time complexity
How to Swap Two Numbers using Third Variable
i) Take an input number from a user. Let's say user has entered two numbers 4 and 5.
first = 4;
second = 5;
ii) Declare third variable temp which holds the value.
Let's assign the value of first in temp.
temp = first;
Assign the value of second in first.
first = second;
Assign the value of temp in second.
second = temp;
Before swapping : a =4 and b = 5
After swapping : a = 5 and b = 4
Swap two numbers without using third variable
C, C++ Interview Questions
C Program to Swap Two Numbers using Third Variable
We have discussed the logic to swap two numbers using third variable. Let's write a c code to implement this logic.
#include<stdio.h>
int main()
{
int first, second, temp;
printf("Enter two numbers\n");
scanf("%d %d", &first, &second);
printf("\nBefore swapping a = %d and b = %d", first, second);
/* Logic to swap two numbers
using third variable */
temp = first;
first = second;
second = temp;
printf("\nAfter swapping a = %d and b = %d",first , second);
return 0;
}
Output:
Enter two numbers : 4 5
Before swapping a = 4 and b = 5
After swapping a = 5 and b = 4
Programming questions for beginners
Swap two numbers using pointers
Sorting algorithm and their time complexity

No comments:
Post a Comment