for循环
- for循环语句是支持迭代的一种通用结构
- for循环执行的次数在执行前就确定的
for(初始化; 布尔表达式; 更新 ){
// 代码语句
}
例题一:计算0-100之间所有奇数和偶数的和
public static void main(String[] args) {
// 计算0-100之间奇数和偶数的和
int oddSum = 0;// 接收奇数
int evenSum = 0;// 接收偶数
//使用for循环遍历0-100
for (int i = 0;i <= 100;i++){
// 判断寄偶性,如果对2取模不等于0,为奇数
if (i % 2 != 0){
oddSum += i;
}else {
evenSum += i;
}
}
System.out.println("奇数的和:"+oddSum);
System.out.println("偶数的和:"+evenSum);
}
例题二:使用whil和for循环输出1-1000之间能被5整除的数
public static void main(String[] args) {
// 使用while和For循环输出1-1000之间能被5整除的数,并且每行输出3个
// while
int i = 1;// 初始化
int count = 0;// 计算输出数的个数,换行
// while循环遍历
while(i <= 1000){
if (i%5==0){
System.out.print(i+"\t");
count++;
}
// 迭代更新
i++;
if (count%3 == 0){
System.out.println();
}
}
System.out.println();
System.out.println("=============");
// for循环
for (int j = 1;j<=1000;j++){
if (j%5==0){
System.out.print(j+"\t");
count++;
}
if (count%3 == 0){
System.out.println();
}
}
}
例题三:打印九九乘法口诀
public static void main(String[] args) {
int sum = 0; // 用于接收乘积
for (int i = 1; i <= 9;i++ ){
for (int j = 1; j <= i ;j++){
sum = i * j;
System.out.print(i + "*" + j + "=" + sum + "\t");
}
System.out.println();// 用于换行
}
}