#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << endl;
++i;
}
}
Assignments like i = i + 1 donโt often appear in loops, because C++ provides a more concise way to add and subtract by one. Recall that, ++ is the increment operator; it has the same effect as i = i + 1. And -- is the decrement operator; it has the same effect as i = i - 1.
We introduced these โshortcut operatorsโ back in Sectionย 3.12. There, we said there is no reason you have to use them, but you should learn to recognize them as they are commonly used. Loops are the most important example of this. Programmers will almost always write i++ or ++i
In C++, there are some differences between i++ and ++i that can make the choice of which to use important. If you are using them as part of a larger expression, the placement of the ++ changes when the increment happens. If you are using ++ on more complex structures, the preincrment version - ++i - can be more efficient than the post increment version. When used on their own with integer variables it does not matter which you use. But it is not a bad habit to get used to writing ++i by default.
The super evil villian RePete wants to annoy the city by hacking into the cityโs helper robots and making them repeat everything they say 5 times. However, thereโs an error in his code and now the robots wonโt stop repeating! Can you find the error?