Certainly! Here’s a C program that swaps two numbers without using a third variable:Certainly! Here’s a C program that swaps two numbers without using a third variable:
#include <stdio.h> void swapNumbers(int *a, int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } int main() { int num1, num2; printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2); printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2); swapNumbers(&num1, &num2); printf("After swapping: num1 = %d, num2 = %d\n", num1, num2); return 0; }
In this program, the swapNumbers
function takes two integer pointers as parameters (a
and b
). It performs the swapping using arithmetic operations without using a third variable. The main
function prompts the user to enter two numbers, calls the swapNumbers
function, and then displays the swapped values.
Program 1: Using + and –
Here’s a modified version of the previous program that uses only the addition (+
) and subtraction (-
) operators to swap two numbers:
#include <stdio.h> void swapNumbers(int *a, int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } int main() { int num1, num2; printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2); printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2); swapNumbers(&num1, &num2); printf("After swapping: num1 = %d, num2 = %d\n", num1, num2); return 0; }
This program is similar to the previous one, but instead of using the multiplication (*
) and division (/
) operators, it uses addition and subtraction to swap the values. The logic remains the same: the sum of both numbers is assigned to the first number, then the difference between the new value of the first number and the second number is assigned to the second number, and finally, the difference between the new value of the first number and the new value of the second number is assigned to the first number.
Program 2: Using * and /
Certainly! Here’s a C program that swaps two numbers using only the multiplication (*
) and division (/
) operators:
#include <stdio.h> void swapNumbers(int *a, int *b) { *a = *a * *b; *b = *a / *b; *a = *a / *b; } int main() { int num1, num2; printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2); printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2); swapNumbers(&num1, &num2); printf("After swapping: num1 = %d, num2 = %d\n", num1, num2); return 0; }
In this program, the swapNumbers
function takes two integer pointers as parameters (a
and b
). It performs the swapping using the multiplication and division operators without using a third variable. The main
function prompts the user to enter two numbers, calls the swapNumbers
function, and then displays the swapped values.