while和for循环

循环结构图:

 

           循环结构主要分为两种:有while和for两种循环,while又分为do{...}while和while{...},do...while表示先执行后判断,而while循坏表示先判断后执行,如果循环条件都不满足的情况下,do...while至少执行一次,而while一次都不会执行。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Demo {
 
public static void main(String[] args) {
 
int i=0,sum=0;
 
while(i<=4){ //假设输入n等于4
 
sum+=i;
 
i++;
 
}
 
System.out.println(sum);
 
}
 
}

  

 

 

Demo.java 1~100之间的整数的和

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Demo {
 
public static void main(String[] args) {
 
int i=0,sum=0;
 
do{ //求1~100的和
 
sum+=i;
 
i++;
 
}while(i<=100);
 
System.out.println(sum);
 
}
 
}

  

 

 

 

题目:对一个正整数,将各位数字反转后输出。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Demo {
 
public static void main(String[] args) {
 
int n=378; //需要输出873
 
/*
 
 * 378%10=8
 
 * 378/10=37
 
 * */
 
do{
 
int ret=n%10;
 
System.out.print(ret);
 
n/=10;
 
}while(n!=0);
 
}
 
}

  

posted @   香菇炖小鸡  阅读(141)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示