Why while loop is not terminating in this program??

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 "std_lib_facilities.h" // authors header file i am using

int main (){
    constexpr int MAX = 5;
    vector<int> monitor(MAX,1);
    vector<int> inputset(MAX);
    int number, j = 1,x, n = 0;
    while (n < inputset.size()){
        cin >> number; // reading five numbers
        inputset.push_back(number);
        n++;
    }
    for (int i = 0; i < inputset.size(); i++){
        for (int j = i+1; j < inputset.size();j++)
            if(inputset[i] == inputset[j])// calculating repeating number
                monitor[i]+=1;// number of times it appeared
            
    }
    for (int i = 0; i < monitor.size(); i++){
        if (j < monitor[i]){
            j = monitor[i];// calculating the number of times mode appeared
            x = i;//taking mode value into x
        }
        }
    cout << "THE MODE OF GIVEN NUMBERS IS: " << inputset[x] << " and is appeared " << j << " times ";
    return 0;
    
    
}
On line 6 you create a vector with 5 elements. Inside the loop you add new elements to the vector. Both n and the size of the vector increases by one for each iteration of the loop. This means n will always be 5 less than the size so the loop condition is never false.
I don't think it's that the while loop doesn't end, it's that it won't end for a while. Since you forcefully set your vector<int> inputset to size of 5, and your while loop calls on inputset.size(), n++ or even ++n won't get you to 5 in one loop.
@YFGHNG, you forget that inputset.size() is also increasing because he calls push_back.
Thanks friends..silly mistake..sorry to bother.
Topic archived. No new replies allowed.