for语句基础求和练习
结构
for(初始化表达式;条件表达式;循环后的操作表达式) {
循环体;
}
1.求出1-10之间数据之和:
class Hello2 { public static void main(String[] args) { int sum = 0; for (int i = 1;i <= 10 ;i++ ) { sum = i + sum; } System.out.println(sum); } }
结果:
2.求出1-100之间偶数和:
public static void main(String[] args) { int sum = 0; for (int i = 1;i <= 100 ;i++ ) { if (i % 2 == 0) { sum = i + sum; } } System.out.println(sum); } }
结果:
3.求出1-100之间奇数和:
方法一:
public static void main(String[] args) { int sum = 0; for (int i = 1;i <= 100 ;i++ ) { if (i % 2 == 1) { sum = i + sum; } } System.out.println(sum); } }
方法二:
class Hello2 { public static void main(String[] args) { int sum = 0; for (int i = 1;i <= 100 ;i+=2 ) { sum = i + sum; } System.out.println(sum); } }
结果:
相关文章