I can't find the bug...

So I started experimenting with arrays and I tried to make a program that sums everything until you enter a negative value.

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>

using namespace std;

int getal[128];
int i;
int a = 0;
int b;

int main ()
{
    cout<<"Dit programma telt alle getallen op die je ingeeft.\nOm het te stoppen geef een negatief getal in.\n";
    for (;;)
    { if (cin>> i>0)
    {
                i = getal [a];

        b = b + getal[a];

        a++;
    }
      else cout<<"de som is" <<b;
    }


    return 0;
}


However, when I enter -1 for example, he does nothing.

Thanks in advance,

Xander
Last edited on
There are a couple of things here that might be problematic. What does for (;;) do? If you want to do an infinite loop, it would be better to to:

1
2
while(1) {
}


Also there is a problem in your if-statement. In order for it to work the way you want, you would have to write:
1
2
if ((cin >> i) > 0) {
}


But I think it would be better to take the users input before doing the if-statement. Also, shouldn't it be getal[a] = i;? Here is my suggestion for your if statement:

1
2
3
4
5
6
cin >> i;
if (i > 0) {
	getal[a] = i;
	b += getal[a];
	a++;
}


Another thing is that your loop won't stop - it really is an infinite loop. I would put in some conditions to prevent accessing over the 128th element of your array since that could cause some errors and whatnot.
Last edited on
Well, at first I had

for (; i>0 ; a++)

But it didn't work either...
I found a solution!

I've heard however, I should avoid goto loop whenever possible. Is there an alternative here?

EDIT: Managed to exclude the goto loop!

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
#include <iostream>

using namespace std;

int getal[128];
int i;
int a = 0;
int b;

int main ()
{
    cout<<"Dit programma telt alle getallen op die je ingeeft.\nOm het te stoppen geef een negatief getal in.\n";


    while (true) {
    cin>> i;
    if ( i > 0 ) {
	getal[a] = i;
	b += getal[a];
    }
    else {

    cout<<"de som is " <<b;
    }
    }

    return 0;
}
Last edited on
Don't use global variables without a good reason (there is none in this case).
An expression such as (cin >> i) > 0 won't do what you expect, because (cin >> i) returns the cin object, not i.
A possible version is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main ()
{
    cout << "Dit programma telt alle getallen op die je ingeeft.\nOm het te stoppen geef een negatief getal in.\n";
    int som=0;
    for (;;)
    {
      int num;
      cin >> num;
      if (num<0)break;
      som+=num;
    }
    cout << "de som is " << som;
}
I've heard however, I should avoid goto loop whenever possible. Is there an alternative here?

Just move cin >> i into the loop?
I got it! Thanks for your help all!
Topic archived. No new replies allowed.