C語言中奇數階方陣中間行與中間列的乘積
給定一個方陣mat[row][column],其中行數和列數相等且為奇數,這意味著行數和列數必須是奇數,即不能被2整除,任務是找到該矩陣中間行和中間列的乘積。
如下圖所示:
約束條件
矩陣必須是方陣。
列數和行數必須是奇數。
輸入
mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
輸出
Product of middle row = 120 Product of middle column = 80
解釋
Product of middle row = 4 * 5 * 6 = 120 Product of middle column = 2 * 5 * 8 = 80
輸入
mat[][] = {{3, 5, 0}, {1, 2, 7}, {9, 0, 5}}
輸出
Product of middle row = 14 Product of middle column = 0
解釋
Product of middle row = 1 * 2 * 7 = 120 Product of middle column = 5 * 2 * 0 = 0
下面使用的方法如下,用於解決問題
將矩陣mat[][]作為輸入。
從中間行和中間列遍歷矩陣
計算中間行和中間列的乘積並返回結果。
演算法
Start In function int product(int mat[][MAX], int n) Step 1→ Declare and initialize rproduct = 1, cproduct = 1 Step 2→ Loop For i = 0 and i < n and i++ Set rproduct = rproduct * mat[n / 2][i] Set cproduct = cproduct * mat[i][n / 2] Step 3→ Print "Product of middle row: rproduct “ Step 4→ Print "Product of middle column: cproduct” In function int main() Step 1→ Declare and initialize mat[][MAX] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } Step 2→ Call product(mat, MAX) Stop
示例
#include <stdio.h> #define MAX 3 int product(int mat[][MAX], int n){ int rproduct = 1, cproduct = 1; //We will only check the middle elements and //find their products for (int i = 0; i < n; i++) { rproduct *= mat[n / 2][i]; cproduct *= mat[i][n / 2]; } // Printing the result printf("Product of middle row: %d
", rproduct); printf("Product of middle column: %d
", cproduct); return 0; } // Driver code int main(){ int mat[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; product(mat, MAX); return 0; }
輸出
如果執行上述程式碼,它將生成以下輸出:
Product of middle row: 120 Product of middle column: 80
廣告