如何重復(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;
}