user1582575
user1582575

Reputation: 89

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?

Upvotes: 0

Views: 33291

Answers (5)

Digital_Reality
Digital_Reality

Reputation: 4738

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);
}

Upvotes: 0

SoulRayder
SoulRayder

Reputation: 5166

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];
    }
}

Upvotes: 0

Hashim Khan
Hashim Khan

Reputation: 440

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];

  }
}

Upvotes: 0

Chowlett
Chowlett

Reputation: 46667

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];

  }
}

Upvotes: 0

Manos Ikonomakis
Manos Ikonomakis

Reputation: 31

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];

  }
}

Upvotes: 2

Related Questions