Computing the average of positive numbers with arrays

why cant i see any output on this code?

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
28
29
30
#include <iostream>
using namespace std;
double average(int a[], int n);
int main(void)
{
int a[5] = {2, 0, -4, -5, 20};
double r = average(a, 5);
if (r == -1) cout << "The array has no positive integers" <<
endl;
else cout << "The average of positive integers in the array is "
<< r << endl;
return 0;
}
double average(int a[], int n)
{
int sum = 0;
int i = 0;
int count = 0;
while(true) {
if (a[i] > 0) {
sum += a[i];
count++;
}
else continue;
i++;
if (i == n) break;
}
if (count > 0) return sum/count;
return -1;
}
Last edited on
If the program just closes, it's because maybe you're not blocking the program at the end (It does everything you tell him: Display text and end the function, but once the function ends it closes itself, it doesn't wait for anything unless you tell him!). You should put a getch() or whatever that function was, before the "return 0" in your main() function.
Because the while loop never ever ends.
Oh, yeah, you must remove the "else continue" part in the loop, or it will block once it finds a negative number, haven't noticed. gj Moschops.
Topic archived. No new replies allowed.