Hi,
Could you please help point out the logic error in the following codes, & give a hint for fixing the error? This is an exercise for control loop and vectors, so I'm not allowed to use a function with an argument as a vector.
Thanks a lot.
Code:// Exercise 16 - Chapter 4 // Control statements, if statements & vectors #include "std_lib_facilities.h" int main() { int x = 0; unsigned int i = 0; unsigned int j = 0; vector<int> numbers; cout << "Enter a series of positive integers: "; while (cin>>x) { numbers.push_back(x); } cout << "You have entered: "; for (i=0; i<numbers.size(); ++i) cout << numbers[i] << ' '; sort(numbers.begin(), numbers.end()); cout << "\nIn ascending sorted order: "; for (i=0; i<numbers.size(); ++i) cout << numbers[i] << ' '; int prev_count = 0; int curr_count = 0; int mode = 0; for (i=0; i<numbers.size(); ++i) { // for each element of the vector "numbers" for (j=0; j<numbers.size(); ++j) { // compare it to all its other elements if (numbers[j]==numbers[i]) // if 2 elements equal, increment the count (curr_count) ++curr_count; } if (curr_count>prev_count) { // if the current count greater than previous count mode = numbers[i]; // the mode is set to equal that element of the vector prev_count = curr_count; // set previous count == current count & repeat above steps curr_count = 0; // set current count to zero after finishing the check on each of the elements } } cout << "The mode is " << mode << '\n'; }



LinkBack URL
About LinkBacks



