在 C++ 中交換上對角線和下對角線
本教程旨在用 c++ 程式碼將一個三對角陣的上行轉換為下行。此外,如果輸入為一個三對角陣,則想要的結果必須如下所示;

為此,演算法中簡要說明了操作過程如下;
演算法
Step-1: Input a diagonal array Step-2: Pass it to Swap() method Step-3: Traverse the outer loop till 3 Step-4: increment j= i+ 1 in the inner loop till 3 Step-5: put the array value in a temp variable Step-6: interchange the value arr[i][j]= arr[j][i] Step-7: put the temp data to arr[j][i] Step-8: Print using for loop
因此,c++ 程式碼按照上述演算法編寫如下;
示例
#include <iostream>
#define n 3
using namespace std;
// Function to swap the diagonal
void swap(int arr[n][n]){
// Loop for swap the elements of matrix.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
// Loop for print the matrix elements.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}
// Driver function to run the program
int main(){
int arr[n][n] = {
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9},
};
cout<<"Input::"<<endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << arr[i][j]<< " ";
cout << endl;
}
// Function call
cout<<"Output(Swaped)::"<<endl;
swap(arr);
return 0;
}輸出
如下所示,輸出中交換了三維陣的上行和下段,如下所示;
Input:: 1 2 3 4 5 6 7 8 9 Output(Swaped):: 1 4 7 2 5 8 3 6 9
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP