for循环小例子

1.计算1+2+3+…+100的和

public static void main(String[] args){
      int sum = 0;
      for(int i = 1;i <= 100;i++){
           sum = sum + i;
        }
     System.out.printf("1+2+3+...+100= %d%n",sum);
     }

运行结果

java for循环练习题 java for循环案例_i++

2.求100以内的偶数和

public static void main(String[] args){      
        int sum = 0;
        for(int i = 2;i <= 100;i+=2){
            sum = sum + i;
        }
        System.out.printf("100以内的偶数和= %d%n",sum);
     }

运行结果

java for循环练习题 java for循环案例_算法_02

3.九九乘法表

public static void main(String[] args){ 
       for (int a = 1; a <= 9; a++) {
            for (int b = 1; b <= a; b++) {
                System.out.printf("%d * %d = %2d  ", a, b, a * b);
            }
            System.out.println();
        }
}

运行结果

java for循环练习题 java for循环案例_数据结构_03

4.百钱百鸡

public static void main(String[] args){
        for(int i = 0; i <= 100;i++){
            for(int i1 = 0; i1 <= 100;i1++){
                for(int i2 = 0; i2 <= 100;i2++){
                    int a = i;
                    int b = i1;
                    int c = i2;
                    if((a + b +c)== 100 && (a * 5 + b * 3 + c / 3)== 100 && c  % 3==0){
                        System.out.printf("公鸡 : %d只,母鸡 : %d只,小鸡 : %d只, %n", a, b, c);
                    }
                }
            }
        }
     }

运行结果

java for循环练习题 java for循环案例_i++_04

5.计算1980年到现在共有多少个闰年?

public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入年份:");
        int year = scan.nextInt();
        int num = 0;
        for (int i = 1980; i <= year; i++) {
            if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0)) {
                num++;
                System.out.print(i + "\t");
            }
            if (num == 4) {
                num = 0;
                System.out.println();
            }
        }
    }

运行结果

java for循环练习题 java for循环案例_数据结构_05