Learning Notes: JAVA Cycle (for,while,do while)

Loop statement

1. for cycle
Syntax:
For (initialization; conditional expression; increment){
// Execution code
}
Note: Execution order, initialization - conditional expression judgement to be true - execution code - increment - Judgement conditional expression to be true - execution code - increment - until conditional expression is false, jump out of loop, end of loop
For example:

//Use for to print the results by accumulating 1 to 10
public class ForTest{
public static void main(String[] args){
int sum=0;
for(int i=1 ; i<=10 ; i++){
		sum+=i;
		}
		System.out.println("1 To 10 cumulative sum is:"+sum);
	}
}

2. while statement
Syntax:
While (cyclic condition){
Circulatory body
}
Note: The loop condition is true, the loop body is executed, otherwise the loop ends.

For example:

	//Use while to print the results by accumulating 1 to 10
public class WhileTest{
public static void main(String[] args){
int sum=0;
int i=1;
while(i<=10 ){
		sum+=i;
		i++;
		}
		System.out.println("1 To 10 cumulative sum is:"+sum);
	}
}

3. Do while statement
Do while and while types, but do while executes once before judging the loop conditions
Syntax:
do{
Circulatory body
} while (cyclic condition);
Note: The cycle conditions of the do while cycle are followed by parentheses.

For example:

//Use do while to print the results by accumulating 1 to 10
public class DoWhileTest{
public static void main(String[] args){
int sum=0;
int i=1;
	do{
		sum+=i;
		i++;
	}while(i<=10 );
		System.out.println("1 To 10 cumulative sum is:"+sum);
	}
}

4. Cyclic nesting
For example:

		//Output the following to the console:
        *
        **
        ***
        ****
        *****
        ******
        *******
        public class Test{
		public static void main(String[] args){
		//i row number
			for(int i=0;i<7;i++){
		//Number of *
					for(int j=0;j<i+1;j++){
							System.out.print("*");
						}
		//Line feed
						System.out.println();
				}
			}
		}

4. break and continue
Note: Breaks and continue s are generally combined with recycling (for/while/do-while)
break: Terminate the entire cycle
Continue: Stop this cycle, skip this cycle and continue

For example:

//break
for(int i=0;i<5;i++){
		if(i==2){
			break;
		}
		System.out.println("i = "+i);
	}
	//Output results:
	i = 0
	i = 1
	
//continue
for(int i=0;i<5;i++){
		if(i==2){
			continue;
		}
		System.out.println("i = "+i);
	}
	//Output results:
	i = 0
	i = 1
	i = 3
	i = 4

5. label label
Loop nesting can be done with label tags on specified loops. The default is the latest
For example:

f1:for(int i=0;i<3;i++){
	f2:for(int j=0;j<5;j++){
		if(j==3){
			break f1;
		}
		System.out.println("j = "+j);
	}

}
//Output results:
	j = 0
	j = 1
	j = 2

Posted by mr00047 on Wed, 02 Oct 2019 20:29:43 -0700