循环结构(三)For循环
1.语法
for(初始化;布尔表达式;更新){
//代码语句
}
-
支持迭代的通用结构,是最有效最灵活的循环结构
-
for循环的执行次数在执行前就确定
2.例题
输出0-10
public class ForDemo01 {
public static void main(String[] args){
//输出0-10;
for (int i = 0; i <=10; i++) {
System.out.println(i);
}
}
}
计算0-100之间奇数与偶数的和
public class ForDemo02 {
public static void main(String[] args) {
//计算0-100之间的奇数和与偶数和;
int oddSum = 0; //奇数和
int evenSum = 0; //偶数和
for(int i = 0;i<=100;i++){
if (i%2!=0){
oddSum += i;
}else{
evenSum+=i;
}
}
System.out.println("奇数和" + oddSum);
System.out.println("偶数和" + evenSum);
}
}
输出1-100能被5整除的数,每行输出三个
public class ForDemo03 {
public static void main(String[] args) {
//输出1-100能被5整除的数,每行输出三个
int m = 0;
for(int i = 1;i<=100;i++){
if(i%5==0){
m++;
if(m%3!=0){
System.out.print(i);
System.out.print(" ");
}else{
System.out.println(i);
}
}
}
System.out.println();
System.out.println("============================");
//方法二
for (int i = 1; i <= 100; i++) {
if(i%5==0){
System.out.print(i+"\t");//\t为空格,print为输出后不换行 println为输出后换行
}
if(i%(5*3)==0){
System.out.println("\n"); // \n为换行
//或System.out.println();
}
}
}
}
输出99乘法表
public class ForDemo04 {
public static void main(String[] args) {
//打印99乘法表
for (int i = 1; i <= 9; i++) {
for(int j = 1;j<=9;j++){
if(j>i){
System.out.print("\t");
}else{
System.out.print(j+"*"+i+"="+i*j+"\t");
}
}
System.out.println();
}
System.out.println("=============================");
//方法二
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j+"*"+i+"="+i*j+"\t");
}
System.out.println();
}
}
}
3.增强for循环
-
语法
for(声明语句:表达式){
//代码语句
}
-
例题
public class ForDemo05 {标签:int,System,print,循环,println,结构,public,out From: https://www.cnblogs.com/HomeFJ/p/16972519.html
public static void main(String[] args) {
int []numbers={10,20,30,40,50};// 定义一个数组
for(int x:numbers){ //遍历输出数组元素
System.out.println(x);
}
System.out.println("=======================");
//相当于
for(int i = 0;i<=4;i++){
System.out.println(numbers[i]);
}
}
}