loop doesn't stop even after using break;

So i want to make a programme that takes continuous input from user and stops when the user press 42.Then the numbers present before 42 will be continuously outputted to the screen.
Here is the 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
#include<iostream>
using std::endl;
using std::cin;
using std::cout;

int main()
{int ar[20];
    int no;
cin>>no;
for(int i=0;no!=42;i++){
ar[i]=no;
cin>>no;

}
for(int j=0;j<20;j++){
    cout<<ar[j]<<endl;

    if(ar[j]==42)
            break;

}
}



I used the concept of array and the first loop worked fine while inputting and the second loop stops before 42 like it should but prints garbage value till the loop ran.

I am a beginner so didn't understood the cause of problem as the programme ran fine.
Well the issue is that break is never called because that if statement within the second for loop is never called. This is because of how when the user inputs 42 in the first loop it will break because of the condition in the loop and thus never actually put that value into the array. Not only that, but I don't recommend to keep the loop going until the user inputs 42 because the loop could go past the array's index and cause undefined behavior. Also I don't recommend using magic numbers as your break key and arr size mainly since if you begin to use the value multiple times in the program you'll have to change each instance. Not only that, but it also makes it more readable.

Here is the fix.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using std::endl;
using std::cin;
using std::cout;

int main() {
    constexpr int inputBuff = 20;
    int key = 42;
    int ar[inputBuff];
    int no;
    for(int i = 0; i < inputBuff; i++){
        cin>>no;
        ar[i]=no;
        if (no == key) {
            break;
        }
    }
    for(int j = 0; j < inputBuff; j++){
        if(ar[j] == key)
            break;
        cout << ar[j] << '\n';
    }
}
thanks for the help rabster .i appreciate the quick response.i have now got it.
Topic archived. No new replies allowed.