如何重复执行一个语句块,直到满足某个条件为之,这称为循环
循环提供了终止循环的方式学习
递增运算符和递减运算符与其他算术运算符相比他们不直接更改变量存储的值
变量只能在声明他后面的语句中存在
递增运算符的前置 ++变量 --变量
递增运算符的后置 变量++ 变量--
#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;//跳出当前的循环||跳出所有的循环
}
}
printf("\n");
}
return 0;
}
使用for循环一般使语句块重复执行指定的次数。干苦力的
//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;
}
试试看:绘制一个盒子
假设要在屏幕上使用字符*绘制一个方框,可以多次使用Printf()语句。但输入量很大,而使用FOR循环来绘制就容易多了。
//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;
}
试试看:数字的总和
这个程序比用*画盒子要有用、有趣的多。假定想知道某条街上所有门牌号的总和是多少,这需要读入最大的门牌号,再使用for循环汇总所有的整数,从1加到输入的那个数值为止。
//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循环
这个例子说明了如何在FOR循环的第3个控制表达式中完成一个计算:
//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循环变量
逆向计算前n个整数的总和
//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 循环
遇到问题不能再是死记硬背,而是理解,不能急,慢慢消化转化为自己的知识
这个例子计算了任意个数字的平均值
//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;
}
试试看:数字猜谜游戏
这个程序要求用户猜测该程序挑选出来的幸运数字。它使用了一个for循环和多个if语句。还加进了条件运算符,提醒读者不要忘记如何使用它。
//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循环
使用while循环编写整数汇总的程序
//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;
}
试试看:使用嵌套的循环
//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;
}
试试看:嵌套循环中的计算
下面的例子已汇总整数的程序为基础。原来的程序是计算从1到输入值之间的所有整数的和。现在要从第一间房子开始。一直到当前的房子为止,计算每间房子的居住人数,看看这个程序的输出,就会比较清楚。
在for 循环里面嵌套了for循环
// 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循环内嵌套while循环
//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 循环
使用do-while循环,将一个正整数中的数字的顺序翻转过来:
//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游戏,这是一个记忆测试游戏。
计算机会在屏幕上将一串数字显示很短的时间。玩家必须在数字消失之前记住他们,然后输入这串数字。每次过关后,计算机会显示更长的一串数字,让玩家继续玩下去。玩家应尽可能使这个过程重复更多的次数。
分析:
1、必须产生一连串的0~9的数字,(如何生成随机数)
2、显示在屏幕上(如何延迟一秒)
3、删除数字串(如何删除随机数)
4、玩家输入数字串(如何判断玩家输入的数字串是否正确)
如何创建和检查数字串
(1)数字串显示限定的时间
(2)用于检查玩家的输入
5、如果玩家输入了正确的数字串,程序会显示更长的数字串直到玩家出入错位u为止
6、根据成功的次数和所花的时间来记分。
7、程序会询问是否继续玩?
变量的含义:
tries 记录玩家成功的次数
digits 的值是正确输入的数字串的长度
total_digit的值也是所有数字输入需要的标准时间
game_time
start_time : 游戏开始的时间
score 游戏分数
clock()函数返回启动程序到当前的时间
#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;//记录玩家成功的次数
unsigned int digits = 0;//记录当前数字串的长度
time_t seed = 0;
unsigned int number = 0;
time_t wait_start = 0; //存储当前的时间
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("用户输入次数");
printf("用成功的次数和时间计算分数");
//Game loop - one outer loop iteration is a complete game
do
{
correct = true;
tries = 0;
digits = 2;//以确保每次游戏设置正确的初始条件
start_time = clock();
/*Initialize a game */
/* Inner loop to play the game */
while (correct)
{
++tries;
wait_start = clock();//返回从启动程序到当前的时间,单位tick
//生成序列数并显示在屏幕上
srand(time(&seed)); //初始化随机序列
for (unsigned int i = 1; i <= digits; ++i)
printf("%d", rand() % 10); //输出随机数
/*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;
}