Dewang Gupta - 3 months ago 15
C++ Question

# How do I run the q loop (INCREMENT Q)?

The q loop doesn't increment. If remove break it becomes an infinite loop. It just doesn't work with q. The k loop works fine. I would be really helpful if you can also explain why is it happening. Please help !!

``````#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace::std;

int main() {

string input;
getline(cin, input) ;
vector<char> myVector(input.begin(), input.end());
vector<char> myVector2(input.begin(), input.end());
sort(myVector2.begin(), myVector2.end());

if(myVector2 == myVector){
cout << "rank :1";
}

else{
int i;
for (i = 0; i < myVector2.size(); i++){
cout << myVector2[i];
}

cout << endl;

int q = 0, k = 0, value = 1, w = 1;
while(q < myVector.size()){
while(k < myVector.size()){
while(myVector2[k] != myVector[q]){
while(w < myVector2.size()){
value = value * w ;
w++;
}
k++;
}

cout << value*k;
cout << endl;

myVector2.erase(myVector2.begin()+k);
for(int j = 0; j< myVector2.size(); j++){
cout << myVector2[j];
}
break;
}
q++;
break;
}
}
return 0;
}
``````

There are 2 basic problems with your code:

Problem 1:

Why are you breaking the loop? The precise definition of break is :`The break statement ends execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the end of the statement, if any.`

You increment `q` and then you break the `while-loop`. Your code looks like this:

``````        while(q < myVector.size()){
//code here
q++;
break; // <------------ This will exit the while loop on the first iteration
}
``````

As a consequence, the outer loop is never executed.

Problem 2:

This loop will become an infinite loop if and only if `myVector2` and `myVector` have no common elements. In that case, k will be incremented infinite times because k is never checked for `k < myVector2.size?`

``````        while(myVector2[k] != myVector[q]){
while(w < myVector2.size()){
value = value * w ;
w++;
}
k++;
}
``````

To fix the issue change the `while-loop`

``````        while(myVector2[k] != myVector[q] && k < myVector2.size()){
while(w < myVector2.size()){
value = value * w ;
w++;
}
k++;
}
``````
Source (Stackoverflow)