R
R
Raily Krevch2021-10-30 19:47:42
C++ / C#
Raily Krevch, 2021-10-30 19:47:42

It is necessary to display in the label1 field the number of the matrix column with the smallest sum. How to do it?

Here's what I have so far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace дз
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.RowCount = 4; 
            dataGridView1.ColumnCount = 5;
            int[,] a = new int[4, 5];
            int i, j;
            
            Random rand = new Random();
            for (i = 0; i < 4; i++)
                for (j = 0; j < 5; j++)
                    a[i, j] = rand.Next(1, 100);
            //выводим матрицу в dataGridView1
            for (i = 0; i < 4; i++)
                for (j = 0; j < 5; j++)
                    dataGridView1.Rows[i].Cells[j].Value = a[i, j].ToString();
            



        }

        private void button2_Click(object sender, EventArgs e)
        {

            int sum = 0;
            for (int k = 0; k < dataGridView1.Rows.Count; ++k)
            {
                sum += Convert.ToInt32(dataGridView1.Rows[k].Cells[1].Value);

                label1.Text = sum.ToString();
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Glebov, 2021-11-16
@GLeBaTi

We create a separate array `sum`, in which we will store / calculate the sum of each column:

int[] sum = new int[5];
int max = Int32.MinValue;
int maxColumnIndex = 0;
for (int k = 0; k < dataGridView1.Rows.Count; ++k)
{
    for(int j = 0; j < dataGridView1.Rows[k].Cells.Count; j++)
    {
        var colSum = sum[j] + Convert.ToInt32(dataGridView1.Rows[k].Cells[j].Value);
        sum[j] = colSum;
        if(colSum > max){
            max = colSum;
            maxColumnIndex = j;
        }
    }
}

label1.Text = maxColumnIndex.ToString();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question