Swapping
C Program to Swap Two Numbers
In this article, we will discuss how to write a C program to swap two number using a temporary variable and also without using a temporary or third variable.
For this C Program to Swap Two Numbers purpose, we are going to use Pointers, Functions, Arithmetic Operators, Bitwise Operators, Call By Reference in C concepts.
This C program allows the user to enter two integer values. Using the third variable, this C program Swap two numbers.
Source Code:
Source Code:
/* C Program to Swap Two Numbers */ #include int main() { int a, b, Temp; printf("\nPlease Enter the value of a and b\n"); scanf("%d %d", &a, &b); printf("\nBefore Swap: a = %d and b = %d\n", a, b); Temp = a; a = b; b = Temp; printf("\nAfter Swapping: a = %d and b = %d\n", a, b); return 0; }
Output Console:
Analysis:
Within this C Program to Swap Two Numbers, we assigned a = 6 and b = 13
Temp = a – it means assigning the a value to the Temp variable
Temp = 6
Temp = 6
a = b – it means assigning the b value to the variable a
a = 13
a = 13
b = Temp – it means assigning the Temp value to the variable b
b = 6
Last Printf statement will print the a, b values as output.
b = 6
Last Printf statement will print the a, b values as output.
No comments:
Post a Comment