Reputation: 35
My while loop has become an infinite one inspite of using decrement operator. Could you please explain why is that so? Isn't it supposed to come out of the while loop once the condition becomes false?
# include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// Function to print the string
void printGrouped(string str)
{
int n = str.length();
// Initialize counts of all characters as 0
int count[MAX_CHAR] = {0};
for (int i = 0 ; i < n ; i++)
count[str[i]-'a']++;
for (int i = 0; i < n ; i++)
{
while (count[str[i]-'a']--)
cout << str[i];
}
}
// Driver code
int main()
{
string str = "applepp";
printGrouped(str);
return 0;
}
Upvotes: 1
Views: 144
Reputation: 114559
The problem is
while(count[str[i]-'a']--) { ... }
the reason is the expression
x--
decrements x
and returns the original value (before decrementing). Using a while condition like
while(x--) { ... }
quits the loop when x
goes from 1 to 0, but if you enter the while again then you've a problem because x
made it to -1 and it will not get back to zero by decrementing it.
-1 is a "true value" for a while test, so it will enter the loop and become -2, then loop again and become -3 and so on until you get an overflow and undefined behavior.
The loop should be probably written as
while(count[str[i]-'a']) {
count[str[i]-'a']--;
....
}
so that you decrement it ONLY if it's not already zero
Upvotes: 1
Reputation: 201
What I can see is that you have an expression in your while loop's "()" brackets. It's better to have a condition over there you should put this expression inside the loop and then you need to add a condition related to that expression in these brackets "()" let's suppose you wish to exit the loop when the expression's value is -1. I am not sure about the synatx, Just tried to demonstrate my logic in the code.
x= count[str[i]-'a']-1;
While(x!=-1)
{
cout << str[i];
x= count[str[i]-'a']-1;
}
Upvotes: 1