Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 위쪽 대각선을 아래쪽으로 바꾸기

<시간/>

이 자습서는 C++ 코드를 사용하여 3-대각선 배열의 위쪽 행을 아래쪽 행으로 바꾸도록 설계되었습니다. 게다가 3대각 배열이 입력이라면 원하는 결과는 다음과 같아야 합니다.

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