0
#include<iostream>
using namespace std;
int main()
{   
    // declared and initialized the 2d array
    int arr2d[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
    int i, j;
    system("cls");
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 4; j++)
        {
            cout << arr2d[i][j] << "\t";
        }    
        cout << endl;
    }
    system("pause");      
 }

This is my (professor's) code. I'm still a newbie to C++ tho (1st year student in college actually). I want to know a simple and really basic code that will help me to get the sum of all the values I declared and initialized in the 2D array. :)

*BTW I'm using Dev Bloodshed C++ 4.9.9.2

2 Answers 2

1

Create a integer to contain the sum. Then, inserted after you cout the value:

sum+=arr2d[i][j];

This simply keeps a running total of all the values. When your loops finish, it will have encountered and added every value to itself.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I can't 1+ up your answer though, I need more rep. Haha, thanks a bunch man :)
0

You can use the std::accumulate free function (found in the header <algorithm>):

int arr2d[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
int sum = std::accumulate(&arr2d[0][0], &arr2d[2][4], 0);

The &arr2d[0][0] is the pointer to the beginning of the array (which act like a random access iterator for the algorithm) and the &arr2d[2][4] is the address of the past-the-end element of the array (which is required by the function). Notice that the past-the-end element is guaranteed by the Standard to exist and have a valid address.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.