0
点赞
收藏
分享

微信扫一扫

For循环语句及使用

伊人幽梦 2022-04-29 阅读 63

for循环

/*
for循环语句支持迭代,是最有效,最灵活的循环结构
1.最先执行初始化步骤,可初始化一个或者多个循环控制变量,也可以是空语句
2.检测布尔表达式的值,为true,循环体被执行,为false,循环终止,执行循环体后面的语句
3.再次检测布尔表达式,循环执行上面的过程
 */

public class ForDemon01 {
    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 ( ; ;){     //死循环
        }
        */

        }
}

用for循环打印九九乘法表:

public class ForDemon03 {
    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 + "*" + i + "=" + (j * i) + "\t");//使用print换行
            }
            System.out.println();
        }
        }
    }

练习:

//练习

public class ForDemon02 {
    public static void main(String[] args) {
        //例题1:计算0到100之间的奇数的和与偶数的和

        int oddSum = 0;
        int evenSum = 0;

        for (int i = 0; i < 100; i++) {
            if (i%2!=0){
                oddSum+=i;
            }else{
                evenSum+=i;
            }
        }
        System.out.println("奇数的和:"+oddSum);
        System.out.println("偶数的和:"+evenSum);
        System.out.println("===========================================");

        //例题2:用while或for循环输出1-1000之间能被5整除的数,并且每行输出3个
        //思路:先利用for循环输出所以5的倍数,在利用 /n 实现每次输出15的倍数就
         // 换行,即可实现每行输出3个
        for (int a = 1; a <=1000; a++) {
            if (a%5==0){
                System.out.print(a+"\t");
            }
            if (a%(5*3)==0){
                System.out.println();

                // System.out.print("\n");  换行,上式输出空字符串也能达到效果
            }
            //  println  输出完会换行
            //  print   输出完不会换行
        }

   
    }
}

遍历数组:

public class ForDemon04 {
    public static void main(String[] args) {
        int[] numbers = {10,20,30,40,50};  //定义了一个数组

        //两种方式

        for (int i=0;i<5;i++){
            System.out.println(numbers[i]);
        }
        System.out.println("====================================");
        //遍历数组的元素
        for (int x:numbers){
            System.out.println(x);
        }

    }
}
举报

相关推荐

0 条评论