第四章循環(huán)控制程序

如何重復(fù)執(zhí)行一個語句塊瑰妄,直到滿足某個條件為之翅楼,這稱為循環(huán)
循環(huán)提供了終止循環(huán)的方式學(xué)習(xí)
遞增運算符和遞減運算符與其他算術(shù)運算符相比他們不直接更改變量存儲的值
變量只能在聲明他后面的語句中存在
遞增運算符的前置 ++變量 --變量
遞增運算符的后置 變量++ 變量--

#include <stdio.h>
#include <stdlib.h>
int main(void){
     for(int i = 0; i<100; i++){
          printf("Number : %d\n",j);
         return 0;
}
for(int i = 1; i < 9;i++){
    for(int j =1; j <9; j++){
        printf("%d*%d=%d \t", i , j ,i*j);
        if(j>5){
           break;//跳出當(dāng)前的循環(huán)||跳出所有的循環(huán)
       }
   }
 printf("\n");
}
return 0;
}

使用for循環(huán)一般使語句塊重復(fù)執(zhí)行指定的次數(shù)。干苦力的

//program   4.1  list   ten  integers

#include<stdio.h>

int main(void)
{
   int count =1;
   for( ; count<= 10; ++count)
   {
       printf("  %d", count);
    }
    printf("\n After  the loop count has the value %d. \n", count);
    return  0;
  }

試試看:繪制一個盒子
假設(shè)要在屏幕上使用字符*繪制一個方框忍法,可以多次使用Printf()語句潮尝。但輸入量很大,而使用FOR循環(huán)來繪制就容易多了缔赠。

//program 4.2 Drawing a box
#include <stdio.h>
 
int main(void)
{
   printf("\n*********************'');
   for(int count =1 ; count <=8 ; ++count)
      printf("\n*  *");
   
   printf("\n*********************\n");
   return 0;
}

試試看:數(shù)字的總和

這個程序比用*畫盒子要有用衍锚、有趣的多。假定想知道某條街上所有門牌號的總和是多少嗤堰,這需要讀入最大的門牌號戴质,再使用for循環(huán)匯總所有的整數(shù),從1加到輸入的那個數(shù)值為止踢匣。

//program 4.3 Sum the integers from 1 to a user-specified number
#include <stdio.h>

int main (void)
{
   unsigned   loog  sum =0LL;
   unsigned  int  count  =0;

   printf("\nEnter the number of integers you want to sum:");
   scanf(" %u", &count);

for (unsigned  int  i =1; i <=count ; ++i)
   sum +=i;
  
printf("\nTotal of the  first %u number  is %11u\n", count, sum);
return 0;
}

試試看:靈活的for循環(huán)
這個例子說明了如何在FOR循環(huán)的第3個控制表達(dá)式中完成一個計算:

//program 4.4 summing integers -compact version
#include <stdio.h>

int main(void)
{
   unsigned long long sum = 0LL;
   unsigned int count  =0;
 
printf("\nEnter the number of  integers you want to sum: ");
scanf(" %u", &count);

for(unsigned int  i=1 ; i<= count ; sum += i++);

printf("\nTotal of the first %u numbers is  %11u\n", count, sum );  
return 0;   
}

修改for循環(huán)變量
逆向計算前n個整數(shù)的總和

//program 4.5 summing integers backward
#include<stdio.h>
{
   unsigned long long sum  =1LL;
   unsigned int count  =0;
 
printf("\nEnter the number of  integers you want to sum: ");
scanf(" %u", &count);

for(unsigned int i  =count ; i >=1 ; sum +=i--);
 
printf("\nTotal of  the first %u  number is %11u\n",count, sum);
return 0;
}

試試看:最小的for 循環(huán)

遇到問題不能再是死記硬背告匠,而是理解,不能急离唬,慢慢消化轉(zhuǎn)化為自己的知識
這個例子計算了任意個數(shù)字的平均值

//program 4.6 The indefinite loop -computing an average
#include <stdio.h>
#include<ctype.h>

int main (void)
{
   char answer = 'N' ;
   double total = 0.0;
   double valve =0.0;
   unsigned int count =0;

   printf("\nThis program calculates the average of " any number of values.")
   
   for (后专;;)
   {
       printf("\nEnter a value: ");
       scanf(" %1f", &value);
       total += value;
       + +count;

       printf("Do you  want to enter another value ?( Y or N): ");
       scanf(" %c", &answer);
       if (tolower (answer) == 'n')
           break;
    }
 
    printf("\nThe average is %.21f\n", total/count );
    return 0;
}

試試看:數(shù)字猜謎游戲

這個程序要求用戶猜測該程序挑選出來的幸運數(shù)字输莺。它使用了一個for循環(huán)和多個if語句戚哎。還加進(jìn)了條件運算符,提醒讀者不要忘記如何使用它嫂用。

//program 4.7 A Guessing Game

#include <stdio.h >

int main (void)
{
   int chosen =15;
   int guess  =0;
   int  count =3;

printf("\n That is a guessing game.");
printf("f\nI have chosen a number between 1 and 20" which you want must guess.\n");
for( 型凳; count > 0 ; --count)
{
   printf("\n You have %d tr%s left.", count, count ==1 ? "Y" : " ies");
   printf("\nEnter a guess: ");
   scanf("%d", %guess);

   if (guess==chosen)
   {
      printf("\n Congratulation. You guessed it!\n");
      return 0;
   }
   else  if(guess < 1 || guess >20)
      printf("I said the number is between 1 and 20.\n ",guess, chosen > guess ? "greater" : "less");
}
printf("\nYou have had three tries ans failed. The number was %d\n",chosen);
return 0;
}

試試看:使用while循環(huán)
使用while循環(huán)編寫整數(shù)匯總的程序

//program 4.8 while programming and summing integers
#include <stdio.h>

int main(void)
{
   unsigned long sum = 0UL;
   unsigned int  i =1;
   unsigned  int count  =0;

printf("\nEnter the number of integers  you wany to sum:");
scanf(" % u", &count);

while(i <= count)
sum += i++;

printf("Total of the first %u numbers is %lu\n", count, sum);
return 0;
}

試試看:使用嵌套的循環(huán)


//program 4.9 Output a box with given width and height
#include<stdio.h>

int main(void)
{
   const  unsigned int MIN_SIZE =3;
   unsigned int width =0;
   unsigned int height =0;

printf("Enter values for the width and height (minimum of %u):", MIN_SIZE);
scanf("%u%u", &width, &height );

if(width < MIN_SIZE)
{
printf("\nWidth value of %u is too small.Setting it to %u.",width,MIN_SIZE);
width = MIN_SIZE;
}
if(height < MIN_SIZE)
{
printf("\nHeight value of %u is too small,Setting it to %u." height, MIN_SIZE);
height = MIN_SIZE
}
for(unsigned int i= 0 ; i< width; ++i)
printf("*");
for(unsigned int j =0; j< height -2 ; ++j)
{
printf("\n*");
for(unsigned int j= 0; j<  width -2 ; ++i)
printf(" ");
printf("*");
}
printf("\n");
for(unsigned int i=0; i < width ; ++i)
printf("*");

printf("\n");
return 0;
}

試試看:嵌套循環(huán)中的計算
下面的例子已匯總整數(shù)的程序為基礎(chǔ)。原來的程序是計算從1到輸入值之間的所有整數(shù)的和≈龊現(xiàn)在要從第一間房子開始甘畅。一直到當(dāng)前的房子為止,計算每間房子的居住人數(shù),看看這個程序的輸出疏唾,就會比較清楚蓄氧。
在for 循環(huán)里面嵌套了for循環(huán)

// program 4.10 Sum of  successive integer sequences
#include <stdio.h>

int main(void)
{
  unsigned long sum = 0 UL;
  unsigned int count = 0 ;

  printf("\nEnter the number of integers you want to sum: ");
  scanf(" %u", &count);

for(unsigned int i =1; i <= count ; ++i)
{
   sum =0UL;

for(unsigned int  j=1; j <= i; ++j)
sum += j;
printf("\n%u\t%5lu", i , sum);
}
printf("\n");
return 0;
}

試試看:在for循環(huán)內(nèi)嵌套while循環(huán)

//program 4.11 sums of integers with a while loop nested in a for loop
#include<stdio.h>

int main(void)
{
  unsigned long sum = 1UL;
  unsigned int j = 1U;
  unsigned int count = 0;

printf("\nEnter the number of integers you want to sum: ");
scanf(" %u" ,&count);

for(unsigned int i = 1 ; i<=count ; ++i)
{
   sum = 1UL;
   j=1;
printf("\n1");

while(j < i)
{
sum += ++j;
printf(" = %lu", sum);
}
printf("\n");
return 0;
}

試試看 :使用do-while 循環(huán)
使用do-while循環(huán),將一個正整數(shù)中的數(shù)字的順序翻轉(zhuǎn)過來:

//program 4.12 Reversing the digits
#include <stdio.h>

int main(void)
{
    unsigned int number = 0;
    unsigned int rebmun = 0;
    unsigned int temp = 0;

    printf("\nEnter a positive integer: ");
    scanf( " %u", &number);

    temp = number;

   do
   {
       rebmun =10*rebmun  +temp % 10;
       temp = temp/10;
   }while(temp);
   printf("\nThe number %u reversed is %u rebmun        ehT\n,number, rebmun);
   return 0;
}

問題:
編寫一個簡單的Simon游戲槐脏,這是一個記憶測試游戲喉童。
計算機(jī)會在屏幕上將一串?dāng)?shù)字顯示很短的時間。玩家必須在數(shù)字消失之前記住他們顿天,然后輸入這串?dāng)?shù)字泄朴。每次過關(guān)后,計算機(jī)會顯示更長的一串?dāng)?shù)字露氮,讓玩家繼續(xù)玩下去。玩家應(yīng)盡可能使這個過程重復(fù)更多的次數(shù)钟沛。
分析:
1畔规、必須產(chǎn)生一連串的0~9的數(shù)字,(如何生成隨機(jī)數(shù))
2恨统、顯示在屏幕上(如何延遲一秒)
3叁扫、刪除數(shù)字串(如何刪除隨機(jī)數(shù))
4、玩家輸入數(shù)字串(如何判斷玩家輸入的數(shù)字串是否正確)
如何創(chuàng)建和檢查數(shù)字串
(1)數(shù)字串顯示限定的時間
(2)用于檢查玩家的輸入

5畜埋、如果玩家輸入了正確的數(shù)字串莫绣,程序會顯示更長的數(shù)字串直到玩家出入錯位u為止
6、根據(jù)成功的次數(shù)和所花的時間來記分悠鞍。
7对室、程序會詢問是否繼續(xù)玩?

變量的含義:
tries 記錄玩家成功的次數(shù)
digits 的值是正確輸入的數(shù)字串的長度
total_digit的值也是所有數(shù)字輸入需要的標(biāo)準(zhǔn)時間
game_time
start_time : 游戲開始的時間
score 游戲分?jǐn)?shù)
clock()函數(shù)返回啟動程序到當(dāng)前的時間

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

int main()
{
    char another_game = 'Y';
    const unsigned int DELAY = 1;
    /*More variable declaration for the program */
    bool correct = true;
    unsigned int tries = 0;//記錄玩家成功的次數(shù)
    unsigned int digits = 0;//記錄當(dāng)前數(shù)字串的長度
    time_t seed = 0;
    unsigned int number = 0;
    time_t wait_start = 0; //存儲當(dāng)前的時間
    clock_t start_time = 0;
    unsigned int score = 0;
    unsigned int total_digits = 0;
    unsigned int game_time = 0;

    //descriable how the game is palyed 
    printf("請在屏幕上顯示一串字符:");
    printf("顯示1s");
    printf("刪除字符串");
    printf("用戶輸入次數(shù)");
    printf("用成功的次數(shù)和時間計算分?jǐn)?shù)");


    //Game loop - one outer loop iteration is a complete game
    do
    {
        correct = true;
        tries = 0;
        digits = 2;//以確保每次游戲設(shè)置正確的初始條件
        start_time = clock();
        /*Initialize a game */


        /* Inner  loop to play the game   */
        while (correct)
        {
            ++tries;
            wait_start = clock();//返回從啟動程序到當(dāng)前的時間咖祭,單位tick

            //生成序列數(shù)并顯示在屏幕上
            srand(time(&seed));  //初始化隨機(jī)序列
            for (unsigned int i = 1; i <= digits; ++i)
                printf("%d", rand() % 10); //輸出隨機(jī)數(shù)
            /*code to wait one second */

            for(; clock()- wait_start < DELAY*CLOCKS_PER_SEC ;)//一秒有多少tick

            /* code to overwriter the digit sequence*/
            printf("\r");
            for (unsigned int i = 1; i <= digits; ++i);
            printf(" ");

            if (tries == 1)
                printf("\nNow you enter the sequence - don't forget the spaces\n");
            else
                printf("\r");
            /* code to prompt for the  input sequence*/

            srand(seed);
            for (unsigned int i = 1; i <= digits; ++i)
            {
                scanf("%u",&number);
                if (number != rand() % 10)
                {
                    correct = false;
                    break;
                }
            }
            if (correct && ((tries % 3) == 0))
                ++digits;
            printf("%s\n",correct ? "Correct!" :"Wrong!");


        }

        /* Output the score when a game is finished *///記分時要反映成功輸入的最長字符串的長度和多花的世間
        score = 10 * (digits - ((tries % 3) == 1));
        total_digits = digits*(((tries % 3) == 0) ? 3 : tries % 3);

        if (digits > 2)
        {
            total_digits += 3 * ((digits - 1)*(digits - 2) / 2 - 1);
        }
        game_time = (clock() - start_time) / CLOCKS_PER_SEC - tries*DELAY;
        
        if (total_digits > game_time)
            score += 10 * (game_time - total_digits);
        printf("\n\nGame time was %u seconds,Your score is %u",game_time,score);
        
        fflush(stdin);

        //Check if a new  game is required
        printf("\nDo you want to paly again(y/n)");
        scanf("%c",&another_game);
    } while (toupper(another_game) == 'Y');
    return 0;

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末掩宜,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子么翰,更是在濱河造成了極大的恐慌牺汤,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件浩嫌,死亡現(xiàn)場離奇詭異檐迟,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)码耐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門追迟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人伐坏,你說我怎么就攤上這事怔匣。” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵每瞒,是天一觀的道長金闽。 經(jīng)常有香客問我,道長剿骨,這世上最難降的妖魔是什么代芜? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮浓利,結(jié)果婚禮上挤庇,老公的妹妹穿的比我還像新娘。我一直安慰自己贷掖,他們只是感情好嫡秕,可當(dāng)我...
    茶點故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著苹威,像睡著了一般昆咽。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上牙甫,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天掷酗,我揣著相機(jī)與錄音,去河邊找鬼窟哺。 笑死泻轰,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的且轨。 我是一名探鬼主播浮声,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼殖告!你這毒婦竟也來了阿蝶?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤黄绩,失蹤者是張志新(化名)和其女友劉穎羡洁,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體爽丹,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡筑煮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了粤蝎。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片真仲。...
    茶點故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖初澎,靈堂內(nèi)的尸體忽然破棺而出秸应,到底是詐尸還是另有隱情虑凛,我是刑警寧澤,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布软啼,位于F島的核電站桑谍,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏祸挪。R本人自食惡果不足惜锣披,卻給世界環(huán)境...
    茶點故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望贿条。 院中可真熱鬧雹仿,春花似錦、人聲如沸整以。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽公黑。三九已至票顾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間帆调,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工豆同, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留番刊,地道東北人。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓影锈,卻偏偏與公主長得像芹务,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子鸭廷,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容

  • FreeCodeCamp - Basic JavaScript 寫在前面: 我曾經(jīng)在進(jìn)谷前刷過這一套題枣抱,不過當(dāng)時只...
    付林恒閱讀 16,443評論 5 28
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法辆床,內(nèi)部類的語法佳晶,繼承相關(guān)的語法,異常的語法讼载,線程的語...
    子非魚_t_閱讀 31,632評論 18 399
  • Comment your JavaScript Code JavaScript中的注釋方式有以下兩種: 使用 //...
    歸云丶閱讀 1,103評論 0 0
  • 說道香港電影反派演員的話,我們會想起烏鴉張耀揚(yáng)一喘、四大惡人等等驱还,內(nèi)地演員中有誰可以和烏鴉匹敵呢,大圣認(rèn)為計春華老師當(dāng)...
    電影聚焦閱讀 762評論 1 5
  • 美術(shù)課的時候闷沥,林希把往日打游戲的習(xí)慣改成刷QQ空間,她已經(jīng)好些日子不玩QQ了咪鲜。 某同學(xué)的一條找兼職的動態(tài)很多人評論...
    度南夕閱讀 450評論 4 1