C++ Programming: Loops (Lesson 4)

C++ has three kinds of loops: while, for, and do-while. Here is a program demonstrating while loops by displaying numbers from 0 to 9. #include using namespace std; int main() { int i=0; while (i<10) { cout << i <<"n"; i++; } } For loop behaves exactly like the while loop that we just saw: for (int i=0; i<10; i++) { cout << i <<"n"; } Do-while loops are special purpose and fairly rare. The condition is tested at the end of the loop instead of the beginning. A do-while loop is basically a reversed while loop. Here is an example that lets a user enter the password until it is correct: #include #include using namespace std; int main() { string password; do { cout <> password; }while (password != “foobar”); cout << "Welcome, you got hte password right n"; } Sometime you want to exit out of the loop early. C++ has just the keyword for you: break. A break statement will immediately terminate whatever loop you are in the middle of.
This material is from the textbook Jumping into C++ by Alex Allain. I strongly recommend this book if you are new to programming and want to learn more than what I described here.
Click for Lesson 3 Click for Lesson 5
This entry was posted in Programming and tagged , . Bookmark the permalink.