简体   繁体   中英

2D array print out sum of elements

I writing a program that sum of elements in a 2D array and print out the sum.

Here my code so far:

#include <iostream>
#include <stdio.h>

int main()
{
    int array [3][5] = 
    {
        { 1, 2, 3, 4, 5, }, // row 0
        { 6, 7, 8, 9, 10, }, // row 1
        { 11, 12, 13, 14, 15 } // row 2
    };

    int i, j=0;
    int num_elements=0;
    float sum=0;

    for (i=0; i<num_elements; i++)
    {
        sum = sum + array[i][j];

    }

/*for(i=0; i<num_elements; i++)
   {
     printf("%d ", array[i][j]);
   }*/

    // printf("a[%d][%d] = %d\n", sum);

    // output each array element's value 
    for ( i = 0; i < 3; i++ )
    {
      for ( j = 0; j < 5; j++ )
      {
          printf("a[%d][%d] = %d\n", i,j, array[i][j]);

      }
    }

    system("PAUSE");
    return 0;
}

I can print out the elements in each array fine. But I want to print out the sum of elements. I tried one as you can see in the comment section but it didn't work. Can anyone help?

You are summing only the first column of your matrix:

sum = sum + array[i][j];

where j is set to 0.

use a double loop:

for ( i = 0; i < 3; i++ )
{
  for ( j = 0; j < 5; j++ )
  {
      sum+=array[i][j];

  }
}

This loop's the problem:

int i, j=0;    
int num_elements=0;
float sum=0;

for (i=0; i<num_elements; i++)
{
    sum = sum + array[i][j];

}

It won't execute at all, since i<num_elements is never true - num_elements is 0. On top of which, you don't ever set j away from 0.

You need a double loop, like you use later on:

for ( i = 0; i < 3; i++ )
{
  for ( j = 0; j < 5; j++ )
  {
      sum += array[i][j];

  }
}

Try this to sum of all elements in 2D array-

for ( i = 0; i < 3; i++ )
{
  for ( j = 0; j < 5; j++ )
  {
      sum=sum+array[i][j];

  }
}

First of all, you have initialized num_elements as zero. So you wont get anything.

Also, for this,

You need a double loop to print sum of all elements. Also declare additional variables such as row_num (for number of rows) and element_num for number of elements in each row, and then use this code.

for(i=0; i<row_num; i++)
{
    for(j=0; j<element_num; j++)
    {
            sum = sum + array[i][j];
    }
}

As array stored in contiguous memory, it is possible to use only one loop.

for (int i=0; i<(3*5); i++) <-- 3*5 is  num_of_colums*num_of_rows.
{
     sum = sum + *(array[0]+i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM