C/C++、Java、Go、Python总结对比22-for和while

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

对比总结:

  1. 一般情况下,第一种for循环和while循环即可满足使用。
  2. c中没有第二种for循环;go中没有while循环;python中没有第二种while循环;不过go可以通过for无限循环和if条件判断间接实现while循环;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值