#include <iostream>
usingnamespace 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.
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.
#include <iostream>
usingnamespace 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;
}
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>
usingnamespace 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;
}