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

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

#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ù)字猜謎游戲

這個程序要求用戶猜測該程序挑選出來的幸運(yùn)數(shù)字。它使用了一個for循環(huán)和多個if語句。還加進(jìn)了條件運(yù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ù)的程序?yàn)榛A(chǔ)。原來的程序是計算從1到輸入值之間的所有整數(shù)的和?,F(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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容