- C++ Game Development By Example
- Siddharth Shekar
- 128字
- 2021-06-24 14:26:11
Iteration
Iteration is the process of calling the same statement repeatedly. C++ has three iteration statements: the while, do...while, and for statements. Iteration is also commonly referred to as loops.
The while loop syntax looks like the following:
while (condition) statement;
Let's look at it in action:
#include <iostream> #include <conio.h> // Program prints out values to screen int main() { int a = 10; int n = 0; while (n < a) { std::cout << "value of n is: " << n << std::endl; n++; } _getch(); return 0; }
Here is the output of this code:

Here, the value of n is printed to the console until the condition is met.
The do while statement is almost the same as a while statement except, in this case, the statement is executed first and then the condition is tested. The syntax is as follows:
do statement
while (condition);
You can give it a go yourself and check the result.
The loop that is most commonly used in programming is the for loop. The syntax for this looks as follows:
for (initialization; continuing condition; update) statement;
The for loop is very self-contained. In while loops, we have to initialize n outside the while loop, but in the for loop, the initialization is done in the declaration of the for loop itself.
Here is the same example as the while loop but with the for loop:
#include <iostream> #include <conio.h> // Program prints out values to screen int main() { for (int n = 0; n < 10; n++) std::cout << "value of n is: " << n << std::endl; _getch(); return 0; }
The output is the same as the while loop but look how compact the code is compared to the while loop. Also the n is scoped locally to the for loop body.
We can also increment n by 2 instead of 1, as shown:
#include <iostream> #include <conio.h> // Program prints out values to screen int main() { for (int n = 0; n < 10; n+=2) std::cout << "value of n is: " << n << std::endl; _getch(); return 0; }
Here is the output of this code:

- Android NDK Game Development Cookbook
- 數字道路技術架構與建設指南
- 深入淺出SSD:固態存儲核心技術、原理與實戰
- Camtasia Studio 8:Advanced Editing and Publishing Techniques
- 電腦軟硬件維修從入門到精通
- Practical Machine Learning with R
- Creating Flat Design Websites
- 超大流量分布式系統架構解決方案:人人都是架構師2.0
- Source SDK Game Development Essentials
- 計算機組裝與維護(慕課版)
- 多媒體應用技術(第2版)
- 快·易·通:2天學會電腦組裝·系統安裝·日常維護與故障排除
- ActionScript Graphing Cookbook
- The Deep Learning Workshop
- Spring微服務實戰(第2版)