यह ट्यूटोरियल 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;
} आउटपुट
जैसा कि आउटपुट में नीचे देखा गया है, ऊपरी पंक्ति को 3D सरणी के निचले खंड के साथ बदल दिया गया है;
Input:: 1 2 3 4 5 6 7 8 9 Output(Swaped):: 1 4 7 2 5 8 3 6 9