Thread: Calculate the sum of all integers in an array using a function and return the sum?

  1. #1
    Registered User
    Join Date
    Oct 2016
    Posts
    17

    Question Calculate the sum of all integers in an array using a function and return the sum?

    Hello!

    I want to create an array of 5 integers in main, pass it into a function, have the function add up all the integers, return a sum to main, store the sum, print the sum on screen.

    I was thinking about something like this:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int myFunc(int *arr, int arrSize)
    {
        int sum = 0;
    
        for(int i = 0; i < arrSize; i++)
        {
            sum = sum + *arr[i];
        }
    
        return sum;
    }
    
    // Enters the program
    int main()
    {
        // Creates an array of 5 integers
        int arr[] = {1, 2, 3, 4, 5};
        int x = 0;
    
        x = myFunc(arr, (sizeof(arr)/sizeof(int)));
    
        cout << x;
    
        // Exits the program
        return 0;
    }

    Question 1:
    Is int *arr pointing to the arr in main? Can I reference all elements in arr this way?

    Question 2:
    Can I copy all integers from main into myFunc() without a pointer? Perhaps by creating a new array in the parameter list?

    Question 3:
    Do I need the arrSize parameter in the function?

    Question 4:
    Is "return sum" out of scope?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,608
    1: Well, yes, you can use a pointer to index an array, but you don't need the star.
    Code:
    mingw32-g++.exe -Wall -fexceptions -pedantic-errors -pedantic -Wfatal-errors -std=c++98 -g  -c C:\Users\jk\Desktop\hello\main.cpp -o obj\Debug\main.o
    C:\Users\jk\Desktop\hello\main.cpp: In function 'int myFunc(int*, int)':
    C:\Users\jk\Desktop\hello\main.cpp:11:27: error: invalid type argument of unary '*' (have 'int')
             sum = sum + *arr[i];
                               ^
    compilation terminated due to -Wfatal-errors.
    2: It's more complicated than the pointer option. Details here.
    3: No, but you might prefer it to other options.
    Code:
    int myFunc(int *first, int *last)
    {
       int sum = 0;
       while (first != last) { sum += *first++; }
       return sum;
    }
    
    #include <iostream>
    int main() 
    {
       int arr[] = {1,2,3,4,5};
       int sum = 0;
       sum = myFunc(arr, arr + sizeof(arr) / sizeof(arr[0]));
       std::cout << sum << std::endl;
    }
    4: No... if it was the compiler would tell you.

  3. #3
    Registered User
    Join Date
    Oct 2016
    Posts
    17
    Variable argument list? My argument list is finite, is it not? I mean I only have 2 arguments that I pass in.

    When I try to compile the code above I get an error.

    Code:
    error: invalid type argument of unary '*' (have 'int')
    What do I need to change in my code?

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,608
    Variable argument list? My argument list is finite, is it not? I mean I only have 2 arguments that I pass in.
    Correct me if I am wrong, but did you want to call myFunc like this:
    Code:
    sum = myFunc(1, 2, 3, 4, 5);
    If so, then chances are you need to use a variable argument list. If you did use it, you could also call this:
    Code:
    sum = myFunc(1, 2, 3);
    and many other potential calls.

    In fairness, there is a simple way using the array template. It's also closer to what you actually asked.
    Code:
    #include <array>
    #include <initializer_list>
    
    int myFunc(std::array<int> arr);
    
    sum = myFunc( { 1, 2, 3, 4, 5 } );
    What do I need to change in my code?
    As highlighted by the compiler, delete the * on that line. It is wrong.

  5. #5
    Registered User
    Join Date
    Oct 2016
    Posts
    17
    Quote Originally Posted by whiteflags View Post
    Correct me if I am wrong, but did you want to call myFunc like this:
    Code:
    sum = myFunc(1, 2, 3, 4, 5);
    If so, then chances are you need to use a variable argument list. If you did use it, you could also call this:
    Code:
    sum = myFunc(1, 2, 3);
    and many other potential calls.
    I now see what you mean. I suppose that is the effect I wanted. I just didn't picture it that way.

    Variable argument list... yeah, I see now where that's coming from. I thought of it as my argument list being finite, like 5 arguments or less. I expected the parameter list in the function to expand to the length of my array, but not less than that.

    Think of it this way.

    Code:
    int myFunc(inte a, int b, int c, int d, int e);
    I thought I would need not fill all the ints with values if my array contains fewer elements than there are ints or arguments in the function. If my array contains 3 elements I would pass in values for a, b and c, but not for d or e. But of course, the number of arguments I pass in must be the same as the number of parameters in the function. It's required.

    I thought the function could take all the elements in my array as one big blob, and then go through them, add up the numbers and return a sum.

    I'm just confusing myself. I don't want to confuse you too. I think you read me correctly.

    Quote Originally Posted by whiteflags View Post
    In fairness, there is a simple way using the array template. It's also closer to what you actually asked.
    Code:
    #include <array>
    #include <initializer_list>
    
    int myFunc(std::array<int> arr);
    
    sum = myFunc( { 1, 2, 3, 4, 5 } );
    As much as I would like to test this, I really would like to keep it to the bare basics I have learned so far. I want to try it my way and see if it can be done.

    Quote Originally Posted by whiteflags View Post
    As highlighted by the compiler, delete the * on that line. It is wrong.
    I removed the asterisk on line 5. I now get a different error.

    Code:
    error: invalid types 'int[int]' for array subscript
    (I'm using CodeBlocks 16.01 with MinGW on Windows 10.)
    Last edited by cozySam; 10-09-2016 at 01:46 PM.

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,608
    I thought the function could take all the elements in my array as one big blob, and then go through them, add up the numbers and return a sum.
    Yeah, about variable argument lists, I think it is better to forget about them and use pointers for now. Pointers to the first element are how built-in arrays are passed to functions, so it isn't really something you should be trying to avoid in C/C++. That is, unless you use a type like std::array. As nice as that feature is in like, MS Excel and stuff, in C++ it is difficult to replicate while under a lot of restrictions.

    As much as I would like to test this, I really would like to keep it to the bare basics I have learned so far.
    That's fair, but be aware that some people consider learning things like std::array first to be the correct or basic approach. This is the approach that some books also take, like Accelerated C++. You'll probably hear it from someone else if you stay on the forum long enough, so I wanted to be the first to say. I like to think I'm nicer about it.

    It's usually not helpful to just paste your errors. I would need to see a program just to see how you changed what you wrote too. In this case though, I don't mind pasting a working program for you. The error in the original was simple enough.

    Code:
    #include <iostream>
     
    using namespace std;
     
    int myFunc(int *arr, int arrSize)
    {
        int sum = 0;
     
        for(int i = 0; i < arrSize; i++)
        {
            sum = sum + arr[i];
        }
     
        return sum;
    }
     
    // Enters the program
    int main()
    {
        // Creates an array of 5 integers
        int arr[] = {1, 2, 3, 4, 5};
        int x = 0;
     
        x = myFunc(arr, (sizeof(arr)/sizeof(int)));
     
        cout << x;
     
        // Exits the program
        return 0;
    }

  7. #7
    Registered User
    Join Date
    Oct 2016
    Posts
    17
    This is essentially what I wanted:

    Code:
    #include <iostream>
    
    using namespace std;
    
    // Enters the program
    int main()
    {
        // Creates an array of 5 integers
        int arr[] = {1, 2, 3, 4, 5};
        int sum = 0;
    
        // Calculates the sum of ints
        for(int i = 0; i < 5; i++)
        {
            sum = sum + arr[i];
        }
    
        cout << sum;
    
        // Exits the program
        return 0;
    }
    With only difference that I wanted to move the calculation to a function that I can call and have it return the sum. Without going into too advanced techniques, how would I do this? Preferably using arrays and pointers.
    Last edited by cozySam; 10-09-2016 at 02:06 PM.

  8. #8
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,608
    In the reply above yours, I posted some correct code that does what you ask. You were very close. There were just other questions to answer.

    HTH

  9. #9
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    If you're allowed to use some parts of the STL, are you allowed to use std::accumulate?

  10. #10
    Registered User
    Join Date
    Oct 2016
    Posts
    17
    Quote Originally Posted by whiteflags View Post
    In the reply above yours, I posted some correct code that does what you ask. You were very close. There were just other questions to answer.

    HTH
    Sorry, I skipped past your reply. So I didn't see it at first.

    Quote Originally Posted by whiteflags View Post
    Yeah, about variable argument lists, I think it is better to forget about them and use pointers for now. Pointers to the first element are how built-in arrays are passed to functions, so it isn't really something you should be trying to avoid in C/C++. That is, unless you use a type like std::array. As nice as that feature is in like, MS Excel and stuff, in C++ it is difficult to replicate while under a lot of restrictions.
    Yeah, I have seen other people use std::array. But I don't feel comfortable using that since I don't fully understand it and I have zero practice with that. Also, in my book, it is not explained at all.

    Quote Originally Posted by whiteflags View Post
    That's fair, but be aware that some people consider learning things like std::array first to be the correct or basic approach. This is the approach that some books also take, like Accelerated C++. You'll probably hear it from someone else if you stay on the forum long enough, so I wanted to be the first to say. I like to think I'm nicer about it.
    You are not the first to say it! But yes, I understand your view point. But like I said, my book does not explain this at all. It's the same with strings. In my book, the author uses C style strings. People keep telling me to use the string class or whatever. I have tested this and it is completely different, it's much easier. But I want to stick to what my book teaches for now.

    In time, I shall learn to use the string, array and vector classes and thereby make life easier for me. I don't know what the correct approach is to teaching C++. I'm just a programming beginner and a complete novice to C++. I don't want to skip between methods and techniques. But I do wish that people who call themselves C++ teachers, tutors and who write C++ books for beginners could come up with a common standard for teaching this subject. There are too many opinions being passed around left and right. I am just a student, it's not my job to know what's right and what's not. I have enough on my plate already as it is. I approached C++ to learn it, not to teach it. Once I know enough about it, I might choose or be given the task to teach others and I might have developed my own preference or opinion about all this. But for now, I am happy if I can do the bare basics... whatever that is now (depends on who you ask apparently).

    Quote Originally Posted by whiteflags View Post
    It's usually not helpful to just paste your errors. I would need to see a program just to see how you changed what you wrote too. In this case though, I don't mind pasting a working program for you. The error in the original was simple enough.
    You are right! I was actually hesitating there for a second whether or not I should paste the whole program all over again. I decided to just reference line 5 in the original program at the top. I didn't want to add too many pastes. So I removed the asterisk in the parameter, but I missed it in the for loop. I slapped myself when I saw that! Thank you!
    Last edited by cozySam; 10-09-2016 at 03:00 PM.

  11. #11
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Yeah, I have seen other people use std::array. But I don't feel comfortable using that since I don't fully understand it and I have zero practice with that. Also, in my book, it is not explained at all.
    std::array is a C++ container that's basically a wrapper around
    Code:
    T data[N]
    where T is your data type and N is a compile-time-known constant (so something like `int const n = 1337;` would suffice). It's a pretty think abstraction layer over a raw C array and operates a lot more naturally in the STL ecosystem.

    It's worth using. Read about it here: std::array - cppreference.com

  12. #12
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,608
    Just to be absolutely clear (in paranoia) note from my example that int *arr is the correct thing to write in the parameter list. In the function body, between the braces, it can be a different story: arr[i] is completely valid. So is something ugly like *(arr + i).

  13. #13
    Registered User
    Join Date
    Oct 2016
    Posts
    17
    Quote Originally Posted by MutantJohn View Post
    If you're allowed to use some parts of the STL, are you allowed to use std::accumulate?
    I am not allowed or disallowed anything. As I explained above, my book is very simple and it does not explain many of these things. It's just some quick introductory text book to programming in general using the C++ language. I use it in a distance learning course on programming for beginners. But I can do whatever I want. My main mission is to learn programming and to learn C++ at the same time.

    I plan on using this, in some modified version, as part of a bigger program which is an assignment for the course. It's just that I have broken the assignment into smaller parts that I can work with. Before I put it all together, and hopefully make it work. But hey I wrote this all by myself, so the teacher can't tell me I copy and pasted the code. I don't want to copy and paste without understanding. I ought to be able to defend my program if the teacher comes and says I copied it.

    But as I was saying, my main mission is to learn programming and to learn C++ in the process. So I am very curious to see how you would have solved this problem. So please, be my guest! Take it away! Move me!

    Quote Originally Posted by MutantJohn View Post
    std::array is a C++ container that's basically a wrapper around
    Code:
    T data[N]
    where T is your data type and N is a compile-time-known constant (so something like `int const n = 1337;` would suffice). It's a pretty think abstraction layer over a raw C array and operates a lot more naturally in the STL ecosystem.

    It's worth using. Read about it here: std::array - cppreference.com
    Wow! You really know some words and stuff! I have no idea what you said. Except STL which I know means Standard Template Library. It's some kind of cook book for C++ code, right? Wrapper? I don't know... I think back to HTML and CSS.
    Last edited by cozySam; 10-09-2016 at 03:17 PM.

  14. #14
    Nasal Demon Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    179
    In my book, the author uses C style strings.
    Ouch!
    I mean, sure, do learn how bare arrays and pointers work. You want to know that. However, switch to modern idioms as soon as you can - maybe a more modern book would suit you better. std::vector, std::string, algorithms, etc, are pretty cool.

    But of course, the number of arguments I pass in must be the same as the number of parameters in the function. It's required.
    Yes, it's required. Mostly.
    But there is a way to have it done with limited max amount of parameters, similar to how you envisioned it in that post - and not use the variadic function. To do that you'd use default arguments or function overloading. With the former you have one function that has many default arguments, with the latter you have many functions with different number of arguments.

  15. #15
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I want to create an array of 5 integers in main, pass it into a function, have the function add up all the integers, return a sum to main, store the sum, print the sum on screen.
    I am not allowed or disallowed anything. As I explained above, my book is very simple and it does not explain many of these things. It's just some quick introductory text book to programming in general using the C++ language. I use it in a distance learning course on programming for beginners. But I can do whatever I want. My main mission is to learn programming and to learn C++ at the same time.

    But as I was saying, my main mission is to learn programming and to learn C++ in the process. So I am very curious to see how you would have solved this problem. So please, be my guest! Take it away! Move me!
    Fair enough!
    Code:
    #include <numeric>
    #include <vector>
    #include <iostream>
    
    using std::accumulate;
    using std::vector;
    using std::cout;
    
    int main(void)
    {
      using integral = int;
    
      vector<integral> v{1, 2, 3, 4, 5};
      integral const sum{accumulate(v.begin(), v.end(), 0)};
      cout << "sum is : " << sum << "\n";
    
      return 0;
    }
    So, there's a lot going on here in actually relatively few lines of code so don't be turned off! This was sort of written to be a "thrown into the deep end of C++" kind of example.

    std::accumulate is a really cool function that takes the beginning and end of a range and sums up all the elements for you!

    But what's a "beginning" and what's a "end"? Well... std::vector is an array-like data structure. You can think of it like a C array on crack and it's one of the bread-and-butter data structures in C++. Well, it happens to have two methods called "begin" and "end" that do exactly what we want. "begin" returns an "iterator" to the beginning of the vector and "end" returns an iterator to one-past the last element. The whole one-past-the-end thing is kind of weird. Why would we want that? Well, it's because std::accumulate is basically doing this:
    Code:
    int accumulate(int* begin, int* end)
    {
      int sum = 0;
      for (int* curr = begin; curr < end; ++curr)
        sum += *curr;
    
      return sum;
    }
    The key there is not the `< end` part of the loop. It's like if you have a 10 element array, it begins at 0 and the last element is technically 9 but the size is 10. So when you loop it, you typically go from 0 to `< 10`. That's the same thing with "end()".

    So accumulate just takes the beginning and end of the range, sums it all up and then returns it to you. std::vector handles all the things like allocation of memory and whatnot. You can also use std::array with std::accumulate as well! This is where you can really start to see the fundamental power in C++ of iterators and algorithms implemented in terms of iterators.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 01-10-2016, 01:23 AM
  2. Replies: 3
    Last Post: 03-26-2012, 10:50 AM
  3. How to return an array from a function
    By millsy5 in forum C Programming
    Replies: 3
    Last Post: 01-26-2010, 11:17 AM
  4. Program to calculate change return.
    By OrAnGeWorX in forum C Programming
    Replies: 15
    Last Post: 11-17-2008, 09:49 AM
  5. function return array
    By dukysta in forum C Programming
    Replies: 4
    Last Post: 06-10-2007, 09:49 AM

Tags for this Thread