一、循環結構的4個要素
①初始化條件
②循環條件
③循環體
④迭代條件
二、for循環的結構
for(①;②;④){
③
}
執行過程:① - ② - ③ - ④ - ② - ③ - ④ - … - ②
練習1:運用for循環輸出100個helloworld
class Test {
public static void main(String[] args) {
for(int a = 1;a<100;a++){
System.out.println("Hello World");
}
}
}
練習2:遍歷100以內的偶數
class Test {
public static void main(String[] args) {
for(int i = 1;i<=100;i++){
if(i % 2 == 0){
System.out.println(i);
}
}
}
}
練習3:遍歷100以內的偶數,並輸出所有偶數之和
class Test {
public static void main(String[] args) {
int sum = 0;//記錄100以內所有偶數之和
for(int i = 1;i<=100;i++){
if(i % 2 == 0){
System.out.println(i);
sum += i;
}
//System.out.println("總數和爲:" + sum);不能寫在這裏。
}
System.out.println("總數和爲:" + sum);
}
}
練習4:遍歷100以內的偶數,並輸出所有偶數之和,輸出偶數的個數
class Test {
public static void main(String[] args) {
int sum = 0;//記錄所有偶數之和
int count = 0;//記錄所有偶數的個數
for(int i = 1;i<=100;i++){
if(i % 2 == 0){
System.out.println(i);
sum += i;
count ++;
}
//System.out.println("總數和爲:" + sum);不能寫在這裏。
}
System.out.println("總數和爲:" + sum);
System.out.println("總個數爲:" + count);
}
}
練習5:編寫一個程序從1循環到150,並在每行打印一個值,
在3的倍數行上打出“foo”
在5的倍數行上打出“biz”
在7的倍數行上打出“baz”
class Test {
public static void main(String[] args) {
for(int i = 1; i<=150;i++){
System.out.print( i + " ")
if(i % 3 == 0){
System.out.print("foo")
}
if(i % 5 == 0){
System.out.print("biz")
}
if(i % 7 == 0){
System.out.print("baz")
}
//換行
System.out.println()
}
}
}