如何在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
廣告