通過加法和減法操作,我們可以將兩個數字從一個內存位置交換到另一個內存位置。
算法
以下是算法的解釋 ?
開始
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
登錄后復制
以上就是如何在C編程中不使用第三個或臨時變量交換兩個數字?的詳細內容,更多請關注www.xfxf.net其它相關文章!