I am new to c++ and i am having issues formatting code to output the number of even and odd integers in a randomized array. I have the code for the randomized array I just cant figure out how to add the even and odd part of it. I have a feeling I am just doing something obvious and dumb.
I get that you don't know how to update two values. There are three ways.
(i) Global variables (or static variables)
(ii) Passing by reference (or pointer)
(iii) Returning a structure (or container)
Like nuderobmonkey said you can make even_count and odd_count global and then it would work. But it's better to use local variables unless you simply can't use them.
But my suggestion would be to pass two variables by references for odd_count and even_count.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void CountingEvenOdd(int arr[], int arr_size, int& odd_count, int& even_count)
{
even_count = 0;
odd_count = 0;
for (int i = 0; i < arr_size; i++)
{
if (arr[i] & 1 == 1)
odd_count++;
else
even_count++;
}
}
So how would I identify arr? Arr is not part of the random array, but is part of the even odd part. Also, how would I identify CountingEvenOdd on line 28? Sorry, its a bit confusing to me.
void foo (int x)
{
cout << x; //x is an alias of sorts for z in this tiny example.
}
int main()
{
int z = 12;
foo(z); //z becomes renamed to x in the function.
}
arr does not exist in main. it is the parameter in your function.
in terms of my example, you are trying to do this:
int main()
{
int z = 12;
foo(z); //z becomes renamed to x in the function.
cout << x; //nope, there is no x in main, nowhere, can't find it, error!
}
you need to call CountingEvenOdd with the variable that you DO have in main, which seems to be num_arr.
c++ is tightly scoped, which means that a variable in one scope (for now, think of scope as {} pairs, you can extend this definition later to be more complete) cannot be seen in another scope. There is a global scope (everything can see it) but that is highly recommended to never use for variables.
I should just count the odd numbers (for example) and make it the return value of the function. The count of even numbers is just the array size n minus the count of odds.
Come to think of it, your totalling function would be more natural returning the sum as a double than as a void function.
For fun, since it's how I think numerical arrays ought to work:
By the way total is initialized in the main function so that part is correct. Although it would make sense to also initialize t with 0 in the function or rather bother initializing only in the function.