JAVA学习—基本for语句—2021-05-25

JAVA学习(小白向)—基本for语句—02021-05-25

1.累加和有步长的累加

package a6;

/**
 * 
 * @author hengyuzuo
 *
 */
public class forStatement {
	/**
	 * **************************
	 * The entrance of the program.
	 * @param args
	 * **************************
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		forStatementTest();
	}// Of main

	/**
	 * **************************
	 * The Method
	 * **************************
	 */
	public static void forStatementTest() {
		// TODO Auto-generated method stub
		int tempN = 10;
		System.out.println("1 add to " + tempN + " is " + added(tempN));
		
		tempN =0;
		System.out.println("1 add to " + tempN + " is " + added(tempN));
		
		int tempStepLength = 1;
		tempN = 10;
		System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: " + addedWithStep(tempN, tempStepLength));
		
		tempStepLength = 20;
		System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: " + addedWithStep(tempN, tempStepLength));
	}// Of forStatementTest
	
	/**
	 * ***************************
	 * add form 1 to N
	 * @param paraN
	 * @return the sum
	 * ***************************
	 */
	public static int added(int paraN) {
		// TODO Auto-generated method stub
		int resultSum =0;
		
		for (int i = 1; i <= paraN; i++) {
			resultSum += i;
		}// Of for
		
		return resultSum;
	}// Of added
	
	/**
	 * ****************************
	 * add with step
	 * ****************************
	 */
	
	public static int addedWithStep(int paraN, int paraStepLength) {
		// TODO Auto-generated method stub
		int resultSum = 0;
		
		for (int i = 1; i <= paraN; i += paraStepLength) {
			resultSum += i;
		}// Of for
		return resultSum;
	}// Of addedWithStep

}// Of class

运行结果:

1 add to 10 is 55
1 add to 0 is 0
1 add to 10 with step length 1 is: 55
1 add to 10 with step length 20 is: 1

for语言语法:
for(初始化; 布尔表达式; 更新) {
//代码语句
}

2.求出1-100的偶数和

package test1;
/**
 * 
 * @author hengyuzuo
 *
 */
public class TestDemo2 {

	public static void main(String[] args) {
		int sum = 0;
		
		for( int i = 1; i <= 100; i++) {
			if(i % 2 == 0) {
				sum += i;
			}// Of if			
		}// Of for
		
	System.out.println("偶数和为:" + sum);
	}// Of main
}// Of TestDemo2 class

运行结果

偶数和为:2550
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值