for循环详解

for循环详解

  • 虽然所有的循环结构否可以用while或者do…while表示,但Java提供了另一种语句——for循环,使一些循环结构变得简单
  • for循环语句是支持迭代的一种通用结构,是最有效,最灵活的循环结构。
  • for循环执行的次数是在执行前就确定的
for(初始化; 布尔表达式; 更新){
    //代码语句
}
  • 练习1:计算0到100之间的奇书和偶数之和
  • 练习2:用while或者for循环输出1-100之间能被5整除的数,并且输出3个
  • 练习3:打印九九乘法表

package com.mz.struct;

public class forDemo01 {
    public static void main(String[] args) {
        int a = 1;  //初始化条件

        while (a<100){ //条件判断
            System.out.println(a);
            a+=2;   //迭代
        }
        System.out.println("while循环结束");

        //初始化 //条件判断 //迭代
        for (int i=1; i<=100; i++){
            System.out.println(i);
        }
        System.out.println("for循环结束");
        /*
        关于for循环有以下几点说明
        最先执行初始化步骤,可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
        然后检测布尔表达式的值,如果为true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
        然后检测布尔表达式。循环执行上面的过程。
         */

        //死循环
        for ( ; ;){
        }


    }
}
package com.mz.struct;

public class forDemo02 {
    public static void main(String[] args) {
        //练习1,计算0-100之间奇数和偶数的和

        int oddSum = 0;
        int evenSun = 0;

        for (int i=0; i<=100; i++){
            if(i%2 !=0){
                oddSum+=i;
            }else {
                evenSun+=i;
            }
        }
        System.out.println("奇数和为:"+oddSum);
        System.out.println("偶数和为:"+evenSun);
    }
}
package com.mz.struct;

public class ForDemo03 {
    public static void main(String[] args) {
        //练习2:用while或者for循环输出1-100之间能被5整除的数,并且输出3个
        for (int i = 0; i <= 1000; i++) {
            if (i % 5==0){
                System.out.print(i+"\t"); //转义字符 \t 制表
            }
            if (i%(5*3)==0){
                System.out.println();
                //System.out.print("\n");
            }
            
        }
    }
}
package com.mz.struct;
/*
1x1=1
2x1=2  2x2=4
3x1=3  3x2=6  3x3=9
4x1=4  4x2=8  4x3=12 4x4=16
5x1=5  5x2=10 5x3=15 5x4=20 5x5=25
6x1=6  6x2=12 6x3=18 6x4=24 6x5=30 6x6=36
7x1=7  7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49
8x1=8  8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64
9x1=9  9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81
 */
public class ForDemo04 {
    public static void main(String[] args) {
        // 1.打印第一列
        // 2.把固定的1再用循环包起来
        // 3.去掉重复项,i <= j
        // 4.调整样式
        for (int j = 1; j <=9; j++) {
            for (int i = 1; i <=j; i++) {
                System.out.print(j+"x"+i+"="+(j*i)+"\t");

            }
            System.out.println();

        }

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值