I am trying to write a for loop inside the while part of a do while loop. Is this possible? Dev-C++ keeps giving me errors saying i'm missing semicolons/parentheses/brackets and such in places that I already have them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
do
{
for (i=0 ; i < Numbers.size(); ++i)
{
if (Numbers[i]> Numbers[i+1])
{
std::swap(Numbers[i], Numbers[i+1]);
std::swap(Names[i], Names[i+1]);
}
}
}while( for( n = 0 ; n < Numbers.size() ; ++i)
{
Numbers[n]>Numbers[n+1];
}
);
And Numbers[] is a vector of int and Names[] is a vector of strings. (This is my method for sorting)
This doesn't make sense, anyway. The while portion is just a condition that determines whether or not the loop is to continue. It doesn't make sense to put another loop in it.
In the above syntax, <condition> can be anything that evaluates to a boolean value (true/false). It can really be anything, AS LONG AS IT EVALUATES TO A BOOLEAN VALUE. A FOR statement does NOT evaluate to a boolean value, and therefore is not appropriate for it to appear in place of <condition>.
Instead, you can place a function that returns a boolean value (among many other constructs, EXCEPT statements like the FOR statement :-) ):
1 2 3 4 5 6 7 8 9 10 11
bool MyBooleanFunction(sometype someParam)
{
...
}
...
do
{
...
} while (MyBooleanFunction(someArg)); // or while (!MyBooleanFunction(someArg))
If you lookup tutorials and help files on C++ about the FOR statement, you will notice that nowhere you'll find anything stating that the statement returns a boolean value, or any other value for that matter.
From what you describe, you want to sort corresponding arrays using the BubbleSort algorithm. This algorithm is well documented in many places. It should not be hard for you to find an example made in C++.
So I don't spoil your fun, I'll just give you a clue: The <condition> part of the do..while loop of yours need to signal when the array is already sorted. When is your array already sorted? The answer is: When all the values are ordered in ascending order. How can your program detect when this happens? When you run through your entire FOR loop and you do not perform any swaps. If there are no swaps, means that [i + 1] was always greater than [i].
Solution: Use a boolean control variable. Call it bSwapOcurred so its name is meaningful. Make sure you set that value to true everytime a swap is performed inside the FOR loop.
Finally, what would be the condition in the do..while loop? Figure this one out yourself. :-)
Returning a Boolean value means that it either returns true or false, is that correct? If so, that makes alot of sense, thanks for helping me understand! :)