0

Need to determine the number of pozitive numbers until the first negative number

When testing this program, I usually use the values to be in this order: 1, 2, 3, 4, -5, 6, 7, 8. If I use only one negative number when executing the program, it does what I want to, but if I use more negative numbers, for example the order: 1, 2, -3, 4, -5, 6, 7, -8; It will show multiple times "s =...", which I don't want to. I tried using the while loop for this, but I couldn't get it to work. Any help is appreciated. This is my code #include <iostream> using namespace std; int main() { int i, j, k, s=0; int arr[2][2][2]; for(i=0;i<2;i++) { for(j=0;j<2;j++) { for(k=0;k<2;k++) { cout<<"Value on ["<<i<<"]["<<j<<"]["<<k<<"] "; cin>>arr[i][j][k]; } } } for(i=0;i<2;i++) { for(j=0;j<2;j++) { for(k=0;k<2;k++) { if(arr[i][j][k]>=0) { s=s+1; } else { cout<<"s = "<<s; } } } } return 0; }

25th Mar 2020, 4:59 PM
Zadnipro Ion
1 Antwort
+ 1
You could simply add a return 0; after printing 's', that way the program ends after the first negative number has been found. Otherwise a boolean flag can help you to control the loop.
25th Mar 2020, 6:15 PM
Shadow
Shadow - avatar