在上一篇文章的時候,介紹到for,而本篇文章的主要內容則介紹while。
例如:用while循環顯示5個Hallo World!
while代碼案例1
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(){
int index = 1;
while(index <= 5)
printf("Hallo World!\n");
return 0;
}
運行結果:
while代碼案例2
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(){
int index = 1;
while(index++ <= 5)
printf("Hallo World!\n");
return 0;
}
運行結果:
在代碼案例中使用while的時候可要注意了,那種寫法代碼運行起來的結果就是無限循環,有時候寫程序的時候,難免寫錯。其實while和for顯示出來的效果是一樣的,如果沒有使用循環的話,那麼想要顯示n條相同的數據時,就會很麻煩,不但麻煩,還增加了代碼量,工作量,這種是划不來的,熟練的使用循環,不但可以簡化代碼,提高程序質量,提高工作效率。