简体   繁体   中英

Write a C++ function that accepts a 1-D array and calculates the sum of the elements, and displays it

I wanted to create a function that would define an 1d Array, calculate a sum of the elements, and display that sum. I wrote the following code however I'm unaware of the use of pointers and other advanced techniques of coding.

#include <iostream>

using namespace std;


int main()
{
int size;
int A[];

cout << "Enter an array: \n";
cin << A[size];

int sum;

int sumofarrays(A[size]);

sum = sumofarrays(A[size]);
cout << "The sum of the array values is: \n" << sum << "\n";
}


int sumofarrays(int A[size])
{
int i;
int j = 0;
int sum;
int B;

        for (i=0; i<size; i++)
                {
                        B  = j + A[i];
                        j = B;
                }

sum = B;
return(sum);
}

When attempting to compile this code, I get following error:

SumOfArrays.cpp:19:18: error: called object type 'int' is not a function or function pointer sum = sumofarrays(size)

If only you had used a container like std::vector<int> A for your data. Then your sum would drop out as:

int sum = std::accumulate(A.begin(), A.end(), 0);

Every professional programmer will then understand in a flash what you're trying to do. That helps make your code readable and maintainable.

Start using the C++ standard library. Read a good book like Stroustrup.

Please choose Bathsheba's answer - it is the correct one. That said, in addition to my comment above, I wanted to give some more tips:

1) You need to learn the difference between an array on the stack (such as "int A[3]") and the heap (such as a pointer allocated by malloc or new). There's some degree of nuance here, so I'm not going to go into it all, but it's very important that you learn this if you want to program in C or C++ - even though best practice is to avoid pointers as much as possible and just use stl containers! ;)

2) I'm not going to tell you to use a particular indentation style. But please pick one and be consistent. You'll drive other programmers crazy with that sort of haphazard approach ;) Also, the same applies to capitalization.

3) Variable names should always be meaningful (with the possible exception of otherwise meaningless loop counters, for which "i" seems to be standard). Nobody is going to look at your code and know immediately what "j" or "B" are supposed to mean.

4) Your algorithm, as implemented, only requires half of those variables. There is no point to using all of those temporaries. Just declare sum as "int sum = 0;" and then inside the loop do "sum += A[i];"

5) Best practice is - unlike the old days, where it wasn't possible - to declare variables only where you need to use them, not beforehand. So for example, you don't need to declare B or j (which, as mentioned, really aren't actually needed) before the loop, you can just declare them inside the loop, as "int B = j + A[i];" and "int j = B;". Or better, "const int", since nothing alters them. But best, as mentioned in #4, don't use them at all, just use sum - the only variable you actually care about ;)

The same applies to your for-loop - you should declare i inside the loop ("for (int i = ....") rather than outside it, unless you have some sort of need to see where the loop broke out after it's done (not possible in your example).

6) While it really makes no difference whatsoever here, you should probably get in the habit of using "++i" in your for-loops rather than "i++". It really only matters on classes, not base types like integers, but the algorithms for prefix-increment are usually a tad faster than postfix-increment.

7) You do realize that you called sumOfArrays twice here, right?

int sum;

int sumofarrays(A[size]);

sum = sumofarrays(A[size]);

What you really meant was:

const int sum = sumofarrays(A);

Or you could have skipped assigning it to a variable at all and just simply called it inside your cout. The goal is to use as little code as possible without being confusing. Because excess unneeded code just increases the odds of throwing someone off or containing an undetected error.

Just don't take this too far and make a giant mishmash or trying to be too "clever" with one-liner "tricks" that nobody is going to understand when they first look at them! ;)

8) I personally recommend - at this stage - avoiding "using" calls like the plague. It's important for you to learn what's part of stl by having to explicitly call "std::...." each time. Also, if you ever write .h files that someone else might use, you don't want to (by force of habit) contaminate them with "using" calls that will have an effect on other peoples' code.

You're a beginner, that's okay - you'll learn! :)

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