iT邦幫忙

DAY 24
0

30天C語言巔峰之路系列 第 24

30天C語言巔峰之路(Day24:迴圈-while迴圈)

while****迴圈
基本架構

while(expression)
{
	statements
}

expression 是迴圈來決定是否繼續執行的條件,statements則是要重複做的事情,只要條件符合,那麼在大括號裡面的程式碼都會依序執行。
※第一次進入迴圈之前就會檢查Condition是否成立了。

expression:0 ->那迴圈則會跳出

#include <stdio.h>
#include <stdlib.h>

int main()
{
	while(0)
	{
		printf("Enter\n");
	}
	printf("Out\n");
	system("pause");
	return 0;
}

執行結果

expression:1 ->那迴圈會永無止盡的做,稱為無窮迴圈

#include <stdio.h>
#include <stdlib.h>

int main()
{
	while(1)
	{
		printf("Enter\n");
	}
	printf("Out\n");
	system("pause");
	return 0;
}

執行結果

expression:x < 5 or x <= 7 or x != 123 ... 如果條件符合就會繼續做。

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int x=0;
	while(x<5)
	{
		printf("x:%d\n",x++);
	}
	printf("Out\n");
	system("pause");
	return 0;
}

執行結果

其實expression除了false(0)以外的數值放入都會形成無窮迴圈,因為布林的觀念所以我們都用true(1)。
在寫程式的時候應避免無窮迴圈的出現,它會導致你程式無法結束,增加Debug的難度。


上一篇
30天C語言巔峰之路(Day23:迴圈-介紹)
下一篇
30天C語言巔峰之路(Day25:迴圈-do迴圈)
系列文
30天C語言巔峰之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言