Nick
Nick

Reputation: 1056

Function that takes an array of integers as a parameter and returns the sum of odd numbers in the array

I keep getting a error: "Run-Time Check Failure #3 - The variable 'x' is being used without being initialized."

I thought I initialized it with all the numbers I put in the array?

#include <iostream>
using namespace std;

const int MAX = 10;

int odd(int sumOdd[])
{
int sum = 0;
for(int i = 0; i < MAX; i ++)
{
    if(sumOdd[i] % 2 != 0)
    sum+=sumOdd[i]; 
}
cout << "Sum of odd integers in the array: " << sum << endl;
return sum;

}

int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};

int returnArray(x[MAX]);

cout << "Sum of odd integers in the array" << endl;

system("pause");
return 0;
}

Upvotes: 0

Views: 4438

Answers (2)

David G
David G

Reputation: 96810

int returnArray(x[MAX]); // in main

should be

returnArray(x);

You've already declared the function as taking an array and returning an integer, so all you need to do is call the function with the array as the parameter.

Upvotes: 1

taocp
taocp

Reputation: 23644

try to change:

 int returnArray(x[MAX]);

to

 int sum =  returnArray(x);
 cout << "Sum of odd integers in the array" << sum << endl;

returnArray returns sum. You can either use a temporary variable to hold the return value and print it out or directly use the return value as follows:

cout << "Sum of odd integers in the array" << returnArray(x) << endl;

When you call a function, simply use the function name and feed it with parameters, you don't need return type anymore (int) in this case. You also directly use the array name x, not x[MAX].

Upvotes: 1

Related Questions