卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章21404本站已运行3414

如何在C编程中不使用第三个或临时变量交换两个数字?

如何在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.

程序

以下是一个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
卓越飞翔博客
上一篇: Python程序:将字符串的第K个索引单词连接起来
下一篇: 返回列表

相关推荐

留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏