在Java中查找矩阵首行和末行元素之和的乘积
矩阵不仅仅是数据的集合,它更是一种以二维矩形布局排列的数据元素的集合。在Java中,二维数组可以被认为是一个矩阵。
根据题目要求,任务是找到矩阵中首行和末行所有元素之和的乘积。
让我们深入研究这篇文章,了解如何使用Java编程语言来完成这个任务。
举几个例子
示例1
假设原始矩阵是
{{15,5,9},
{4,14,16},
{7,8,19}};
在找到矩阵中首行和末行所有元素之和的乘积后,结果索引将为:
首行和末行所有元素之和的乘积是:986
示例2
假设原始矩阵是
{{11,7,2},
{3,4,24},
{12,8,15}};
在找到矩阵中首行和末行所有元素之和的乘积后,结果索引将为:
首行和末行所有元素之和的乘积是:700
算法
步骤1 - 初始化并声明矩阵。
步骤2 - 初始化并声明首行和末行元素为0。
步骤3 - 使用for循环计算首行和末行元素的和。
步骤4 - 找到首行和末行所有元素的总和。
步骤5 - 找到两者之间的乘积。
步骤6 - 打印结果。
多种方法
我们提供了多种解决方法。
使用矩阵元素的静态初始化
使用用户自定义方法
让我们逐一查看程序及其输出。
方法1:使用矩阵的静态初始化
在这种方法中,矩阵元素将在程序中初始化。然后根据算法找到首行和末行所有元素之和的乘积。
示例
public class Main{
//main method
public static void main(String args[]){
//Initialising and declaring matrix
int arr[][] = {{15,5,9},
{4,14,16},
{7,8,19}};
int row, col ;
//Initialising and declaring the first row and last row as 0
int first_Row_Sum=0;
int last_Row_Sum=0;
//for loop to calculate the sum of first row elements and last row elements
for(row=0;row<3;row++){
for(col=0;col<3;col++){
//finding sum of all elements of the first row
if(row==0)
first_Row_Sum = first_Row_Sum+arr[0][col];
//finding sum of all elements of the last row
else if(row==2)
last_Row_Sum = last_Row_Sum+arr[2][col];
}
}
//finding product between sum of first row elements and last row elements
int prod = first_Row_Sum * last_Row_Sum;
//Printing the product of first row elements and last row elements
System.out.print("Product of sum of all elements in first row and last row is: "+prod);
}
}
输出
Product of sum of all elements in first row and last row is: 986
方法2:使用用户自定义方法
在这种方法中,矩阵元素将在程序中初始化。然后通过将矩阵作为参数传递给用户自定义方法,并在方法内部根据算法找到首行和末行所有元素之和的乘积。
示例
public class Main{
//main method
public static void main(String args[]){
//Initialising and declaring matrix
int arr[][] = {{11,7,2},
{3,4,24},
{12,8,15}};
func(arr);
}
//user defined method
static void func(int arr[][]){
int row, col ;
//Initialising and declaring the first row and last row as 0
int first_Row_Sum=0;
int last_Row_Sum=0;
//for loop to calculate the sum of first row elements and last row elements
for(row=0;row<3;row++){
for(col=0;col<3;col++){
//finding sum of all elements of the first row
if(row==0)
first_Row_Sum = first_Row_Sum+arr[0][col];
//finding sum of all elements of the last row
else if(row==2)
last_Row_Sum = last_Row_Sum+arr[2][col];
}
}
//finding product between sum of first row elements and last row elements
int prod = first_Row_Sum * last_Row_Sum;
//Printing the product of first row elements and last row elements
System.out.print("Product of sum of all elements in first row and last row is: "+prod);
}
}
输出
Product of sum of all elements in first row and last row is: 700
在这篇文章中,我们探讨了使用Java编程语言检查对角占优矩阵的不同方法。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP