For Loop
Sometimes we need to deal with repetitive work. At this time, using cyclic statements is a good method. Let's take a look at this exercise;
1. Start Geany
1) Click "Application-programming-Geany" in the menu to start Geany and create a c ++ source program;
2) Click the "file-save as" command in the menu and save the file to your folder with "for" as the file name;
2. Enter the program code.
1) First, let's look at an integer code that shows up to 10;
For (int I = 0; I <10; I ++)
{
Cout <I <"";
}
2) There are three for statement brackets. The first sentence is to define a loop variable. The initial value is 0, and the middle sentence is a loop condition. When I is less than 10, execute the loop statement. The following content must be enclosed in braces,
The next sentence is the step size, I ++ is I = I + 1, plus one increment operation;
3) Save, compile, generate, and run the command, and display 10 records ranging from 0 to 9;
4) Because I starts from 0 and must be smaller than 10, it cannot be equal to, so the two ends are 0 and 9;
5) Okay. Enter another accumulate program, from 1 to 100 (1 + 2 + 3 +... + 100 );
Int sum = 0;
For (int I = 1; I <= 100; I ++)
{
Sum = sum + I;
}
Cout <"sum =" <sum;
6) This I <= 100, which can be added to 100. sum is the variable for storing and adding an I to it each time,
Sum = sum + I, this sentence is cumulative, Like stacked wooden boxes;
7) Save, translate, generate, and run, and the accumulated results are displayed;
# Include <iostream>
Using namespace std;
Int main (int argc, char ** argv)
{
For (int I = 0; I <10; I ++)
{
Cout <I <"";
}
Cout <endl;
Int sum = 0;
For (int I = 1; I <= 100; I ++)
{
Sum = sum + I;
}
Cout <"sum =" <sum;
Return 0;
}