This article explains the differences between for, while, and do while in Java through examples. The specific details are as follows:
The first type: for loop
The format of the loop structure for statement:
for(initialization expression; conditional expression; operation expression after loop) { loop body; }eg:
class Dome_For2{public static void main(String[] args) {//System.out.println("Hello World!");//Find the sum of even numbers of 1-10 int sum = 0;for (int i = 1;i<=10 ; i++ ) {if (i%2 ==0) { //Judgement statement sum +=i; //Sum}System.out.println(sum);}} The output structure is 30
The second while statement
The format of the loop structure while statement:
Initialization statement;
while(judgment conditional statement) { loop body statement; control conditional statement; }eg:
class Demo_While {public static void main(String[] args) {//Find the sum of 1-100 int sum = 0; //Define the initial sum to 0int i = 1; //Define the first number to start sum while (i <= 100) { //Judge conditional statement sum += i; //sum = sum + i;i++; //Let the variable i increase itself}System.out.println("sum = " + sum);}} The output result is: sum = 5050
The third do....while statement
The format of the loop structure do...while statement:
Initialization statement;
do { loop body statement; control conditional statement; }while(judgment conditional statement);eg:
class Demo1_DoWhile {public static void main(String[] args) {//Find the sum of 1-100 int sum = 0; //Define the variable sum, which is used to store the sum of the value int i = 1; //Define the variable ido { // do is the stem//System.out.println("i = " + i); //Loop body statement sum +=i;i++;}while (i <= 100); //Judge the conditional statement System.out.println("sum = "+sum); //Output result}} Output result: sum = 5050
Summary: The difference between three loop statements:
1.do...while loop executes the loop body at least once.
2. For, while loop must first determine whether the condition is true, and then decide whether to execute the loop body statement.
The above is an introduction to the differences between for, while, and do while in Java introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!