流程图算法 |从数组中查找 Cpp 中的矩阵

问题描述

我遇到过这个关于算法主题的练习,使用流程图来分别呈现和测试矩阵行的总和。

The Exercise with Matric

0 1 -2
-2 2 5
1 3 -1

直到现在,我都不知道用 Flowchart 计算矩阵,你们能帮我吗?如果您使用 Flowgorithm 应用程序或任何其他类似应用程序来执行此操作,那就太好了。

结果应该是: 第一行:-1 第二个:5 对于第三个:3

我这样做了,但我不知道如何优化代码

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int rreshti[9] = {
        0,1,-2,2,5,3,-1,};

    int r1,r2,r3;
    r1 = 0;
    r2 = 0;
    r3 = 0;

    for(int i = 0; i <= 2; i++) {
        r1 = r1 + rreshti[i];
    };
    cout << "Totali i reshtit te pare: " << r1 << endl;

    for (int i = 3; i <= 5; i++) {
        r2 = r2 + rreshti[i];
    };
    cout << "Totali i reshtit te pare: " << r2 << endl;

    for (int i = 6; i <= 8; i++) {
        r3 = r3 + rreshti[i];

    };
    cout << "Totali i reshtit te pare: " << r3 << endl;

    return 0;
}

解决方法

您可以像在二维矩阵中使用的那样使用嵌套循环。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int no_of_rows = 3; // I would reccommend you to replace constants and use variables like this.
    int no_of_cols = 3;

    int rreshti[no_of_rows * no_of_cols] = {
        0,1,-2,2,5,3,-1,};

    vector<int> rowSum(no_of_rows,0);

    for(int i = 0; i < no_of_rows; i++){
        for(int j = 0; j < no_of_cols; j++){
            rowSum[i] += rreshti[i*no_of_cols + j];
        }cout<<"Sum of row no. "<<(i+1)<<" is = "<<rowSum[i]<<endl;
    }

    return 0;
}