package java基础知识.小结与练习;
public class Test2 {
/**
* @param 求1+2+3+4...+10的和并输出此和.
* 思路:
* 可以通过循环结构完成,for循环是常用的方法
* 定义一个变量记录累加之和 sum
* for循环结束打印出sum的值
*/
public static void main(String[] args) {
// for循环
int sum = 0; //定义变量记录其累加之和
for (int i=1 ; i<=10 ; i++){
sum += i; //从1开始累加并不断储存改变sum的值
}
//输出和
System.out.println("通过for循环 输出 1到10以内整数的和是 :"+sum);
//while循环
int avg = 0; //定义一个保存和的变量
int a = 1; //初始化循环变量
while (a<=10){ //判定循环条件表达式
avg = a+avg; //储存累加的和的结果
a++; //改变循环变量
}
//输出结果
System.out.println("通过while输出 1到10以内整数的和是 :"+avg);
//do..while循环
int he = 0;//定义保存和的变量
int b = 1; //初始化循环变量
do{
he = he+b;//存储累加和
b++; //改变循环变量
}while(b<=10);//判定循环体的条件表达式
//输出结果
System.out.println("通过do..while 输出 1到10以内整数的和是 :"+he);
//递归
System.out.println("通过递归方式计算1到10以内整数的和是:" + count1(10));
}
public static int count1(int n){ // 递归.
return n == 1?1:count1(n-1)+n; //三元运算符 如果n不等于1通过循环不断调用本类的方法求和
}
}