Looping: do-while Loop
The do-while
loops function similar to while
loops but with a subtle difference - the do-while
loop is execute at least once irrespective of the condition, and then the condition is checked. It is mostly used when the number of iterations is not known, but we need to execute the loop at least once.
The loop begins with the do
keyword, followed by a block of code to be executed, and then the while
condition is evaluated. If it is true, the loop is repeated, else it stops.
1int portfolio = 1;
2do {
3 cout << "Analysis on stock portfolio number " << portfolio << " completed.\n";
4 portfolio++;
5} while (portfolio <= 5);
This above code ensures that we at least analyze one portfolio. Then, if we have more than one portfolio, the loop will keep analyzing the portfolios until there are none left.
In the realm of AI finance, this is a common need - we often have tasks that we need to execute at least once, and then continue executing if a certain condition is met. In our example, we ensured we completed at least one portfolio analysis, and if there were more portfolios to analyze, we continued doing so.
xxxxxxxxxx
using namespace std;
int main() {
int portfolio = 1;
do {
cout << "Analysis on stock portfolio number " << portfolio << " completed.\n";
portfolio++;
} while (portfolio <= 5);
return 0;
}