4 / 4 / 4 Регистрация: 09.03.2014 Сообщений: 187 |
|
1 |
|
Найти сумму элементов каждого столбца двумерного массива02.04.2014, 19:40. Показов 43152. Ответов 3
как найти суму елементов каждого столбца двумерного массива(при условии что елементы не должны равняться 0)
0 |
newb_programmer 238 / 238 / 113 Регистрация: 03.09.2011 Сообщений: 558 |
||||
02.04.2014, 21:00 |
2 |
|||
shukaka,
1 |
shukaka 4 / 4 / 4 Регистрация: 09.03.2014 Сообщений: 187 |
||||
02.04.2014, 21:05 [ТС] |
3 |
|||
если я ввожу массив допусим 2 1
0 |
newb_programmer 238 / 238 / 113 Регистрация: 03.09.2011 Сообщений: 558 |
||||
02.04.2014, 21:48 |
4 |
|||
Решениеshukaka,
1 |
Ниже приведена демонстрационная программа, которая отвечает на ваш вопрос
Как найти сумму элементов столбцов массива?
#include <iostream>
#include <iomanip>
int main()
{
const size_t Rows = 3;
const size_t Cols = 4;
int a[Rows][Cols] =
{
{ 0, 1, 2, 3, },
{ 4, 5, 6, 7, },
{ 8, 9, 10, 11, },
};
long long int sum[Cols];
for ( size_t col = 0; col < Cols; col++ )
{
sum[col] = 0;
for ( size_t row = 0; row < Rows; row++ )
{
sum[col] += a[row][col];
}
}
for ( size_t row= 0; row < Rows; row++ )
{
for ( size_t col = 0; col < Cols; col++ )
{
std::cout << std::setw( 2 ) << a[row][col] << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
for ( long long int x : sum ) std::cout << std::setw( 2 ) << x << ' ';
std::cout << std::endl;
return 0;
}
Вывод программы на консоль выглядит следующим образом
0 1 2 3
4 5 6 7
8 9 10 11
12 15 18 21
В программе для вывода сумм столбцов используется цикл for
на основе диапазонов. Если ваш компилятор не поддерживает такую конструкцию, то просто замените его на обычный цикл for
с использованием индексов.
Лучше, если функция будет «не в курсе» размеров массива, так универсальнее.
Тут не проверяю, что массив двухмерный, что элементы числа, что все строки равны по длине. А надо бы..
Берём первую (нулевую) строку и проходясь по остальным, прибавляем значения из соответствующих колонок:
function sum2d(arr) {
var row, col, sum = arr[0].slice();
for( row = 1; row < arr.length; row++) {
for( col = 0; col < sum.length; col++) {
sum[col] += arr[row][col];
}
}
return sum;
}
sum2d([
[1,2,3],
[8,9,0],
])
// [9,11,3]
Перейти к содержанию
Суммы строк и столбцов матрицы
Просмотров 10.7к. Обновлено 15 октября 2021
Посчитать суммы каждой строки и каждого столбца матрицы. Вывести суммы строк в конце каждой строки, а суммы столбцов под соответствующими столбцами.
Поскольку двумерный массив обычно перебирается построчно, то сумму строк считать проще. Можно, заполняя строку матрицы и выводя ее элементы на экран, накапливать в переменной сумму элементов строки и выводить ее в конце строки.
Для сумм столбцов можно предусмотреть отдельный массив, в ячейках которого накапливать сумму каждого столбца. При построчном проходе по матрице, каждый новый элемент следует суммировать с соответствующим ему элементом массива сумм столбцов. Индекс элемента в строке матрицы будет совпадать с индексом элемента в массиве сумм.
Выводить суммы столбцов следует в отдельном цикле.
Pascal
const
M = 10;
N = 5;
var
a: array[1..N,1..M] of integer;
i, j: byte;
s: integer;
sc: array[1..M] of integer;
begin
for i:= 1 to M do
sc[i] := 0;for i:=1 to N do begin
s := 0;
for j:=1 to M do begin
a[i,j] := random(10);
write(a[i,j]:6);
s := s + a[i,j];
sc[j] := sc[j] + a[i,j]
end;
writeln (' |', s);
end;
for i:= 1 to M do
write('--':6);
writeln;
for i:= 1 to M do
write(sc[i]:6);
writeln;end.
Пример выполнения программы:5 5 7 8 6 8 5 8 4 6 |62
6 3 4 2 8 0 9 2 3 4 |41
7 8 5 4 5 3 9 8 0 3 |52
0 6 0 3 8 9 7 1 8 8 |50
9 4 7 8 4 5 7 6 1 7 |58
-- -- -- -- -- -- -- -- -- --
27 26 23 25 31 25 37 25 16 28
Язык Си
сумма элементов каждого столбца матрицы c++
#include < stdio.h>
#define M 10
#define N 5
main() {
int a[N][M];
int sc[M];
int s, i, j;
srand(time(NULL));
for (i=0; i< M; i++) sc[i] = 0;
for (i=0; i< N; i++) {
s = 0;
for (j=0; j< M; j++) {
a[i][j] = rand() % 10;
printf("%5d", a[i][j]);
s += a[i][j];
sc[j] += a[i][j];
}
printf(" |%dn", s);
}
for (i=0; i< M; i++)
printf("%5s", "--");
printf("n");
for (i=0; i< M; i++)
printf("%5d", sc[i]);
printf("n");
}
Python
сумма элементов строки матрицы python (питон)
from random import random
M = 10
N = 5
a = []
for i in range(N):
b = []
for j in range(M):
b.append(int(random()*11))
print("%3d" % b[j], end='')
a.append(b)
print(' |', sum(b))for i in range(M):
print(" --", end='')
print()for i in range(M):
s = 0
for j in range(N):
s += a[j][i]
print("%3d" % s, end='')
print()
Пример(ы) выполнения программы на языке Python:6 7 3 10 10 10 4 2 6 5 | 63
2 8 0 9 0 4 9 3 6 3 | 44
5 3 1 10 5 6 5 2 0 9 | 46
10 9 10 8 7 8 5 2 10 9 | 78
3 3 6 0 4 1 6 10 10 3 | 46
-- -- -- -- -- -- -- -- -- --
26 30 20 37 26 29 29 19 32 29
В Python используется немного иной алгоритм решения задачи. Сначала создается пустой список - будущая матрица. Далее в цикле в нее добавляются вложенные списки.Суммы строк матрицы вычисляются с помощью функции sum(), которой передается текущий список-строка цикла.
Суммы столбцов вычисляются путем прохода по каждому столбу матрицы. Обратите внимание, что здесь наоборот: внешний цикл - проход по столбцам, внутренний - по строкам.
КуМир
алг суммы строк столбцов
нач
цел M = 10, N = 5
цел таб a[1:N,1:M], sc[1:M]
цел i, j, s
нц для i от 1 до M
sc[i] := 0
кцнц для i от 1 до N
s := 0
нц для j от 1 до M
a[i,j] := int(rand(0,10))
вывод a[i,j], " "
s := s + a[i,j]
sc[j] := sc[j] + a[i,j]
кц
вывод " |", s, нс
кцнц для i от 1 до M
вывод "---"
кц
вывод нс
нц для i от 1 до M
вывод sc[i], " "
кц
кон
Basic-256
M = 10
N = 5
dim a(N,M)
dim sc(M)
for i = 0 to N-1
s = 0
for j=0 to M-1
a[i,j] = int(rand*10)
print a[i,j] + " ";
s = s + a[i,j]
sc[j] = sc[j] + a[i,j]
next j
print " |" + s
next ifor i=0 to M-1
print "-- ";
next i
for i=0 to M-1
print sc[i] + " ";
next i
I have two dimensional array as below:
[33] [96] [34] [11] [65] [68] [12] [8 ] [=327]
[94] [91] [3 ] [20] [16] [59] [74] [97] [=454]
[29] [0 ] [31] [13] [4 ] [63] [52] [73] [=265]
[51] [3 ] [55] [74] [52] [79] [61] [74] [=449]
[18] [19] [1 ] [53] [33] [93] [26] [14] [=257]
[56] [41] [4 ] [16] [45] [8 ] [57] [22] [=249]
[43] [33] [43] [59] [61] [58] [58] [69] [=424]
[38] [41] [42] [29] [27] [72] [85] [75] [=409]
[36] [3 ] [23] [65] [40] [56] [41] [96] [=36]
[=?] [=?] [=?] [=?] [=?] [=?] [=?] [=?]
how to get the sum of the columns in the array?
here is my code to get the sum of the rows:
public static void main(String[] args) {
int[][] nums = new int[9][9];
int random, total_rows=0, total_cols=0;
Random randomGenerator = new Random();
for (int i=0; i < 9; i++) {
for (int j=0; j < 9; j++) {
random = randomGenerator.nextInt(100);
nums[i][j] = random;
if(j < 8) {
total_rows += random;
}else {
System.out.print("=");
nums[i][j] = total_rows;
total_rows = 0;
}
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
asked Oct 19, 2011 at 15:30
scoohhscoohh
3756 gold badges12 silver badges19 bronze badges
2
You can try:
int[][] num = new int[9][9];
/*
* ...populate the array
*
*/
for (int i = 0; i < num.length; i++) {
int sum = 0;
for (int j = 0; j < num[i].length; j++) {
sum += num[j][i];
}
System.out.println(sum);
}
answered Oct 19, 2011 at 15:38
Konstantin YovkovKonstantin Yovkov
61.9k8 gold badges100 silver badges147 bronze badges
I’d separate your array-generation code from your summation/display code.
You should then be able to notice that all you’ll have to do is flip i
and j
when accessing the array in the inner loop.
answered Oct 19, 2011 at 15:34
Clockwork-MuseClockwork-Muse
12.7k6 gold badges30 silver badges45 bronze badges
Homework question
So, instead of giving you code, I’m going to tell you that you are quite close to the answer already.
To tally the columns, you need a separate array, and then, as you create each column in each row, simply add that value to the correct position.
At the end of the day, you will have the row total, as well as the column total. Given what you’ve done thus far, it should be easy for you to do.
answered Oct 19, 2011 at 15:36
EwaldEwald
5,6612 gold badges27 silver badges31 bronze badges
Here is the code;
Demo Code for Sum of Rows and Columns of a 2d-Array
import java.util.Random;
public class SumOfColumns {
public static void main(String[] args) {
int[][] nums = new int[9][9];
handleArray(nums);
printArray(nums);
}
private static int getSumOfRow(int[][] array, int rowNum) {
int sumOfRows = 0;
for(int i = 0; i < array[rowNum].length; i++)
sumOfRows += array[rowNum][i];
return sumOfRows;
}
private static int getColumnSum(int[][] array, int columnNum) {
int sumOfColumn = 0;
for(int i = 0; i < array.length; i++)
sumOfColumn += array[i][columnNum];
return sumOfColumn;
}
private static void handleArray(int[][] array) {
Random randomGenerator = new Random();
for (int i=0; i < array.length; i++) {
for (int j=0; j < array[i].length; j++) {
int random = randomGenerator.nextInt(100);
array[i][j] = random;
}
}
}
private static void printArray(int[][] array) {
System.out.printf(" ");
for(int i = 0; i < array.length; i++)
System.out.printf("%4d ", i);
System.out.println("n __________________________________________________");
for(int i = 0; i < array.length; i++) {
System.out.printf("%4d | ", i);
for(int j = 0; j < array[i].length; j++)
System.out.printf("%4d ", array[i][j]);
System.out.printf("| Sum = %4d", getSumOfRow(array, i));
System.out.println();
}
System.out.println(" __________________________________________________");
handleSumOfColumnPrint(array);
}
private static void handleSumOfColumnPrint(int[][] array) {
System.out.printf(" ");
for(int i = 0; i < array[0].length; i++)
System.out.printf("%4d ", getColumnSum(array, i));
}
}
Sample Output
0 1 2 3 4 5 6 7 8
__________________________________________________
0 | 1 86 95 71 78 21 85 99 35 | Sum = 571
1 | 45 82 68 75 30 1 71 94 8 | Sum = 474
2 | 33 78 61 74 52 75 63 8 1 | Sum = 445
3 | 17 10 99 78 61 73 63 40 8 | Sum = 449
4 | 66 68 54 74 28 78 13 4 79 | Sum = 464
5 | 75 60 79 76 55 14 20 28 27 | Sum = 434
6 | 17 17 29 39 6 90 0 94 75 | Sum = 367
7 | 57 89 73 27 28 42 92 36 16 | Sum = 460
8 | 40 44 79 64 92 90 43 60 53 | Sum = 565
__________________________________________________
351 534 637 578 430 484 450 463 302
answered Apr 27, 2016 at 0:33
Levent DiviliogluLevent Divilioglu
11.1k5 gold badges59 silver badges106 bronze badges
Array[][] // Vertical, Horizontal.
//sum of row n:
sum=0
for(int i:Array[n]){
sum+=i;
}
//sum of column n:
sum=0
for(int i=0;i<Array.length();i++){
sum+=Array[i][n];
}
I hope this makes sense.
answered Oct 19, 2011 at 15:36
MartinHaThMartinHaTh
1,4171 gold badge13 silver badges25 bronze badges
Homework question by any chance?
If so, maybe some hints would be more helpful?
You are calculating the row total while you are generating the 2d array — since you are doing this row by row it makes it easy for you to calculate this for rows (as you can build it up as you go along), but more tricky for columns since you effectively lose track of the previous rows each iteration.
If you only generate the array in the first for loops you will have a fully populated 2d array, but no row/column totals. But the data remains in your array, so you can now write code to calculate these totals.
As a small hint: if you wrote another loop after generating the data along the lines of:
int columnTotal = 0;
for (int r=0; r < 9; r++) {
columnTotal += nums[r][0];
}
that should let you sum the values of the first column (column 0).
Hope this helps
answered Oct 19, 2011 at 15:42
davbryndavbryn
7,1802 gold badges24 silver badges47 bronze badges
Here is my code to solve the problem…
import java.util.Random;
public class columnsAndRowsSummatory
{
static int x = 0;
static int y = 0;
public static void main (String[] arg)
{
String spaces = " " ;
//There are 7 spaces on the spaces String
int[][] nums = new int[9][9];
int random, rowTotal = 0, colTotal = 0;
Random randomGenerator = new Random();
String ColTotal = "";
for ( x = 0; x < nums.length -1; x++)
{
rowTotal = 0;
for (y = 0; y < nums.length ; y++)
{
random = randomGenerator.nextInt(10000);
nums[x][y] = random;
while( y < nums.length -1 )
{
rowTotal = rowTotal + random;
break;
}
if(y < nums.length -1 && x != nums.length -1 && random != 0)
{
int z = (int)Math.floor(Math.log10(random) );
System.out.print(random + spaces.substring( (z) ) );
//This method calculates how many digits does the number 'random'
//Have and takes that amount away from the spaces string to even
//Out numbers displayed
}
else if(random == 0 && x != nums.length -1)
{
System.out.print(random + spaces);
}
else
{
System.out.printf("= %d ", rowTotal);
}
}
System.out.println();
}
for(x = 0; x < nums.length -1; x++)
{
for (y = 0; y < nums.length -1 ; y++)
{
colTotal = colTotal + nums[y][x];
}
int z = (int)Math.floor(Math.log10(colTotal) );
ColTotal = ColTotal + colTotal + spaces.substring(z) ;
colTotal = 0;
}
System.out.print(ColTotal + "<-Totals^");
}
}
Now in this code would display a neat array of how many number of rows and columns you want and it would display the column/row total on the corresponding last line of the array. If you would be dealing with numbers higher than 10 million, then all you need to do is add a space to the spaces string and you’re good to go.
For example if you have
random = randomGenerator.nextInt(999999);
It would display something like this:
711778 119342 62648 8035 652270 344935 101175 265275 174969 = 2440427
414592 798519 453329 988340 180647 540748 572587 675951 903581 = 5528294
747535 955957 47966 742898 773810 34212 914212 625716 209569 = 5051875
492510 998618 622957 517383 704277 397076 970357 280134 842993 = 5826305
190916 57734 590635 944535 991653 366530 145640 402605 456611 = 4146859
117598 612710 967466 67209 660383 247281 304953 141144 260186 = 3378930
635384 660332 768930 340590 800611 758383 41154 289514 189504 = 4484402
173484 740549 226505 921889 135020 555594 554520 65581 433272 = 3806414
796617 601478 77503 161865 891582 715084 14614 189920 568788 = 4017451
4280414 5545239 3817939 4692744 5790253 3959843 3619212 2935840 4039473 <-Totals^
wattostudios
8,65613 gold badges43 silver badges57 bronze badges
answered Oct 27, 2012 at 3:27