The Do...while loop is somewhat similar to the while loop syntax, but the execution process is quite different.
Grammar:
Execution process:
<1>, perform the cycle operation first, and then determine if the loop condition is true
<2>, if the conditions are established, continue to implement < 1 >, < 2, until the cycle conditions are not established
Features: first execution, after judgment
Thus, the Do...while statement guarantees that the loop is executed at least once !
For example, still output 1000 times "I adore class net", using Do...while implementation code:
Task
Light said not practice is "false bashi", let us do a practice test it!
Implementation function: Calculates the sum of even numbers within 50 (including 50)
Implementation ideas: First define a variable sum, to hold all the even numbers and then define a variable num represents an even number between 1--50, the value starts at 2, each time the loop executes, the value of NUM is accumulated in the variable sum, and the NUM value is added 2 (even, you know ha ~ ~), only The value of num must be repeated within 1--50 to execute the loop
Please complete the 10th and 14 lines in the compiler and run the result as follows:
1 Public classHelloWorld {2 Public Static voidMain (string[] args) {3 4 intsum = 0;//Save 1-50 even-numbered and5 6 intnum = 2;//represents an even number between 1-507 8 Do {9 //Implementing Cumulative SummationTen One Anum = num + 2;//the value is added 2 for each execution once to determine the next cyclic condition - -} while( );//repeat loop when value is met between 1-50 the -System.out.println ("The sum of even numbers within 50 is:" +sum); - } -}
1 Public classHelloWorld {2 Public Static voidMain (string[] args) {3 4 intsum = 0;//Save 1-50 even-numbered and5 6 intnum = 2;//represents an even number between 1-507 8 Do {9 //Implementing Cumulative SummationTenSum + =num; One Anum = num + 2;//the value is added 2 for each execution once to determine the next cyclic condition - -} while(Num <= 50);//repeat loop when value is met between 1-50 the -System.out.println ("The sum of even numbers within 50 is:" +sum); - } -}
Mu Class Network-android engineer first form the do...while of -4-8 Java Loop statement