for和while是我们在平时的开发中经常用到的。其中for的使用场景一般都是已知需要迭代的次数,而while的使用场景更多是不知道循环多少次才能达到条件。下面来看代码:
c的写法
#include <stdio.h>
int main() {
//第一种for循环
for (int i = 0; i < 3; ++i) {
printf("%d\n", i);
}
//第一种while循环
int whi = 0;
while (whi <3) {
printf("the first while %d\n", whi);
whi++;
}
//第二种while循环
whi = 0;
do {
printf("the second while %d\n", whi);
whi++;
} while (whi <3);
return 0;
}
c++的写法
#include <stdio.h>
int main() {
//第一种for循环
for (int i = 0; i < 3; ++i) {
printf("the first for %d\n", i);
}
//第二种for循环
int array[3] = {4,5,6};
for (auto &arr: array) {
printf("the second for %d\n", arr);
}
//第一种while循环
int whi = 0;
while (whi <3) {
printf("the first while %d\n", whi);
whi++;
}
//第二种while循环
whi = 0;
do {
printf("the second while %d\n", whi);
whi++;
} while (whi <3);
return 0;
}
java的写法
public class ForWhile {
public static void main(String[] args) {
//第一种for循环
for (int i = 0; i < 3; i++) {
System.out.println("the first for is "+ i);
}
//第二种for循环
int[] array = {1,2,3};
for (int arr : array) {
System.out.println("the second for is "+arr);
}
//第一种while循环
int a = 0;
while (a < 3) {
System.out.println("the first while is "+a);
a++;
}
//第二种while循环
do {
System.out.println("the second while is "+a);
a--;
} while (a >0);
}
}
go的写法
func main() {
//第一种for循环
for i:=0; i < 3; i++ {
fmt.Println("the first for is ", i)
}
//第二种for循环
array := [3]int{1,2,3}
for i, arr:=range array{
fmt.Printf("the second for %d is %d\n", i, arr)
}
//间接实现while循环
a := 0
for {
if a > 3 {
fmt.Println("a is greater than 3")
break
}
time.Sleep(1*time.Second)
a++
}
}
python的写法
if __name__ == "__main__":
#第一种for循环
for i in range(0, 3):
print("the first for is " + i)
#第二种for循环
array = [1, 2, 3]
for i in array:
print("the second for is " + i)
#第一种while循环
whi = 0
while whi < 3:
print("the first while is " + whi)
whi += 1
对比总结:
- 一般情况下,第一种for循环和while循环即可满足使用。
- c中没有第二种for循环;go中没有while循环;python中没有第二种while循环;不过go可以通过for无限循环和if条件判断间接实现while循环;