设计 任务书 文档 开题 答辩 说明书 格式 模板 外文 翻译 范文 资料 作品 文献 课程 实习 指导 调研 下载 网络教育 计算机 网站 网页 小程序 商城 购物 订餐 电影 安卓 Android Html Html5 SSM SSH Python 爬虫 大数据 管理系统 图书 校园网 考试 选题 网络安全 推荐系统 机械 模具 夹具 自动化 数控 车床 汽车 故障 诊断 电机 建模 机械手 去壳机 千斤顶 变速器 减速器 图纸 电气 变电站 电子 Stm32 单片机 物联网 监控 密码锁 Plc 组态 控制 智能 Matlab 土木 建筑 结构 框架 教学楼 住宅楼 造价 施工 办公楼 给水 排水 桥梁 刚构桥 水利 重力坝 水库 采矿 环境 化工 固废 工厂 视觉传达 室内设计 产品设计 电子商务 物流 盈利 案例 分析 评估 报告 营销 报销 会计
 首 页 机械毕业设计 电子电气毕业设计 计算机毕业设计 土木工程毕业设计 视觉传达毕业设计 理工论文 文科论文 毕设资料 帮助中心 设计流程 
垫片
您现在所在的位置:首页 >>毕设资料 >> 文章内容
                 
垫片
   我们提供全套毕业设计和毕业论文服务,联系微信号:biyezuopin QQ:2922748026   
如何使用for、while和do-while循环(译文及原文)
文章来源:www.biyezuopin.vip   发布者:毕业作品网站  

译文:

循环

上一章学习了如何比较数据项,并根据其结果进行判断。我们可以根据程序的输入选择计算机如何做出反应。本章将介绍如何重复执行一个语句块,直到满足某个条件为止,这称为循环。

语句块的执行次数可以简单地用一个计数器来控制,语句块重复执行指定的次数,或者还可以更复杂一些,重复执行一个语句块,直到满足某个条件为止,例如用户输入quit。后者可以编写上一章的计算器示例,使计算过程重复需要的次数,而不必使用goto语句。

在这一章你会学到如下:

•如何使语句或语句块重复执行指定的次数

•如何重复执行语句或语句块,直到满足某个条件为止

•如何使用for、while和do-while循环

•递增和递减运算符的作用,以及你如何使用它们

•编写一个简单的Simon游戏程序

循环工作原理

如之前所讲述,使一系列语句重复执行指定的次数,或重复执行它们,直到满足某个条件为止的编程机制称为循环。循环和比较数据项是基本的编程工具。能比较数据值和重复执行语句块后,就可以合并这两个功能,控制语句块的执行次数。例如,可以重复执行一个操作,直到比较的两个数据项相同为止。当它们相同时,就可以执行另一个操作。

在第3章的程序3.8中,抽奖示例允许用户猜3次,换而言之,可以让用户继续猜测,直到number_of_guesses变量等于3为止。这就涉及一个循环,它重复执行代码,从键盘上读取猜测的数字,检查输入值的准确性。图4-1显示了循环的工作过程。

我们要经常对不同的数据值应用相同的计算。没有循环,那么要处理多少组数据值,就必须重复编写多少组相同的指令,这是非常繁琐的。循环可以使用相同的程序码,处理输入的任何多个数据。

图 4-1   循环的工作过程

在讨论C语言中的各种循环之前,首先介绍C程序中常见的两个新算术运算符:递增运算符和递减运算符。这两个运算符经常用在循环中,这就是在这里讨论它们的原因。我们先简要介绍递增运算符和递减运算符,再用一个例子说明如何在循环中使用它们。在能灵活运用循环后,再回过头来了解递增运算符和递减运算符的一些特质。

介绍递增运算符和递减运算符

递增运算符(++)和递减运算符(--)会将存储在整数变量中的值递增或递减1。假设定义了一个整数变量number,该值当前数值为6。可以用以下语句将其增加1:

++number;                     /* Increase the value by 1*/

执行完这个语句后,number的数值是7。同样地,可以用以下语句来给number的数值减1:

--number;                    /* Decrease the value by 1 */

这些运算符和前面介绍的其他算术运算符不一样。使用其他算术运算符时,会创建一个表达式,其计算结果为一个数值,该数值存储在一个变量中,或用作复杂表达式的一部分。它们不直接更改变量存储的数值。假如number的数值是+6,则表达式-number的结果是-6,但是存储在number中的数值不会改变。而表达式--number会更改number的数值,这个表达式将number的数值减1,所以number的结果是5。

递增和递减运算符还有更多需要了解的内容,这些将在后面讨论。现在回到主题,看看最简单的循环——for循环。以后还会介绍其他类型的循环,这里用较多的篇幅介绍for循环,因为理解了这个循环,其他的循环就容易掌握了。

for 循环

使用for循环的基本形式可以使语句块重复执行指定的次数。假设要显示1~10之间的数字,可以不用编写10条printf()语句,而可以这么写:

int count;

for (count=1; count<=10; ++count)

printf(“\n%d”, count);

for循环的操作由关键字for后面括号中的内容控制。如图4-1所示。每次重复执行循环时,都需要执行关键字for所在的第一行后面的语句。这里只有一条语句,但这和放在括号中的语句块是一样的。

图4-2说明了3个由分号分开的控制表达式,它们控制循环的执行。每个控制表达式的作用如图4-2所示,下面详细讨论循环执行的过程。

图4-2   for循环的控制表达式

•第一个控制表达式在循环开始时执行,且只执行一次。在这个例子,第一个表达式设定一个变量count为1。这个表达式是count=1。

•第二个控制表达式必须是一个逻辑表达式,其结果为true或false;在这个例子,它是count<=10。第二个表达式在每次循环迭代开始重复前计算。如果结果是true,循环就继续;否则,循环就结束,程序继续执行循环块或循环语句后面第一个语句。false是0,而不为零值是true,所以只要count小于或等于10,这个循环例子就会执行printf()语句。当count等于11时,循环就结束了。

•第三个控制表达式++count在每一次循环迭代结束时执行。这里使用递增运算符给count的值加1:在第一次迭代时,count是1,所以printf()输出1。第二次迭代时,count的值递增为2,所以printf()输出数值2...一直到显示值10为止。在开始下一个迭代时,count的值递增到11,而第二个控制表达式的结果是法律色,因此循环结束。

注意标点符号。for循环的控制表达式包含在括号内,每个表达式用分号隔开。这些控制表达式均可以省略,但必须保留分号。例如,在循环外声明变量count并初始化为1:

int count = 1;

现在不需要指定第一个控制表达式,for循环如下所示:

for(; count <= 10; ++count)

printf(“\n%d”, count);

在下面的小例子中,添加几行代码,把这个循环添加到一个真实的程序中:

/* Program 4.1 List ten integers */

#include <stdio.h>

int main(void)

{

int count = 1;

for( ; count <= 10 ; ++count)

printf(“\n%d”, count);

printf(“\n We have finished.\n”);

return 0;

}

这个程序将1~10的数字显示在不同的行上,接着输出如下信息:

We have finished.

图4-3中的流程图说明了这个程序的逻辑。

图4-3   程序4.1的逻辑

在这个例子中,很容易看出变量count的起始点,所以这个代码没什么问题。但通常情况下,除非控制循环的变量非常靠近循环语句,否则最好在第一个控制表达式中初始化它。这样可以避免潜在的错误。也可以在第一个控制表达式中声明循环变量,此时该变量是循环的本地变量,循环结束后它就不存在了。main()函数可以编写如下:

int main(void)

{

for (int count = 1; count <= 10; ++count)

printf(“\n%d”, count);

printf(“\nWe have finished.\n”);

return 0;

}

count在第一个for循环表达式中声明。这说明,count在循环结束后就不存在了,所以不能再循环结束后输出它的值。如果需要在循环的外部访问循环控制变量,就应在循环前面的一个语句中声明它,如程序4-1所示。

下面是一个略有不同的示例。

试试看:绘制一个盒子

假设要在屏幕上使用字符*绘制一个盒子。可以多次使用printf()语句,但输入量很大。而使用for循环来绘制就容易多了。代码如下:

/* Program 4.2 Drawing a box */

#include <stdio.h>

int main(void)

{

printf(“\n**************”);           /* Draw the top of the box */

for(int count = 1; count <=8; ++count)

printf(“/n*            *”);          /* Draw the sides of the box */

printf(“\n**************\n”);       /* Draw the bottom of the box */

return 0;

}

这个程序的输出如下:

代码的说明

这个程序相当简单。第一条printf()语句在屏幕上输出盒子的第一行:

printf(“\n**************”);  /* Draw the top of the box */

下一条语句是for循环:

for(int count = 1; count <=8; ++count)

printf(“/n*          *”); /* Draw the sides of the box */

这里printf()语句重复了8次,输出盒子的侧面。下面用专业术语来解释其执行过程。循环控制如下:

for(int count = 1; count <=8; ++count)

循环的执行由关键字for后面括号中的3个表达式来控制。第一个表达式是:

int count = 1

这条语句创建并初始化了循环控制变量(或循环计数器),在这个例子中,循环控制变量是整数变量count。可以使用其他类型的变量,但是整数类型比较方便。下一个循环控制表达式是:

count <= 8

这是循环的继续条件。在每次循环迭代之前都要检查这个条件,确定循环是否应继续。如果该表达式是true,循环就继续。否则,就结束循环,程序将继续执行循环后面的语句。在这个例子中,只要count变量小于等于8,循环就继续。最后一个表达式是:

++count

这条语句在每一次循环迭代结束时,递增循环计数器的值。因此,输出盒子侧面的循环语句会执行8次。迭代8次后,变量count的值递增为9,循环继续的条件是false,所以循环结束。

程序继续执行循环后面的语句:

printf(“\n**************\n”);       /* Draw the bottom of the box */

这条语句在屏幕上输出盒子的底部。

注意:

只要需要多次重复执行某个语句块,就应使用循环,这通常可以节省时间和内存。

外文原文:

Loops

In the last chapter you learned how to compare items and base your decisions on the result. You were able to choose how the computer reacted based on the input to a program. In this chapter, you’ll learn how you can repeat a block of statements until some conditions is met. This is called a loop.

The number of times that a loop is repeated can be controlled simply by a count—repeating the statement block a given number of times—or it can be more complex—repeating a block until some condition is met, such as the user entering quit, for instance. The latter would enable you to program the calculator example in the previous chapter to repeat as many times as required without having to use a goto statement.

In this chapter, you’ll learn the following:

•How you can repeat a statement, or a block of statements, as many times as you want

•How you can repeat a statement or a block of statements until a particular condition is fulfilled

•How you use the for, while, and do-while loops

•What the increment and decrement operators do, and how you can use them

•How you can write a program that plays a Simple Simon game

How Loops Work

As I said, the programming mechanism that executes a series of statements repeatedly a given number of times, or until a particular condition is fulfilled, is called a loop. The loop is a fundamental programming tool, along with the ability to compare items. Once you can compare data values and repeat a block of statements, you can combine these capabilities to control how many times the block of statements is executed. For example, you can keep performing a particular action until two items that you are comparing are the same. Once they are the same, you can go on to perform a different action.

In the lottery example in Chapter 3 in Program 3.8, you could give the user exactly three guesses—in other words, you could let him continue to guess until a variable called number_of_guesses, for instance, equals 3. This would involve a loop to repeat the code that reads a guess from the keyboard and checks the accuracy of the value entered. Figure 4-1 illustrates the way a typical loop would work in this case.

More often than not, you’ll find that you want to apply the same calculation to different sets of data values. Without loops, you would need to write out the instructions to be performed as many times as there were sets of data values to be processed, which would not be very satisfactory. A loop allows you to use the same program code for any number of sets of data to be entered.

Figure 4-1. Logic of a typical loop

Before I discuss the various types of loops that you have available in C, I’ll first introduce two new arithmetic operators that you’ll encounter frequently in C programs: the increment operator and the decrement operator. These operators are often used with loops, which is why I’ll discuss them here. I’ll start with the briefest of introductions to the increment and decrement operators and then go straight into an example of how you can use them in the context of a loop. Once you’re comfortable with how loops work, you’re return to the increment and decrement operators to investigate some of their idiosyncrasies.

Introducing the Increment and

Decrement Operators

The increment operator (++) and the decrement operator (--) will increment or decrement the value stored in the integer variable that they apply to by 1. Suppose you have defined an integer variable, number, that currently has the value 6. You can increment it by 1 with the following statements:

++number;                             /* Increase the value by 1 */

After executing this statement, number will contain the value 7. Similarly, you could decrease the value of number by one with the following statement:

--number;                             /* Decrease the value by 1 */

These operators are different from the other arithmetic operators you have encountered. When you use any of the other arithmetic operators, you create an expression that will result in a value, which may be stored in a variable or used as part of a more complex expression. They do not directly modify the value stored in a variable. When you write the expression-number, for instance, the result of evaluating this expression is 6 if number has the value +6, but the value stored in number is unchanged. On the other hand, the expression –number does modify the value in number. This expression will decrement the value in number by 1, so number will end up as 5 if it was originally 6.

There’s much more you’ll need to know about the increment and decrement operators, but I’ll defer that until later. Right now, let’s get back to the main discussion and take a look at the simplest form of loop, the for loop. There are other types of loops as you’ll see later, but I’ll give the for loop a larger slice of time because once you understand it the will be easy.

The for Loop

You can use the for loop in its basic form to execute a block of statements a given number of times. Let’s suppose you want to display the numbers from 1 to 10. Instead of writing ten printf() statements, you could write this:

int count;

for (count=1; count<=10; ++count)

printf(“\n%d”, count);

The for loop operation is controlled by the contents of the parentheses that follow the keyword for. This is illustrated in Figure 4-2. The action that you want to repeat each time the loop repeats is the statement immediately following the first line that contains the keyword for. Although you have just a single statement here, this could equally well be a block of statements between braces.

Figure 4-2 shows the three control expressions that are separated by semicolons and that control the operation of the loop.

Figure 4-2. Control expressions in a for loop

The effect of each control expression is shown in Figure 4-2, but let’s take a much closer look at exactly what’s going on.

•The first control expression is executed only once, when the loop starts. In the example, the first expression sets a variable, count, to 1. This is the expression count = 1.

•The second control expression must be a logical expression that produces a result of true or false; in this case, it’s the expression count <= 10. The second expression is evaluated before each loop iteration starts. If the expression evaluates to true, the loop continues, and if it’s false, the loop ends and execution of the program continues with the first statement following the loop block or loop statement. Remember that false is a zero value, and any nonzero value is true. Thus, the example loop will execute the printf() statement as long count is less than or equal to 10. The loop will end when count reaches 11.

•The third control expression, ++count in this case, is executed at the end of each iteration. Here you use the increment operator to add 1 to the value of count. On the first iteration, count will be 1, so the printf() will output 1. On the second iteration, count will have been incremented to 2, so the printf() will output the value 2. This will continue until the value 10 has been displayed. At the start of the next iteration, count will be incremented to 11, and because the second control expression will then be false, the loop will end.

Notice the punctuation. The for loop control expressions are contained within parentheses, and each expression is separated from the next by a semicolon. You can omit any of the control expressions, but if you do you must still include the semicolon. For example, you could declare and initialize the variable count to 1 outside the loop:

int count = 1;

Now you don’t need to specify the first control expression at all, and the for loop could look like this:

for(; count <= 10; ++count)

printf(“\n%d”, count);

As a trivial example, you could make this into a real program simply by adding a few lines of code:

/* Program 4.1 List ten integers */

#include <stdio.h>

int main(void)

{

int count = 1;

for( ; count <= 10 ; ++count)

printf(“\n%d”, count);

printf(“\n We have finished.\n”);

return 0;

}

This program will list the numbers from 1 to 10 on separate lines and then output this message:

The flow chart in Figure 4-3 illustrates the logic of this program.

Figure 4-3. The logic of Program 4.1

In this example, it’s easy to see what the variable count starts out as, so this code is quite OK. In general, though, unless the variable controlling the loop is initialized very close to the loop statement itself, it’s better to initialize it in the first control expression. That way, there’s less potential for error.

You can also declare the loop variable within the first loop control expression, in which case the variable is local to the loop and does not exist once the loop has finished. You could write the main () function like this:

int main(void)

{

for (int count = 1; count <= 10; ++count)

printf(“\n%d”, count);

printf(“\nWe have finished.\n”);

return 0;

}

Now count is declared within the first for loop expression. This means that count does not once the loop ends, so you could not output its value after the loop. when you really do need access to the loop control variable outside the loop, you just declare it in a separate statement preceding the loop, as in Program 4.1.

Let’s try a slightly different example.

TRY IT OUT: DRAWING A BOX

Suppose that you want to draw a box on the screen using * characters. You could just use the printf() statement a lot of times, but the typing would be exhausting. You can use a for loop to draw a box much more easily. Let’s try it:

/* Program 4.2 Drawing a box */

#include <stdio.h>

int main(void)

{

printf(“\n**************”);            /* Draw the top of the box */

for(int count = 1; count <=8; ++count)

printf(“/n*            *”);       /* Draw the sides of the box */

printf(“\n**************\n”);       /* Draw the bottom of the box */

return 0;

}

No prizes for guessing, but the output for this program looks like this:

How It Works

The program itself is really very simple. The first printf() statement outputs the top of the box to the screen:

printf(“\n**************”);            /* Draw the top of the box */

The next statement is the for loop:

for(int count = 1; count <=8; ++count)

printf(“/n*            *”);       /* Draw the sides of the box */

This repeats the printf() statement eight times to output the sides of the box. You probably understand this, but let’s look again at how it works and pick up a bit more jargon. The loop control is the following:

for(int count = 1; count <=8; ++count)

The operation of the loop is controlled by the three expressions that appear between the parentheses following the keyword for. The first expression is the following:

int count = 1

This creates and initializes the loop control variable, or loop counter, which in this case is an integer variable, count. You could have used other types of variables for this, but integers are convenient for the job. The next loop control expression is the following:

count <= 8

This is the continuation condition for the loop. This is checked before each loop iteration to see whether the loop should continue. If the expression is true, the loop continues. If it’s false, the loop ends and execution continues with the statement following the loop. In this example, the loop continues as long as the variable count is less than or equal to 8. The last expression is the following:

++count

This statement increments the loop counter at the ends of each loop iteration. The loop statement that outputs the sides of the box will therefore be executed eight times. After the eighth iteration, count will be incremented to 9 and the continuation condition will be false, so the loop will end.

Program execution will then continue by executing the statement that follows the loop:

printf(“\n**************\n”);       /* Draw the bottom of the box */

This outputs the bottom of the box on the screen.

Tip Whenever you find yourself repeating something more than a couple of times, it’s worth considering a loop. They’ll usually save you time and memory.

  全套毕业设计论文现成成品资料请咨询微信号:biyezuopin QQ:2922748026     返回首页 如转载请注明来源于www.biyezuopin.vip  

                 

打印本页 | 关闭窗口
本类最新文章
高速离心式果汁机的结构设计 评阅 离心式榨汁机机械结构设计 任务书 风力发电增速齿轮箱设计 任务书
小型甘蔗打包机的设计 开题报告 小型甘蔗打包机的设计 文献综述 基于Spring Boot的助老
| 关于我们 | 友情链接 | 毕业设计招聘 |

Email:biyeshejiba@163.com 微信号:biyezuopin QQ:2922748026  
本站毕业设计毕业论文资料均属原创者所有,仅供学习交流之用,请勿转载并做其他非法用途.如有侵犯您的版权有损您的利益,请联系我们会立即改正或删除有关内容!