Reprinted without permission
Copyright to Mr. Gao lei
Contact info:
Email: gaolei57521@gamil.com
QQ: 38929568
This series of blogs are only published at the following three addresses:
Http://kome2000.blog.51cto.com/
Http://38929568.qzone.qq.com/
Http://blog.csdn.net/kome2000
About loop Traversal
1. for Loop
Common Methods
- Int I;
- For (I = 0; I <N; I ++)
- {
- // Code for the operation
- }
The variables used for cyclic stepping are usually I, j, k, m, n... But letter variables. In terms of efficiency and readability, it is better to have a loop level lower than three layers.
For Loop end conditions, the first choice is less than. If you need other conditions such as <= N or> 0 to do the loop end conditions, you need to add comments to explain why you were doing this at the time!
1.1 layer-2 loops are also common, such as traversing a two-dimensional array
- Int array [row] [col]; // row is a constant of the number of rows, and col is a constant of the number of columns.
- Int I, j;
- For (I = 0; I <row; I ++)
- {
- For (j = 0; j <col; j ++)
- {
- // Array access format: array [I] [j],
- // Code for the operation
- }
- }
The inner loop must be the first dimension of the array, because we know that the array is a continuous memory space, and an array of any dimension can be rewritten to a one-dimensional array,
The first dimension of the array is a continuous memory address, so the computer can access the continuous address quickly,
In addition, processing the first dimension of the array is more intuitive and can be understood by those who read the code.
1.2 If the first dimension is relatively small, such as an array of 1000 coordinates
Can be defined
Int pos [1000] [2]; // The first dimension has only two values. If the subscript is 0, it indicates the X coordinate. If the small value is 1, it indicates the Y coordinate.
Such an array can be traversed through a layer-1 loop, which can reduce the number of times the CPU has been cross-cut.
For example
- For (I = 0; I <1000; I ++)
- {
- // Pos [I] [0];
- // Pos [I] [1]; // process the subscript 0. 1...
- // Code for the operation
- }
This article is from the "key code window" blog and will not be reprinted!