Fiona Fiona - 21 days ago 7
C++ Question

No errors but nothing happens when I run (C++)

Simple program that reads 6 numbers from keyboard and returns the sum of all the even numbers. But when I run this, it doesn't print anything and just quits.

What am I missing here? (I know vector would be better but I'm practicing for finals and this is an old finals question that specified using arrays).

#include <iostream>

using namespace std;

void readNumbers();
void sumOfEven(int arr[6]);

int main(){
void readNumbers();
return 0;
}

void readNumbers(){
int myArray[6];
cout << "Enter 6 numbers:" << endl;
for(int i = 0; i < 6; i++){
cin >> myArray[i];
}
sumOfEven(myArray);
}

void sumOfEven(int arr[6]){
int sum = 0;
for(int i = 0; i <= 6; i++){
if(arr[i] % 2 == 0)
sum = sum + arr[i];
}
cout << "Sum of even numbers: " << sum;
}

Answer

In main there is a function declaration instead of a function call

int main(){
    void readNumbers();
    ^^^^^^^^^^^^^^^^^
    return 0;
}

You should write

int main(){
    readNumbers();
    ^^^^^^^^^^^^^^
    return 0;
}

The second problem is that you use incorrect indices in the loop

for(int i = 0; i <= 6; i++){
               ^^^^^^^

There must be

for(int i = 0; i < 6; i++){
               ^^^^^
Comments