จากเมทริกซ์สี่เหลี่ยมจัตุรัส 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\n", rproduct);
printf("Product of middle column: %d\n", 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