Java Fundamentals 05 Loop Structure

Like you who love programming!
Learn SpringBoot actual combat course https://edu.csdn.net/course/detail/31433
Learn SpringCloud introductory course https://edu.csdn.net/course/detail/31451


Preface

No matter how complicated the program is, it is composed of three basic structures: sequence structure, branch structure and loop structure. In this article, we will learn this loop structure. The content of this article includes: for\while\do-while loop, loop control break and continue, and Nested loops.

cycle

Galen’s E skill in LOL is to take a sword and make a circle. Assuming that a total of ten circles are needed, how does the program control him to perform repeated circle operations?
The answer is: to execute a piece of code repeatedly through a loop

Loops in Java are

  • for
  • while
  • do-while

Three elements of the cycle

  1. Conditions to stop the loop
  2. Initial quantity, initialization of loop variables
  3. Update of loop variables

for loop

Generally used for a fixed number of loops.
Syntax structure:

for(循环变量的初始化;循环的条件;循环变量的更新){
	循环的执行语句;
}

Implementation process:

  1. initialization
  2. Judge the loop condition, if it holds
  3. Execute loop statement
  4. Variable update
  5. Judge the loop condition
    ...
    Insert picture description here

Exercises:
1. The case of spinning

for(int i = 1;i <= 10;i++){
	System.out.println("盖伦转了" + i + "圈");
}

2. Output all odd numbers between 100 and 999.
3. Find the factorial of 5. 5! = 1 * 2 * 3 * 4 * 5
4. Find the sum of 1~100

while loop

The execution process of while loop is the same as for
Syntax:

循环变量的初始化
while(循环条件){
	循环的执行语句
	循环变量的更新
}

Exercise:
1. Complete with a while loop

int i = 1;
while(i <= 10){
	System.out.println("盖伦转了" + i + "圈");
	i++;
}

2. Use the while loop to complete, enter two numbers m and n, and find the sum of the numbers between m and n (assuming m <n)

do-while loop

grammar:

变量的初始化;
do{
	循环执行的语句;
	变量的更新;
}while(循环条件);

The difference between do-while and for and while:
for and while are the conditional judgment first, and then the loop statement is executed. If the condition is not established, it will not be executed once.
Do-while is to execute the loop statement first, then the conditional judgment, if the condition is not established, it will be executed at least once.
Implementation process:
Insert picture description here

Practice: Run by yourself. After finishing a lap, ask him if he wants to continue running. When the answer is "y", continue to run the next lap, otherwise end the run.
1. Use do-while to complete
2. Use String type for loop variables
3. Loop code, first output and run a circle, and then input string into loop variables
4. Loop condition is that the variable value is "y"

Scanner input = new Scanner(System.in);
String answer = "";
do{
	System.out.println("跑完了一圈,是否要继续跑?");
	answer = input.next();
}while(answer.equals("y"));
System.out.println("跑完了,休息下");

break keyword

Question: Suppose a person is going to work for a year in the company, suppose it is 365 days. If this person buys a lottery ticket to make a fortune on the 100th day and does not want to work anymore, what should I do?
-Use the break keyword
break function: stop the execution of the entire loop in the middle of the loop.

//使用循环模拟上365天班
for(int i = 1;i <= 365;i++){
	System.out.println("上了"+i+"天班");
	//在第100天中奖,辞职不上班了
	if(i == 100){
		//停止整个循环的执行
		break;
	}
}

continue keyword

Question: Suppose the person above didn't really win the lottery, just dreaming, but fell asleep while catching a cold, and wanted to take a day off on the 100th day before continuing to work. What should I do?
——Use the continue keyword
continue function: skip the execution of a certain loop in the middle of the loop, and continue the next loop.

for(int i = 1;i <= 356;i++){
	//在第100天,跳过当天的上班
	if(i == 100){
		System.out.println("今天发烧了,要请假!");
		//跳过本次循环,继续
		continue;
	}
	System.out.println("上第"+i+"天班");
}

Exercise:
1. Find the sum of 1 to 100, and if the sum exceeds 2000, it ends.
2. Output all numbers between 1 and 100 whose mantissa is not 3

Nested loop

Any statement can be executed inside the loop, including another loop, which forms a nested loop.
Such as:

for(...){
    for(...){
        ...
    }
}
while(..){
    while(..){
        ...
    }
}

Etc., for, while, do-while can also be nested with each other.

Execution process of nested loop: the
outer loop is executed once, the inner loop is executed once
Insert picture description here

Exercise 1: Simulate minutes and seconds.
Analysis:
The loop of seconds is nested inside the loop of
minutes. It executes one round per second and once per minute

for(int i = 0;i < 60;i++){
	for(int j = 0;j < 60;j++){
		System.out.printf("当前时间是:%d分%d秒\n",i,j);
	}
}

Exercise 2: Output 5 5 squares, only one output at a time.
Analysis: The
outer loop controls the number of printed lines. The
inner loop controls the number of printed lines .

//外层控制行数
for(int i = 1;i <= 5;i++){
	//内层控制打印5个*
	for(int j = 1;j <= 5;j++){
		System.out.print("* ");
	}
	//输出换行
	System.out.println();
}

Exercise 3: Output a right triangle

*
* *
* * *
* * * *
* * * * *

Exercise 4: Invert a right triangle

* * * * *
* * * *
* * *
* *
*

Exercise 5: Output an isosceles triangle

        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

Break and continue of nested loops

for(...){
    for(...){
     	if(...){
        	break/continue;
        }
    }
}

The break and continue in the inner loop only affect the inner loop and have no effect on the outer loop.
If you want break and continue to affect the outer loop, you can use the label statement (label text can be customized)

label:
for(...){
    for(...){
        if(...){
       		 break label;
        }
    }
}

End

Okay, leave some homework for everyone:

  1. Output 20 Fibonacci numbers:
    1, 1, 2, 3, 5, 8, 13, 21, 34...
    Starting from the third number, each number is equal to the sum of the first two numbers.

  2. Output diamond

        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *
  * * * * * * *
    * * * * *
      * * * 
        *
  1. Find all prime numbers between 1 and ·100 (only divisible by 1 and itself)

If you need to learn other Java knowledge, poke here ultra-detailed knowledge of Java Summary

Guess you like

Origin blog.csdn.net/u013343114/article/details/112275496