for循环 学习记录


for循环 学习记录


/*
For循环的使用
一:循环结构的四个要素
 1.初始化条件
 2.循环条件 -- 是 boolean类型 
 3.循环体
 4.迭代条件

二: for循环的结构(初始 条件 迭代 循环)
for (1;2;4) { 3 }

执行过程:初始 条件 循环 迭代  1- 2 - 3 - 4 - 2 - 3 - 4 - 2
*/
class ForTest
{
	public static void main(String [] args)
	{
		for (int i = 1;i<=5 ;i++ ) //i = 1 2 3 4 5
		{
			System.out.println("Hello World");
		}
		//System.out.print(i);    i在for循环内有效,出了for失效

		//练习
		int num = 1;
		for (System.out.print('a');num<=3 ;System.out.print('c'),num++ )
		{
			System.out.print('b');
		} //abcbcbc

		System.out.println();

		//例题:遍历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);//此处注意 写到了for循环外面,否则会被当成循环执行进去
		System.out.println("偶数的个数为" + count);
}
}
/*
例题:编写程序,从1循环到150,并在每行打印一个值,
另外在每个3的倍数上打印输出foo,
在每个5的倍数上打印输出biz,
在每个7的倍数上打印baz
*/
class ForTest1
{
	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();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值