Program logic control (2)-loop structure (for statement, while statement, the difference between break and continue and common exercises: find the first n items and find the factorial sum and other code implementation)

Program logic control (2)

1. Loop structure

1.while loop

//语法(循环条件为 true, 则执行循环语句; 否则结束循环)
while(循环条件){
    
    
循环语句;
}
  • Print numbers from 1-10;
  • Calculate the sum of 1-100;
  • Calculate the factorial of 5;
  • Calculate the result of 1! + 2! + 3! + 4! + 5!;
public static void main(String[] args) {
    
    
    //打印1-10的数字
    int num = 1;
    while(num  <= 10){
    
    
        System.out.println(num);
        num++;
    }
    //计算1-100的和
    int n = 1;
    int result = 0;//用来存放结果的变量
    while(n <=100 ){
    
    
        result += n;
        n++;
    }
    System.out.println("1-100的和为: "+result);
    //计算5的阶乘
    int m = 1;
    int res = 1;//用来存放结果的
    while(m <= 5){
    
    
        res *= m;
        m++;
    }
    System.out.println("5的阶乘是: "+res);
    //计算 1! + 2! + 3! + 4! + 5!
    int nums = 1;
    int sum = 0;//放最终的结果
    //外层循环求和
    while(nums <= 5){
    
    
        int fac = 1;
        int tmp = 1;
        //里面这次循环计算阶乘
        while(tmp <= nums){
    
    
            fac *= tmp;
            tmp++;
        }
        sum += fac;
        nums++;
    }
    System.out.println("1! + 2! + 3! + 4! + 5!的结果是: "+sum);

2.for loop

  • Expression 1: Used to initialize loop variables.
  • Expression 2: Loop condition
  • Expression 3: Update loop variable
//语法,
for(表达式1;表达式2;表达式3){
    
    
循环体;
}
public static void main(String[] args) {
    
    
    // 计算 1 - 100 的和
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
    
    
        sum += i;
    }
    System.out.println("sum = " + sum);
    //计算5的阶乘
    int result = 1;
    for (int i = 1; i <= 5; i++) {
    
    
        result *= i;
    }
    System.out.println("result = " + result);
    //计算 1! + 2! + 3! + 4! + 5!
    int sums = 0;
    for (int i = 1; i <= 5; i++) {
    
    
        int tmp = 1;
        for (int j = 1; j <= i; j++) {
    
    
            tmp *= j;
        }
        sums += tmp;
    }
    System.out.println("sums = " + sums);
}

3.break和continue

  • break directly out of the loop
//找到 100 - 200 中第一个 3 的倍数
public static void main(String[] args) {
    
    
    int num = 100;
	while (num <= 200) {
    
    
		if (num % 3 == 0) {
    
    
			System.out.println("找到了 3 的倍数, 为:" + num);
			break;
		}
	num++;
	}
}
// 执行结果
找到了 3 的倍数,:102(因为102已经找到了,所以直接就跳出循环,不在循环了)
  • continue is to jump out of this loop and enter the next loop
// 找到 100 - 200 中所有 3 的倍数
public static void main(String[] args) {
    
    
	int num = 100;
	while (num <= 200) {
    
    
		if (num % 3 != 0) {
    
    
			num++; // 这里的 ++ 不要忘记! 否则会死循环.
			continue;
		}
		System.out.println("找到了 3 的倍数, 为:" + num);
		num++;
	}
}
//执行到 continue 语句的时候, 就会立刻进入下次循环(判定循环条件), 从而不会执行到下方的打印语句;

Guess you like

Origin blog.csdn.net/qq_45665172/article/details/110455876