Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สลับ Upper diagonal กับ Lower ใน C++


บทช่วยสอนนี้ออกแบบมาเพื่อสลับแถวบนของอาร์เรย์สามแนวทแยงเป็นแถวล่างโดยใช้โค้ด c++ นอกจากนี้ หากอาร์เรย์ 3 เส้นทแยงมุมเป็นอินพุต ผลลัพธ์ที่ต้องการจะต้องเป็นแบบนั้น

สลับ Upper diagonal กับ Lower ใน 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;
}

ผลลัพธ์

ดังที่แสดงด้านล่างในผลลัพธ์ แถวบนที่สลับกับส่วนล่างของอาร์เรย์ 3 มิติเป็น;

Input::
1 2 3
4 5 6
7 8 9
Output(Swaped)::
1 4 7
2 5 8
3 6 9