在一个循环语句内部再嵌套一个或多个循环,称为嵌套循环。while、do-while与for循环可以任意嵌套多层。
题目
编程求和:
∑1+∑2+∑3+……+∑100
=1 +(1+2)+(1+2+3)+(...)+(1+2+3+4+5+…+100)
第一种方法:for循环嵌套while循环:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13public class QiuHeYunSuan { public static void main(String[] args) { int j=1; int sum1=0; int sum2=0; for(int i=1;i<=100;i++) { while(j<=i) { //求每一个100内每个∑n的值 sum1+=j; j++; } sum2+=sum1;//将每个∑相加 } }
第二种方法:for循环嵌套for循环
复制代码
1
2
3
4
5
6
7
8
9
10
11
12public class QiuHeYunSuan { public static void main(String[] args) { int sum3=0; for(int a=1;a<=100;a++) { for(int b=1;b<=a;b++) {//解析成100个1,99个2…………1个100,相加 sum3+=b; } } System.out.println("方法2:"+"∑1+∑2+……+∑100="+sum3); } }
运行结果:

最后
以上就是忧郁大侠最近收集整理的关于do while 里面怎么嵌套switch_java 测试嵌套循环的全部内容,更多相关do内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复