Java series tutorial day06 -- loop statement

Posted by DeepakJ on Fri, 29 Oct 2021 07:17:25 +0200

day06 -- loop statement

Outline:

1,Cyclic structure
2,while loop
3,do-while loop
4,for loop
5,break sentence
6,continue sentence
7,loop nesting 
8,task

Add Qianqian teacher vx to get the latest information    

 

1, Cyclic structure

1.1 concept

If the conditions are met, some code will be executed repeatedly. The condition doesn't hold. The loop ends. 0-n Times.

1.2 why is the cycle used

Some code may need to be executed many times during development. If it is used CV Dafa, CV Soldiers, treat the symptoms rather than the root causes. The following problems occur
1,The code is too bloated!
2,Code reading is very poor!
3,Code maintenance is extremely poor!

Components of the cycle

1. Initialization part: initial assignment of cyclic variables.
2. Cycle condition part: judge whether the cycle variable meets the cycle condition.
3. Loop body part: the specific code to be executed in the loop.
4. Update loop variable section: modify the value of loop variable.

2, Circular statement

2.1. while cycle

Syntax result of while loop:

while( Cycle condition judgment ){
  //Circulatory body
  //(changes in variables in the loop)
}
/*
Execution process:
  First, judge the value of the loop condition in the parentheses after while: Boolean --- > true, false
  If it is true, it means that the loop condition is true, execute the contents in {}, and then judge the condition
  If false, it means that the loop condition is not true, and the loop ends
*/
/*
matters needing attention:
  1,Learn circular process reasoning and avoid dead cycle
  2,If an endless loop occurs, ctrl+c terminates the program
*/
//The characteristics of while loop: judge the conditions first, and then execute the code.

Flow chart of while loop:

Example code:

class Test2While 
{
  public static void main(String[] args) 
  {
    
    /*
    while( boolean (expression of type){
      
    }
​
    Example:
    while( Alive){
      Heart beat
    }
    */
​
    //Use the while loop to print helloworld 100 times
​
    //Initialize a variable indicating the number of times helloworld is printed
    int i = 1; //1,2,3....100
​
    while( i <= 100 ){
      System.out.println("Hello World!");
      //i++;
      ++i;
​
    }
​
    System.out.println(i);
​
    
  }
}
​

Classroom exercises:

public class Test3While 
{
  public static void main(String[] args) 
  {
    //Class exercise: print 10-1 numbers using the while loop.
​
    int i = 10;
    while(i > 0){
      System.out.println(i);
      i--;
    }
    System.out.println("mian..over...");
    /*
    System.out.println(10);
    System.out.println(9);
    System.out.println(8);
    System.out.println(7);
    ...
    System.out.println(1);
    */
​
  }
}
​


2.2. Do while cycle

Syntax structure of do while loop:

do{
  //Circulatory body
  //(changes in cyclic variables)
}while( Cycle condition );
/*
Execution process:
  First execute the contents between {} after do, and then judge the loop conditions in while.
  If the condition is true, the loop continues.
  If the condition is false, the loop terminates!
*/

Execution flow chart of do while

Example code:

public class Test5DoWhile 
{
  public static void main(String[] args) 
  {
    /*
    do{
      //Circulatory body
      //(Cyclic variable change)
    }while( Cyclic conditions);
    */
    //Use the do while loop to print the number 1-10
    
    int i = 1;
​
    do{
      //Circulatory body
      System.out.println(i);
      //(cyclic variable change)
      i++;
    }while( i <= 10 );
  
    /*
    System.out.println(1);
    System.out.println(2);
    System.out.println(3);
    //...
    System.out.println(10);
    */
​
    System.out.println("i--->" + i);
  }
}
​

Compare while and do while loops

while Loop, first judge the conditions of the loop, and then execute the loop body according to the conditions.
do-while Loop, first execute the loop body, and then judge the condition. In a word: execute first, then judge.


2.3 for cycle

Syntax structure of for loop:

for(Expression 1:Initialization of loop variables ; Expression 2:Cyclic conditions ; Expression 3: variation of loop variable ){
    //Circulatory body;
}
/*
Execution process:
Execute expression 1 first: only once. Used to initialize loop variables.
Then execute expression 2: judgment condition of loop: Boolean -- > true, false
 If true, execute the loop body;
Then execute expression 3: change of variable
 Then judge whether the condition is true. If it is true, continue
 Otherwise, if the condition does not hold, the whole cycle will be ended
*/
/*
for Advantages of circulation
  1,for The syntax of the loop is very clear.
  2,for Cycle, it is convenient to calculate the number of cycles.
*/

for execution process

Example code:

class Test7For 
{
  public static void main(String[] args) 
  {
    /*
    for(Expression 1: initialization of loop variable; expression 2: condition of loop; expression 3: change of loop variable){
      //Circulatory body;
    }
    */
​
    //Print "porridge" 10 times
    
    for(int i = 1 ; i <= 10 ; i++ ){
      //Circulatory body;
      System.out.println("Drink porridge..." + i);//i:1,2,3...10
    }
    
    
    //System.out.println(i); / / i cannot be printed here because i is defined in the for loop and exceeds the scope.
​
​
    System.out.println("Hello World!");
  }
}
​

Classroom exercises:

public class Test8For 
{
  public static void main(String[] args) 
  {
    //Class exercise: use the for loop to sum 1-10
    /*
    Analysis process:
      sum = 0;
      sum += 1;//+1
      sum += 2;//+1 +2
      sum += 3;//+1 +2 +3
      ...
      sum += 10;//+1 +2 +3....+10
    */
    int sum = 0;//Define the variable sum to represent the sum of 1-10. The initial value of this result is 0
    for(int i = 1; i<= 10; i++){
      sum += i;//i:1,2,3...10
    }
    System.out.println(sum);
  }
}
​

Special form of for loop: understanding the content of

1,If expression 2 is omitted, it indicates that the loop is always true.
      The cycle condition defaults to true--->establish
​
2,Expression 3: it was originally executed after the loop body.
      But not very recommended
​
3,If expressions 1 and 3 are omitted, only expression 2 remains-->amount to
      while(Cycle condition){
        
      }
​
4,If expression 1,2,3 Omit: for(;;){}--->amount to
      while(true){
      
      }

Example code:

public class Test9For 
{
  public static void main(String[] args) 
  {
    /*
    Standard for loop
    for(Expression 1; expression 2; expression 3;){
      Circulatory body;
      
    }
​
​
    for Special forms of circulation: Understanding
​
    1,If expression 2 is omitted, it indicates that the loop is always true.
      By default, the loop condition is true --- > true
​
    2,Expression 3: it was originally executed after the loop body.
      But not very recommended
​
    3,If expressions 1 and 3 are omitted, only expression 2 -- > is equivalent to
      while(Cycle conditions){
        
      }
​
    4,If expressions 1, 2 and 3 are omitted: for (;;) {} --- > is equivalent to
      while(true){
      
      }
    */
    
    for(int i = 1;i <= 10 ;i++){
      System.out.println(i);
      
    }
    
  }
}
​


2.4 comparison of several cycles

1,For the same problem, the three cycles can replace each other.
2,When the number of cycles is determined, it is preferred for The number of cycles is not fixed while,do-while Cycle.
3,To prevent infinite loops--->Dead cycle


3, Circular flow control statement

3.1. break statement

break keyword

break: Word meaning: break, break, destroy
 Usage 1: switch-case In the statement, break Used to prevent switch pierce through.
Usage 2: Circular statement: while,do-while,for. Forces the end of a loop statement, whether or not the loop condition is met.

Example code:

class Test10Break 
{
  public static void main(String[] args) 
  {
    /*
    Cycle stop: if the cycle condition is not established, the cycle stops.
    break Statement: control loop structure.
      break Usage: Meaning: break, break,
        Usage 1: in switch case statement. Used to end case branch and switch statement.
        Usage 2: for loop statements, once the break statement is executed in a loop, the loop will completely end
          Whether the cycle conditions are met or not.
    */
    for(int i= 1;i <= 10;i++){
      if( i == 5){
        break;//Forced end loop.
      }
      System.out.println(i);
    }
​
​
    System.out.println("main..over...");
  }
}
​


3.2. continue statement

continue keyword

continue: Meaning: continue
 It can only be used in the loop and is specially used to control the loop.
Usage: end the current loop, and the loop will continue to execute next time.
Note: continue Big pit,
    stay while,do-while Use in circulation, pay attention to continue Keyword and the position of the change of loop variables. Prevent the occurrence of dead loop.
    for There is no such concern in the cycle.

Example code:

public class Test2Continue 
{
  public static void main(String[] args) 
  {
    /*
    continue: The current cycle has ended. The cycle will continue next time.
    */
    for(int i = 1;i<= 10;i++){
      if( i == 5){
        continue;//Word meaning: continue, end the current cycle and continue next time.
      }
      System.out.println(i);
    }
    System.out.println("main...over...");
​
    int j = 0;
    while(j < 10){
​
      if( j == 5){
        continue;
      }
      
      j++;
​
      System.out.println("j-->"+j);
    }
​
    System.out.println("main...over........");
  }
}
​


4, Loop nesting

What is multiple cycles?

Multiple loops refer to the nesting of loops.
Features: the outer loop is executed once. The memory loop should be executed once completely.

Guard against arrogance and impatience: the amount of code.

Example code:

public class Test3Loop 
{
  public static void main(String[] args) 
  {
    
    for(int i = 1;i <= 5;i++){//5 times, i:1,2,3,4,5, control the number of rows
​
      for(int j = 1;j<= 5;j++){//Number of control *
        System.out.print("*");
      }
​
      System.out.println();
    }
    
    
    
  }
}
/*
*****
*****
*****
*****
*****
*/
​

Class exercise: printing multiplication tables

class Loop2 
{
  public static void main(String[] args) 
  {
    /*
    Print 9 * 9 multiplication table
    1*1=1
    2*1=2 2*2 =4
    3*1=3 3*2=6 3*3=9
    ...
    9*1=9 9*2=18 9*3=27 9*4=36...9*9=81
​
    analysis:
​
    Print
      i * j
​
    i = 1
      j = 1
    i = 2
      j = 1,2
    i = 3
      j = 1,2,3
    i = 4
      j = 1,2,3,4
    ..
    i = 9
      j = 1,2,3,4,5,6,7,8,9
​
​
    */
​
    for(int i = 1;i < 10;i++){
      for(int j = 1;j<=i;j++){
        System.out.print(j+"*"+i+"="+i*j+"\t");
      }
      System.out.println();
    }
    
  }
}
​


5, Recycling summary

1,Learn to find out the law of operation in the code and complete the code implementation of the loop.
    Arrays, collections, algorithms...
2,Always remember: the pit in the cycle
    Dead cycle, while,do-while
    continue keyword, while,do-while
3,Learn the value reasoning process of cyclic variables:
    The initial value, end value, number of cycles, and how the variable changes(Variable step size)
4,Learn to use loop nesting
    Point by point analysis, reasoning
    Each layer of loop, each variable is meaningful..


extend

Several printing methods

System.out.println();
1.println();//Line wrap after printing: print+line
2.print();//Just print without line breaks
3.printf(" placeholder  \n",Variable of type);//Format print: print+format
    %d,Integer placeholder
    %s,String placeholder
    %f,Floating point placeholder
        %.2f,%.3f
    %c,Character placeholder
​

Example code:

class Test4Print 
{
  public static void main(String[] args) 
  {
    /*
    Print: System.out.xxxx()
    1,println();print + line ,Wrap after printing
​
    2,print();Just print, no line breaks
​
    3,Extended content:
      printf();print+format ,formatted print 
    */
​
    System.out.println("Hello World!");//print + line, wrap after printing
    System.out.println("hahahahah");
    System.out.println();//Just line feed
    System.out.println("Wang Ergou");
    System.out.print("Li Xiaohua");
    System.out.print("Baigujing");
​
    System.out.println();
​
    String name = "Prettyy ";
    int age = 100;
    double score = 88.7;
​
​
    System.out.printf("full name:%s,Age:%d Years old, score:%.2f\n",name,age,score);//Placeholder, using a symbol, occupies the place
    System.out.println("main..over..");
  }
}
​

6, Homework

1. "A hundred dollars for a hundred chickens" is a famous mathematical problem in ancient China. Title Description: one Rooster for 5 Wen, one hen for 3 Wen, three chicks for 1 Wen, and 100 Wen just buy 100 chickens. How do you buy them?

2. Find the number of daffodils. The so-called daffodil number refers to a three digit number, and the cube sum of each digit (the cube of 100 digits + the cube of 10 digits + the cube of 10 digits) is just the number itself. For example, 153 1 ^ 3 + 5 ^ 3 + 3 ^ 3 is exactly 153. So 153 is a daffodil number.

3. Print all primes in 2-100. (prime numbers, also known as prime numbers, are numbers that can only be divided by 1 and itself, such as 3, 7, 11, 13, etc.)

4. Print diamond
 

Welfare at the end of the article
You can add teachers vx to get the latest information

  Don't forget to scan the code and get the [Java HD roadmap] and [full set of learning videos and supporting materials]

 

Topics: Java JavaEE Back-end