java process control 03- loop structure

java process control 03- loop structure

1, while loop

1.while is the most basic loop. Its structure is

while(Boolean expression){
    //Cyclic content
}

2. As long as the Boolean expression is true, the loop will continue to execute

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

4. In a few cases, the loop needs to be executed all the time, such as server request response listening, etc.

5. If the cycle condition is true all the time, it will cause infinite cycles (dead cycles). We should try to avoid dead cycles in our normal business. It will affect the program performance or cause the program to jam and crash

package struct;

public class WhileDemo01 {
    public static void main(String[] args) {
//        Output 1-100
        int i = 0;
        while (i < 100){
            i++;
            System.out.println(i);
        }
    }
}
package struct;

public class WhileDemo02 {
    public static void main(String[] args) {
//        Dead cycle in practice, try to avoid dead cycle
        while (true){
            //        Regularly check waiting for client connection, etc
        }

    }
}
package struct;

public class WhileDemo03 {
    public static void main(String[] args) {
//        Calculate 1 + 2 ++ one hundred
        int i = 0;
        int sum = 0;
        while (i <= 100) {
            sum = sum + i;
            i++;
        }
        System.out.println(sum);
    }
}

2, Do while... loop

1. For the while statement, if the conditions are not met, it cannot enter the loop. But sometimes we need to execute at least once even if the conditions are not met.

2.do... The while loop is similar to the while loop, except that do The while loop executes at least once.

do {
    //Code statement
}while(Boolean expression);

3.while and do The difference between while

while is judged before execution. do...while is execution before judgment.

do...while always ensures that the loop is executed at least once! This is their main difference.

package struct;

public class DoWhileDemo01 {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        do {
            sum = sum + i;
            i++;
        }while (i <= 100);
        System.out.println(sum);
    }
}
package struct;

public class DoWhileDemo02 {
    public static void main(String[] args) {
        int a = 0;
        while (a < 0) {
            System.out.println(a);//No output, no entry into this cycle
            a++;
        }
        System.out.println("==================");
        do {
            System.out.println(a);//Once
            a++;
        } while (a < 0);
    }
}

3, for loop

1. Although all loop structures can use while or do While, but java provides another statement: for loop, which makes some loop structures simpler.

2.for loop statement is a general structure that supports iteration. It is the most effective and flexible loop structure.

3. The number of times the for loop is executed is determined before execution. The syntax format is as follows:

for (initialization; Boolean expression; to update){
    //Code statement
}
package struct;

public class ForDemo01 {
    public static void main(String[] args) {
        int a = 1;//Initialization condition

        while (a <= 100){//Conditional judgment
            System.out.println(a);//Circulatory body
            a +=2;//iteration
        }
        System.out.println("while End of cycle!");
//        initialization; Condition judgment; iteration
        for (int i=1;i<=100;i++){
            System.out.println(i);
        }
        System.out.println("for End of cycle!");
    }
}

There are the following explanations for the for loop:

1. Perform the initialization step first. You can declare a type, but you can initialize one or more loop control variables or empty statements

2. Then, detect the value of Boolean expression. If true, the loop body is executed. If false, the loop terminates and starts executing the statement after the loop body.

3. After executing a cycle, update the cycle control variable (the iteration factor controls the increase or decrease of the cycle variable).

4. Check the Boolean expression again and execute the above process in a loop.

//Dead cycle
for (; ; ){
    
}

Exercise 1: calculate the sum of odd and even numbers between 0 and 100

package struct;

public class ForDemo02 {
    public static void main(String[] args) {
        int oddSum = 0;
        int enenSum = 0;

        for (int i = 0; i < 100; i++) {
            if (i % 2 != 0) {
                oddSum += i;
            } else {
                enenSum += i;
            }
        }
        System.out.println("Even sum" + oddSum);
        System.out.println("Odd sum" + enenSum);
    }
}

Exercise 2: use the while or for loop to output a book with 1-1000 divisible by 5, and output three numbers per line

package struct;

public class ForDemo03 {
    public static void main(String[] args) {
        for (int i = 0; i <= 1000; i++) {
            if (i % 5 == 0) {
                System.out.print(i + "\t");//nowrap 
            }
            if (i % (5 * 3) == 0) { //Line feed
                System.out.println();
                System.out.print("\n");
            }
        }
    }
}
package struct;

public class WhileDemo04 {
    public static void main(String[] args) {
        int i = 0;
        while (i <= 1000) {
            i++;
            if (i % 5 == 0) {
                System.out.print(i + "\t");
                if (i % 15 == 0) {
                    System.out.println();
                }
            }
        }
    }
}

Exercise 2: print the 99 multiplication table

package struct;

public class ForDemo04 {
    public static void main(String[] args) {
//        1. Print the first column first
//        2. Wrap the fixed 1 in another cycle
//        3. Remove duplicates, I < = J
//        4. Adjust style
        for (int j = 1; j <= 9; j++) {
            for (int i = 1; i <= j; i++) {
                System.out.print(i + "*" + j + "=" + (j * i) + "\t");
            }
            System.out.println();
        }
    }
}

Enhance the for loop (understand and focus on it later)

1. Java 5 introduces an enhanced for loop that is mainly used for arrays or collections.

2. The syntax format of Java enhanced for loop is as follows:

for(Declaration statements: expressions)
{
    //Code sentence
}

3. Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time.

4. Expression: the expression is the name of the array to be accessed or the method whose return value is array.

package struct;

public class ForDemo05 {
    public static void main(String[] args) {
        int[] number = {10, 20, 30, 40, 50};
        for (int i = 0; i < 5; i++) {
            System.out.println(number[i]);
        }
        System.out.println("=============");
        for (int x : number) {
            System.out.println(x);
        }
    }
}

Keywords: Java

Added by cahamilton on Sun, 06 Feb 2022 04:54:51 +0200