For循环结构的使用
一、循环结构的四个要素
1.初始化条件
2.循环条件 ---->是boolean类型
3.循环体
4.迭代条件
二、for循环的结构
for(1;2;4;){
3
}
执行过程:1 - 2 - 3 - 4 - 2 - 3 - ......- 2
class day4a{
public static void main(String[] args){
for(int i = 1;i <= 5;i++){
System.out.println("hello");
}
//i:在for循环内有效,出了for循环就无效
//System.out.println(i);错误
//练习:
int num = 1;
for(System.out.print('a');num <= 3;System.out.print('c'),num++){
System.out.println('b');
}
//练习2:遍历100以内的偶数,输出所有的偶数个数,并求和
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("总个数为" + count);
}
}
题目:输入两个正整数,求其中最大公约数和最小公倍数
说明:break关键字的使用
import java.util.Scanner;
class day4b{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入第一个正整数");
int m = scan.nextInt();
System.out.println("请输入第二个正整数");
int n = scan.nextInt();
//获取最大公约数
//获取两个值中最小值
int min = (m <= n)?m : n;
for(int i = min;i >= 1;i--){
if(m % i == 0 && n % i ==0){
System.out.println("最大公约数为" + i);
break;//跳脱出循环结构中
}
}
//获取最小公倍数
int max = (m >= n)?m : n;
for(int i = max;i <= m * n;i++){
if(i % m == 0 && i % n == 0){
System.out.println("最小公倍数为" + i);
break;//跳脱出循环结构中
}
}
}
}
while循环的使用
一、循环结构的四个要素
1.初始化条件
2.循环条件 ---->是boolean类型
3.循环体
4.迭代条件
二、while循环的结构
1
while(2){
3;
4;
}
执行过程:1 - 2 - 3 - 4 - 2 - 3 - 4 - ... - 2
说明:
1.写while循环千万要小心不要忘了迭代条件,一旦丢失,有可能导致死循环
2.我们写程序的时候,要避免出现死循环
3.for循环和while循环是可以相互转换的;
区别:for循环和while循环的初始化条件部分的作用范围不同
class day4c{
public static void main(String[] args){
int i = 1;
while(i <= 100){
if(i % 2 ==0){
System.out.println(i);
}
i++;
}
}
}
算法:有限性
do-while循环的使用
一、循环结构的四个要素
1.初始化条件
2.循环条件 ---->是boolean类型
3.循环体
4.迭代条件
二、do-while循环结构:
1
do{
3;
4;
}while(2);
执行过程:1 - 3 - 4 - 2 - 3 - 4 - 2 - ... -2
do-while至少会执行一次循环体!
开发中,使用for和while更多一些,较少使用do-while
class day4d{
public static void main(String[] args){
int num = 1;
int sum = 0;
int count = 0;
do{
if(num % 2 ==0){
System.out.println(num);
sum += num;
count++;
}
num++;
}while(num <= 100);
System.out.println("总和为" + sum);
System.out.println("总个数为" + count);
}
}
嵌套环境的使用
1.嵌套循环:将每一个循环结构A声明在另一个循环结构B的循环体中,就构成了嵌套循环
2.
外层循环:循环结构B
内层循环:循环结构A
3.说明
1.内层循环结构遍历一边,只相当于外层循环循环体执行了一次
2.假设外层循环需要执行m次,内层循环体执行了n次,此时内层循环的循环一共执行了m*n次
//实例练习
/*
******
******
******
******
*/
class day4e{
public static void main(String[] args){
for(int j = 1;j <= 4;j++){
for(int i = 1;i <= 6;i++){
System.out.print("*");
}
System.out.println();
}
/*
*
**
***
****
*/
for(int j = 1; j <= 4;j++){
for(int i = 1;i <= j;i++){
System.out.print("*");
}
System.out.println();
}
/*
****
***
**
*
*/
for(int j = 1; j <= 4;j++){
for(int i = 4;i >= j ;i--){
System.out.print("*");
}
System.out.println();
}
}
}