for循环

1、 for循环
(1)语法结构
语法结构
for(表达式1;表达式2;表达式3){
 ...代码块/循环体...
}
理解
  • 表达式1:初始化变量

  • 表达式2:判断条件

  • 表达式3:更新变量

执行顺序
  1. 初始化变量

  2. 判断条件:结果必须是boolean类型

    1. true:执行代码块,更新变量,重复第二个步骤

    2. false:跳出整个循环语句

(2)案例

案例1:循环输出1~10的数字

for(int i=1;i<=10;i++){
    System.out.println(i);
}

案例2:循环输出1~10的奇数数字

for(int i=1;i<=10;i+=2){
    System.out.println(i);
}

案例3:循环录入5次int类型的数字,输出总和

public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        
        int sum = 0;
        for(int i=1;i<=5;i++) {
            System.out.println("请输入第"+i+"个数字:");
            int num = scan.nextInt();
            sum += num;
        }
        System.out.println("总和为:"+sum);
        
    }

案例4:循环录入熊二的5门成绩,计算平均分

public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        
        double sum = 0;
        for(int i=1;i<=5;i++) {
            System.out.println("请输入第"+i+"门成绩:");
            double score = scan.nextInt();
            sum += score;
        }
        double avg = sum/5;
        System.out.println("平均分为:"+avg);
        
    }

案例5:循环录入5次int类型的数字,输出最大值

public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入第1个数字:");
        int max = scan.nextInt();
        for(int i=2;i<=5;i++) {
            System.out.println("请输入第"+i+"个数字:");
            int num = scan.nextInt();
            //如果录入的num比max更大,就将录入的num赋值给max
            if(max<num) {
                max = num;
            }
        }
        System.out.println("最大值为:"+max);
    }

(3)注意

1、在for循环中声明的变量只能在循环中使用

2、for循环中的更新变量i++和++i没有区别

(4)for循环嵌套

需求1

/**
 *  打印以下图形
 *      ****
 *      ****
 *      ****
 */
public class Test01 {
​
    public static void main(String[] args) {
        for(int i=1;i<=3;i++) {//控制行数
            for(int j=1;j<=4;j++) {//控制列数
                System.out.print("*");
            }
            System.out.println();//换行
        }
        
    }
}

需求2

/**
 *  打印以下图形
 *      *
 *      **
 *      ***
 *      ****
 *      *****
 */
public class Test01 {
​
    public static void main(String[] args) {
        
        for(int i=0;i<5;i++) {
            for(int j=0;j<=i;j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        
    }
}

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值