Loop structure: Sometimes we want a piece of code to be executed several times. But if you have to execute it several times, it's too much trouble to write it several times. At this time, we can easily implement the function of "several times a piece of code is executed" by using the loop structure.
for loop
Format:
For (expression a; expression b; expression c){
Statement group
}
Explanation: 1. Calculate the value of expression a first
Re-evaluate the value of expression b: 2. (1) If true, execute the statement group, and then calculate expression c. Then calculate the value of expression B and repeat 2.
(2) If it is false, exit the for loop and execute the following procedure.
Example 1: Output characters a~z
#include <iostream> #include <cstdio> using namespace std; int main() { int i; //Cyclic control variables for(i = 0;i < 26;++i){ cout << char('a' + i); } cout << endl; for(int i = 0;i < 26;++i){ printf("%c",'a' + i); } return 0; }
When the loop control variable is defined in expression 1, then this variable only works in the for loop. Don't worry about variable renaming.
Example 2: An alternate output sequence a~z
#include <iostream> #include <cstdio> using namespace std; int main() { int i =5; for(int i = 0;i < 26;i += 2){ //Cyclic control variables do not add only 1 at a time printf("%c",'a' + i); } cout << i; //Output i is 5 return 0; }
Expressions a and c in for loops can be several expressions connected by commas.
Example 3:
#include <iostream> #include <cstdio> using namespace std; int main() { for(int i = 15,j = 0;i > j;i -= 2,j += 3){ cout << i << "," << j << endl; } return 0; }
Example 4: Output of all factors of a number
#include <iostream> #include <cstdio> using namespace std; int main() { int n; scanf("%d",&n); for(int i = 1;i <= n;i++){ if(n % i == 0) cout << i <<endl; } return 0; }
Example 5: All the factors that output a number in reverse order
#include <iostream> #include <cstdio> using namespace std; int main() { int n; scanf("%d",&n); for(int i = n;i >= 1 ;i--){ if(n % i == 0) cout << i <<endl; } return 0; }