如何在C语言编程中不使用第三个或临时变量来交换两个数字?
借助加法和减法运算,我们可以将两个数字从一个内存位置交换到另一个内存位置。
算法
算法解释如下:
开始
Step 1: Declare 2 variables x and y. Step 2: Read two numbers from keyboard. Step 3: Swap numbers. //Apply addition and subtraction operations to swap the numbers. i. x=x+y ii. y=x-y iii. x=x-y Step 4: Print x and y values.
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
程序
以下是C程序,它解释了如何在不使用第三个变量或临时变量的情况下交换两个数字:
#include<stdio.h> int main(){ int x,y; printf("enter x and y values:"); scanf("%d%d",&x,&y);// lets take x as 20 and y as 30 x=x+y;// x=20+30=50 y=x-y;//y=50-30=20 x=x-y;//x=50-20=30 printf("After swap x=%d and y=%d",x,y); return 0; }
输出
您将得到以下输出:
enter x and y values:20 30 After swap x=30 and y=20
注意 - 我们可以使用乘法和除法以及位异或运算符来交换两个数字,而无需借助第三个变量。
考虑另一个例子,它解释了如何使用乘法和除法运算符交换两个数字。
程序
以下是C程序,用于演示交换两个数字的相应功能:
#include<stdio.h> int main(){ int x,y; printf("enter x and y values:"); scanf("%d%d",&x,&y); x=x*y; y=x/y; x=x/y; printf("After swap x=%d and y=%d",x,y); return 0; }
输出
执行上述程序后,您将获得以下输出:
enter x and y values:120 250 After swap x=250 and y=120
广告