在 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