一、目标
1、掌握循环类型
2、掌握循环案例
二、知识点
1、循环
作用:用于重复执行相同代码的一种执行过程,在该过程中通过
执行的条件控制需要重复执行的代码。
种类:
1、有效循环 --> 有次数的循环
2、死循环 -->无次数的循环
2、循环类型
包含以下3种:
a、while循环
语法:
while(循环执行条件){
循环执行的代码部分
}
b、do..while循环
语法:
do{
循环执行的代码部分
}while(循环执行条件);
while和do..while的区别:
while循环必须满足循环条件才能执行循环部分,而
do..while会先执行一次循环部分,再根据循环条件决定
是否继续循环。
c、for循环
语法:
for(参数1;参数2;参数3){
循环执行的代码部分
}
参数1:计数器 --> int i=1;
参数2:循环条件 --> i<?
参数3:计数 --> i++;
3、循环案例
1、使用循环打印1-100之间偶数内容
2、使用循环统计1-100之间的总和
3、使用循环获取1-100之间偶数的个数
4、作业:
1、使用循环打印100-999之间的水仙花数
153 : 111 + 555 + 333 = 153
2、使用循环打印9X9乘法表
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
....
3、扩展题:
使用循环在控制台打印等边三角形
*
## 作业
public class Homework {
public static void main(String[] args) {
System.out.println("水仙花数---------------------------------------------------------------------------");
int ge=0,shi=0,bai=0;
for(int i=100;i<=999;i++) {
bai=i/100;
shi=(i/10)%10;
ge=i-bai*100-shi*10; //i%10
if(ge*ge*ge+shi*shi*shi+bai*bai*bai==i) {
System.out.println("水仙花数有"+i);
}
}
System.out.println("九九乘法表--------------------------------------------------------------------------");
int x=1,y=1; //x为横向,y为竖向
for(y=1;y<=9;y++) {
for(x=1;x<=9;x++) {
System.out.print(x+"*"+y+"="+x*y+" ");
if(x==y) {
System.out.println(); //当列数等于行数时换行并跳出循环进行下一行的输出
break;
}
}
}
System.out.println("等边三角形--------------------------------------------------------------------------");
int i=0,j=0,n=3; //i是行数,j是*数,n是空格
for(i=1;i<=4;i++) { //第一行i=1;3个空格 第二行 i=2 两个空格 4-i为空格数
for(n=4-i;n>0;n--) {
System.out.print(" "); //控制空格数
}
for(j=1;j<=7;j++) { //j控制*号数,打印*循环
System.out.print("*");
if(j==2*i-1) {
System.out.println(); //换行并跳出打印*号的循环
break; //字符串递增可用拼接 str="*" str+="**"
}
}
}
}
}