Declaring an array inside a function

Jul 25, 2022 at 10:34pm
Hello, I am making a program that takes in an unspecified amount of integers inside an array and adds up the absolute values of the numbers. Look at the code to understand more.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cmath>
#include <windows.h>

using namespace std;

int getAbsSum(int nums[]){
    int sum = 0;
    for(int i = 0; i <= (sizeof(nums) / sizeof(int)); i++){
        if(nums[i] < 0){
            nums[i] = 0 - nums[i];
            sum += nums[i];
        } else {
            sum += nums[i];
        }
    }
    return sum;
}

int main()
{
    cout << getAbsSum([1, -4, -5, 6, 1]);

    return 0;
}


The error is
1
2
3
4
5
6

|22|error: expected identifier before numeric constant
|22|error: expected ']' before ',' token
|22|error: expected '{' before ',' token
|22|error: expected ')' before ']' token


Jul 25, 2022 at 11:04pm
You can't create an array "inline" like that in C/C++. Instead, try the following:
1
2
3
4
5
int main()
{
    int input[] = { 1, -4, -5, 6, 1 };
    cout << getAbsSum(input);
}


...or maybe have a look at:
https://cplusplus.com/reference/initializer_list/initializer_list/
Last edited on Jul 25, 2022 at 11:14pm
Jul 26, 2022 at 1:26am
Using std::vector as the dynamic array, initialized with initializer list syntax in the function call, range-based for loops and std::abs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>
#include <vector>

int getAbsSum(const std::vector<int>& nums)
{
   int sum {};

   for (const auto& i : nums)
   {
      sum += std::abs(i);
   }
   return sum;
}

int main()
{
   std::cout << getAbsSum({ 1, -4, -5, 6, 1 }) << '\n';
}
17
Jul 26, 2022 at 1:42am
It is possible to pass a regular array of "unknown size" into a function using a template, but the array has to be declared first:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cmath>

template <size_t N>
int getAbsSum(int (&nums)[N])
{
   int sum {};

   for (size_t i {}; i < N; ++i)
   {
      sum += std::abs(nums[i]);
   }
   return sum;
}

int main()
{
   int nums[] { 1, -4, -5, 6, 1 };

   std::cout << getAbsSum(nums) << '\n';
}

I'd stick with using C++ containers when possible instead of using regular arrays, they make "programming life" much easier.
Jul 26, 2022 at 5:01am
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <numeric> //for std::accumulate(),
using namespace std;

int main(){
	 auto abs_sum = [](int a, int b){ //lambda function	
	 	return b<0? a-b : a+b;
	};  
	 int ar[]={1,-2,3,4};
	 int size= sizeof(ar)/sizeof(ar[0]);
	 cout<< endl << accumulate(ar, ar+size, 0, abs_sum);
}
10
Jul 26, 2022 at 5:18am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

int getAbsSum(int nums[], int size){
    int sum = 0;

    for (int i = 0; i < size; ++i)
    {
        if (nums[i] >= 0)
        {
            sum += nums[i]; 
        }
        else
        {
            sum -= nums[i];
        }
    }

    return sum;
}

int main()
{
    int xs[] = {1, -4, -5, 6, 1};
    std::cout << getAbsSum(xs, (sizeof xs / sizeof *xs));

    return 0;
}
Last edited on Jul 26, 2022 at 5:19am
Jul 26, 2022 at 5:34am
@anup30
Try std::transform_reduce or std::inner_product instead:
1
2
std::transform_reduce(std::begin(xs), std::end(xs), 0, std::plus{}, 
  [](auto x){ return x < 0? -x: x; });
Last edited on Jul 26, 2022 at 5:41am
Jul 26, 2022 at 12:16pm
Thanks everyone.
It was solved.
i am kind of a beginner here.
so thank you very much
Jul 26, 2022 at 2:03pm
@mbozzi, can you write the full the program?(because i dont understand why you are using transform_reduce)
and my program works fine. do i even need to change it? while it has no bugs or malfunctions?
Jul 26, 2022 at 11:44pm
@mbozzi, can you write the full the program?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iterator>
#include <numeric>
#include <iostream>
#include <functional>

int main() 
{
  int const xs[] { 1, -4, -5, 6, 1 };
  int const sum = std::transform_reduce(std::begin(xs), std::end(xs), 0, std::plus{}, 
    [](auto x){ return x < 0? -x: x; });
  std::cout << sum << '\n';
}


Conceptually, each element is "transformed" by computing its absolute value. Then the list of absolute values is "reduced" into a single value by adding them together.
My program works fine. Do i even need to change it? while it has no bugs or malfunctions?
Of course not, yours is fine. But given the problem description
"Sum the absolute values of an array",
transform_reduce or inner_product is a better fit.

Jul 27, 2022 at 3:39am
did you run the program?
Jul 27, 2022 at 4:40am
anup30 wrote:
did you run the program?

Did you?

Runs for me using Visual Studio 2022 set to language standard C++20.

A hint, std::transform_reduce requires C++17 or better to work, std::inner_product is a bit more relaxed.

https://en.cppreference.com/w/cpp/algorithm/transform_reduce
https://en.cppreference.com/w/cpp/algorithm/inner_product
Jul 27, 2022 at 8:08am
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <valarray>
using namespace std;

int getAbsSum( const valarray<int> & V )
{
   return abs( V ).sum();
}

int main()
{
   cout << getAbsSum( { 1, -4, -5, 6, 1 } );
}
17 
Topic archived. No new replies allowed.