Day14 (loop structure, while loop, do...while loop)

Loop structure

while loop

The structure is:

while(布尔表达式){
    
    //循环内容}
  • As long as the Boolean expression is true, the loop will continue to execute.

  • In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop.

  • A small number of cases need to be executed in a loop, such as server request response monitoring.

  • If the loop condition is always true, it will cause an infinite loop (endless loop). In our normal business programming, we should try to avoid infinite loops. It will affect the performance of the program or cause the program to freeze and crash.

  • Calculate 1+2+3…+100:

//输出1加到100:
public class A0117 {
    
    
    public static void main(String[] args) {
    
    
        //简略的方式:
        int i = 1;
        int sum = 0;
        while(i<=100){
    
    sum=sum+i;i++;}
        System.out.println(sum);
         //自己写的比较麻烦的代码:
        int a = 0;
        int b = 1;
        int c = 1;
        int e = 1;
        while(c<=100){
    
    
            c++;e=b++;a=a+e;
        }
        System.out.println(a);

do...while loop

  • The do...while loop is similar to the while loop, except that the do...while loop will be executed at least once.

  • The difference between while and do-while:

    1. While judges first and then executes, do...while executes first and then judges
    2. do...while always guarantees that the loop body will be executed at least once! This is their main difference.
  • grammar:

do{
    
    }while();
public class A0117a {
    
    
    public static void main(String[] args) {
    
    
        int a = 1;
        int b = 0;
        do {
    
    b=a+b;a++;//先执行后判断
        }while(a>5);
        System.out.println(b);
run:
1

Guess you like

Origin blog.csdn.net/SuperrWatermelon/article/details/112727573