- 1C Hello World Program
- 2C Program to Print Your Own Name
- 3C Program to Print an Integer Entered by the User
- 4C Program to Add Two Numbers
- 5C Program to Multiply Two Floating‑Point Numbers
- 6C Program to Print the ASCII Value of a Character
- 7C Program to Swap Two Numbers
- 8C Program to Calculate Fahrenheit to Celsius
- 9C Program to Find the Size of int, float, double and char
- 10C Program - Add Two Complex Numbers
- 11C Program - Find Simple Interest
- 12C Program - Find Compound Interest
- 13C Program - Area And Perimeter Of Rectangle
- 14C Program - Check Whether a Number is Positive, Negative, or Zero
- 15C Program - Check Whether Number is Even or Odd
- 16C Program - Check Whether a Character is Vowel or Consonant
- 17C Program - Find Largest Number Among Three Numbers
- 18C Program - Calculate Sum of Natural Numbers
- 19C Program - Print Alphabets From A to Z Using Loop
- 20C Program - Make a Simple Calculator
- 21C Program - Generate Multiplication Table
- 22C Program - Reverse a Number
- 23C Program - Check whether the input number is a Neon Number
- 24C Program - Find All Factors of a Natural Number
C Program to Swap Two Numbers - Using Temp, Arithmetic & XOR
Swap Using a Temporary Variable
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
printf("a = %d, b = %d\n", a, b);
return 0;
}
a = 10, b = 5
Here the value of a is preserved in temp so that it can be assigned back to b after a receives b’s original value.
Swap Using Arithmetic Operations
#include <stdio.h>
int main() {
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
printf("a = %d, b = %d\n", a, b);
return 0;
}
a = 10, b = 5
This method avoids a temporary variable by using arithmetic operations: after a is set to a + b, subtracting b from a yields the original a which can be stored in b, and subtracting the new b from a yields the original b.
Swap Using XOR
#include <stdio.h>
int main() {
int a = 5, b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a = %d, b = %d\n", a, b);
return 0;
}
a = 10, b = 5
The XOR method leverages the property that applying XOR twice with the same operand retrieves the original value. After three XOR operations, the values of a and b are exchanged.
⬅ Previous TopicC Program to Print the ASCII Value of a Character
Next Topic ⮕C Program to Calculate Fahrenheit to Celsius
Next Topic ⮕C Program to Calculate Fahrenheit to Celsius
Comments
Loading comments...