⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 loopexit.txt

📁 c语言开发方面的经典问题,包括源代码.c语言开发所要注意的问题,以及在嵌入式等各方面的应用
💻 TXT
📖 第 1 页 / 共 2 页
字号:
I have looked for other studies that might contradict the findings ofthe Soloway study.  Although I have found authors who assert that theuse of internal loop exits is wrong, I have encountered none thatsupport their claims with objective evidence.It is also possible to use standard Pascal texts as evidence that theread/process strategy in fact corresponds to student intuition.  Anexamination of at the approach used to solve the read-until-sentinelproblem in the five best-selling Pascal textbooks [Cooper92, Dale92,Koffman91, Leestma87, Savitch91] reveals that:   o  In each of the textbooks, the problem is solved by unwinding      the loop so that the read phase of the operation occurs twice:      once prior to the loop and once at the end of the loop body.   o  In every text except Leestma and Nyhoff, the authors derive      their solution by first presenting the read/process strategy      and subsequently modifying it to fit the process/read form      required by Pascal's control structures.To me, the approach these authors take suggests that they themselvesaccept that students find the read/process strategy more intuitive.  Toencourage students to write programs that fit Pascal's restrictions,these texts teach them -- often at great length -- to abandon theirinitial strategy in favor of one that reverses the order of theoperations within the loop.  My own classroom experience certainlysupports this conclusion.  By introducing loop exits and using theread/process strategy, I find that I can save almost an entire day'slecture.The concern, of course, about introducing an internal loop exit form isthat students will end up abusing it, since it is certainly possible todo so.  Our experience at Stanford, however, suggests that this problemdoes not in fact arise.  Students tend to write code based on the modelsthey are given, using internal loop exits only in the disciplined wayoutlined in the class examples.  In the last three years, over 2500students have completed CS1 at Stanford, and the teaching assistantshave reported no problems with overuse of the break construct.  Thisfinding is consistent with the results of a study by Sheppard, whichdemonstrated that internal loop exits do not in fact compromise programreadability [Sheppard79].4.  SEQUENTIAL SEARCHIn addition to encouraging the use of an internal loop exit to solve theloop-and-a-half problem, I also teach students that it is appropriate touse a return statement at any point in a function where the result valuebecomes known, even if the return statement is nested in such a way thatit acts as a nonstandard exit from an enclosing control structure.  Theparadigmatic example that underscores the value of this technique is thesequential search problem.In essence, the sequential search problem consists of writing animplementation for the following function header line:          function Search(var list: IntList;                          n, key: integer) : integer;The parameter list is an array of integers that conforms to the Pascaltype definition          type            IntList = array [1..MaxList] of integer;where MaxList is some constant upper bound on the list size.  The actualnumber of elements actively stored in the array is typically smaller andis given by the parameter value n.  The problem is to implement Searchin such a way that it returns the least index i for which list[i] isequal to key; if the value key does not appear in list, the functionSearch should return 0.  Functions that have this basic structure comeup frequently in programming, even at the introductory level.If the language includes an active return statement, such as the oneprovided by C, Modula-2, or Ada, the Search function has the followingconcise and natural implementation:          function Search(var list: IntList;                          n, key: integer) : integer;          var            i: integer;          begin            for i := 1 to n do              if list[i] = key then return i;            return 0          end;If students are restricted to the facilities available in StandardPascal, the Search function, as simple and as fundamental as it is,turns out to be extremely hard to code -- so difficult in fact that manyof them are incapable of developing a correct solution.  If you haven'tencountered this problem, it is worth spending a few minutes to writethe code on your own.The difficulty of coding the sequential search algorithm was describedin 1980 in an insightful paper by Henry Shapiro that never received theattention it deserved.  The statistics he reports are far moreconclusive than those in the Soloway study of internal loop exits.  Ofthe students in his study who attempted to use the for loop strategy,all of them managed to solve the problem correctly, even though theywere forced to use a goto statement to achieve the effect of the returnstatement in the preceding example.  In fact, Shapiro notes that      I have yet to find a single person who attempted a program      using [this style] who produced an incorrect solution.Students who attempted to solve the problem without using an explicitreturn from the for loop fared much less well: only seven of the 42students attempting this strategy managed to generate correct solutions.That figure represents a success rate of less than 20% [Shapiro80].That students would have difficulty in developing a general solution tothis problem is not really surprising.  When they are limited toPascal's control structures, the answer is quite complicated.  To seejust how complicated the solutions can get, it is again useful toconsider how the leading Pascal texts handle the problem.The following code, adapted from the solution given on page 300 ofLeestma and Nyhoff [Leestma87], illustrates that a correct solution isindeed possible:          function Search(var list: IntList;                          n, key: integer) : integer;          var            i: integer;            found: boolean;          begin            i := 1;            found := FALSE;            while (i <= n) and not found do              if list[i] = key then                found := TRUE              else                i := i + 1;            if found then              Search := i            else              Search := 0          end;This solution introduces a Boolean variable and uses 11 lines of code todo the work accomplished by three in the solution based on the returnstatement.  It does, however, return the correct result.  The Dale andWeems text [Dale92] uses a slight variation of this strategy that alsoreturns the correct result.The other leading Pascal texts adopt a different approach.  The codesuggested independently by Cooper, Koffman, and Savitch [Cooper92,Koffman91, Savitch91] has the following general form:          function Search(var list: IntList;                          n, key: integer) : integer;          var            i: integer;          begin            i := 1;            while (i < n) and (list[i] <> key) do              i := i + 1;            if list[i] = key then              Search := i            else              Search := 0          end;These authors have taken great pains to avoid some of Pascal's pitfalls.The bounds test for the while loop specifies continuation only if i < n,even though the test i <= n might seem more natural in this context.The problem with the test i <= n is that Pascal's handling of the andoperator can generate a subscript violation if n is equal to MaxList.On the last cycle, Pascal evaluates both halves of the condition andtherefore evaluates list[i] even if it has already determined thati > n.  Fixing this problem also requires that the test in the ifstatement check the element value and not the value of the index.Unfortunately, this change in the final test introduces a new problem:the function can fail if n is 0.  As written, the implementation teststhe first element in the array against the key even if the array has noactive elements.In fairness to the authors, it is important to point out that theoriginal examples are not in fact buggy in the strictest sense.  Koffmanspecifically rules out the possibility that n is 0 in the preconditionsof the function, although this relationship is not tested within theimplementation.  In both Cooper and Savitch, the upper bound is aconstant rather than a variable.  Since the constant is not declared tobe zero, the problem does not actually arise.  Even so, the importantpoint is that the coding from these texts cannot be considered as anappropriate model for a general-purpose search function.  A studenttrying to solve the general case might well do exactly what I did: gothrough the functions and replace the constant bound with thecorresponding variable.  At that point, the implementation fails.The conclusion that the sequential search problem is difficult forstudents who use the Pascal strategy is strongly supported by ourexperience at Stanford.  When we taught the introductory course inPascal, we worked hard to present the sequential search algorithm in acareful and rigorous way that would ensure correct operation inspecial-case situations.  Despite that care, we discovered that even ourbest students had trouble regenerating the solution after taking thecourse.  The situation is entirely different now that we use a returnstatement to implement the sequential search algorithm.  Students whomanage to understand arrays at all understand the sequential searchalgorithm immediately; it no longer represents a source of difficulty.5.  CONCLUSIONSWhen students are limited to the control structures available in Pascal,they tend to have significant difficulty solving certain programmingproblems that come up frequently in practical applications.  Allowingstudents to use control forms that provide a structured mechanism forloop exit increases their comprehension along with their ability towrite correctly functioning code.  Although these facilities are absentfrom Pascal, they are widely available in modern programming languagesand should be introduced when those languages are used in aninstructional setting.To a significant extent, the discipline that Pascal encouraged has had apositive effect on the computer science curriculum.  As we move to newprogramming languages, however, it is crucial to analyze our experienceto determine what aspects of traditional practice are predicated more onthe particular nature of Pascal than on some more general principle.  Ifour programming methodology can be defended on its own merits, we shouldcontinue to support it.  On the other hand, if our students are unableto write correct code using the existing paradigms, we must reevaluatethem.  As Dijkstra observed, "the tools we use have a profound (anddevious!) influence on our thinking habits, and, therefore, on ourthinking abilities" [Dijkstra82].  As we adopt new tools, we must beready to think in new ways.REFERENCES[Boehm66] C. Boehm and G. Jacopini, "Flow diagrams, Turing machines, andlanguages with only two formation rules," Communications of the ACM, May1966.[Cooper92] Doug Cooper, Oh! Pascal! Turbo Pascal 6.0 (third edition),New York: Norton, 1992.[Dahl72] Ole Johan Dahl, Edsger W. Dijkstra, and C.A.R.  Hoare,Structured Programming, London: Academic Press, 1972.[Dale92] Nell Dale and Chip Weems, Turbo Pascal (third edition),Lexington, MA: D.C. Heath, 1992.[Dijkstra68] Edsger W. Dijkstra, "Goto statement considered harmful,"letter to the editor, Communications of the ACM, March 1968.[Dijkstra82] Edsger W. Dijkstra, "How do we tell truths that mighthurt," SIGPLAN Notices, March 1982.[Knuth74] Donald Knuth, "Structured programming with goto statements,"Computing Surveys, December 1974.[Koffman91] Elliot Koffman with Bruce Maxim, Turbo Pascal (thirdedition), Reading, MA: Addison-Wesley, 1991.[Ledgard75] Henry Ledgard and Michael Marcotty, "A genealogy of controlstructures," Communications of the ACM, November 1975.[Leestma87] Sanford Leestma and Larry Nyhoff, Pascal: Programming andProblem Solving (second edition), New York: Macmillan, 1987.[Roberts93] Eric S. Roberts, "Using C in CS1: Evaluating the StanfordExperience," SIGCSE Bulletin, March 1993.[Roberts95] Eric S. Roberts, The Art and Science of C: A Library-BasedApproach, Reading, MA: Addison-Wesley, 1995.[Savitch91] Walter Savitch, Pascal: An Introduction to the Art andScience of Programming (third edition), Redwood City, CA:Benjamin/Cummings, 1991.[Shapiro80] Henry Shapiro, "The results of an informal study to evaluatethe effectiveness of teaching structured programming," SIGCSE Bulletin,December 1980.[Sheppard79] S. Sheppard, B. Curtis, P. Millman, and J.  Clement,"Modern coding practices and programmer performance," Computer, December1979.[Soloway83] Elliot Soloway, Jeffrey Bonar, and Kate Ehrlich, "Cognitivestrategies and looping constructs: an empirical study," Communicationsof the ACM, Vol.  26, No. 11, November 1983.[Yuen94] C. K. Yuen, "Programming the premature loop exit: fromfunctional to navigational," SIGPLAN Notices, March 1994.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -