Dewang Gupta Dewang Gupta - 3 months ago 6
C++ Question

How do I print the sum outside the loop ? I think there's some mistake in deceleration of global and local variable

When I put the 6th last line (cout << "rank : " << sum + 1 << endl;) outside the loop it says that sum was not declared in this scope.
The code is right below :

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

using namespace::std;

int main() {

string input;
cout << "Don't enter repetitive alphabet word \n" << "Enter a word : ";
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{
for (int i = 0; i < myVector2.size(); i++){
//cout << myVector2[i];
}

cout << endl;

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

break;
}
sum = sum + temp;

myVector2.erase(myVector2.begin()+k);
/* for(int j = 0; j < myVector2.size(); j++){
cout << myVector2[j];
}*/

cout << "rank : " << sum + 1 << endl;
q++;
}

}
}


How do I print the 6th last line : cout << "rank : " << sum + 1 << endl;
outside the loop? And please also explain the reason

Answer

In C++ each time a curly braces is open, a new scope is created and when closed, it's destroyed. Each scope has access to other scopes as long as they are not destroyed.

Your sum is declared within a scope in the first while loop. So when the while loop is closed, the scope is destroyed, which results your declaration of sum to be nullified/destroyed.

You must declare sum before your loop and you probably want to initialize it.

int q = 0, value = 1, w = 1, sum = 0;
while( ... ) {
    ...
}
Comments