In this exercise, let's introduce another important loop statement in C #, for loops.
for (expression 1; expression 2; expression 3)
{
Loop body
}
Expression 1: The general assignment expression, assigns the initial value to the control variable;
Expression 2: Logical expression, loop control condition, Loop executes the statement in the loop body when the condition is true.
Expression 3: Usually an assignment expression that gives the control variable an increment or decrement.
This seems to be not quite abstract. With practical examples, you will be very easy to understand for loops.
You create a project. The solution name is Sloution18, the project name is Exercise18, and the project type is a console program. Click Program.cs. Add the code to the inside.
/span>
Simply explain the program.
1. Line 14th is the core of the For loop. Where I is the control variable. int i=0; Assigning the initial value to the control variable i;
2. The i<=10; is a cyclic control condition; When i<10, the statements in curly braces are executed;
3. i++ is the increment of the control variable. Add 1 each time.
4. The 17th line is to do 1 to 10 of the cumulative. is to calculate 1+2+3+4+ ... +10.
Run results
/span>
Practice
1. Read this code and annotate important statements
2. If the 14th line of code is changed to for (int i=0;i<=10;) What will be the result of running the program?
3. If the 14th line of code is changed to for (int i=0;; i++) What will be the result of running the program?
4. Modify the code so that the program outputs the value of I from 0 to 20 to the DOS window, and calculates the cumulative result from 0 to 20.
Loop execution for Loop in C #