1 / 40

Repeating Instructions

6. Repeating Instructions. C# Programming: From Problem Analysis to Program Design 3rd Edition. Part II. For Loop. Pretest form of loop (like the while) Considered specialized form of while statement Usually associated with counter-controlled types

ikia
Télécharger la présentation

Repeating Instructions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 6 Repeating Instructions C# Programming: From Problem Analysis to Program Design 3rd Edition C# Programming: From Problem Analysis to Program Design

  2. Part II C# Programming: From Problem Analysis to Program Design

  3. For Loop • Pretest form of loop (like the while) • Considered specialized form of while statement • Usually associated with counter-controlled types • Packages initialization, test, and update all on one line • General form is: for (statement; conditional expression; statement) statement; • Interpreted as: for (initialize; test; update) statement; C# Programming: From Problem Analysis to Program Design

  4. For Loop (continued) Figure 6-8 Flow of control with a for statement C# Programming: From Problem Analysis to Program Design

  5. For Loop (continued) For loop is executed as shown in the numbered steps Figure 6-9 Step of the for statement C# Programming: From Problem Analysis to Program Design

  6. Comparison of While and For Statement int counter = 0; while (counter < 11) { Console.WriteLine("{0}\t{1}\t{2}", counter, Math.Pow(counter,2), Math.Pow(counter,3)); counter++; } for (int counter = 0; counter < 11; counter++) { Console.WriteLine("{0}\t{1}\t{2}", counter, Math.Pow(counter,2), Math.Pow(counter,3)); } Replace above while loop with for loop below –does same C# Programming: From Problem Analysis to Program Design

  7. For Loop (continued) counter out of SCOPE Figure 6-10 Syntax error C# Programming: From Problem Analysis to Program Design

  8. Ways to Initialize, Test, and Update For Statements • for (int counter = 0, val1 = 10; counter < val1; counter++) • for ( ; counter < 100; counter+=10) // No initialization • for (int j = 0; ; j++) // No conditional expression • for ( ; j < 10; counter++, j += 3) // Compound update • for (int aNum = 0; aNum < 101; sum += aNum, aNum++) ; // Null loop body • for (int j = 0,k = 10; j < 10 && k > 0; counter++, j += 3) C# Programming: From Problem Analysis to Program Design

  9. Ways to Initialize, Test, and Update For Statements (continued) • Floating-point variables can be used • for initialization, expressions, and update for (double d = 15.0; d < 20.0; d += 0.5) { Console.Write(d + “\t”); } • The output produced 15 15.5 16 16.5 17 17.5 18 18.5 19 19.5 C# Programming: From Problem Analysis to Program Design

  10. Ways to Initialize, Test, and Update For Statements (continued) • Can change the loop control variable inside the loop for (double d = 15.0; d < 20.0; d += 0.5) { Console.Write(d + “\t”); d += 2.0 } • The output produced 15 17.5 C# lets you change the conditional expressionendValue inside the loop body– BUT, be careful here C# Programming: From Problem Analysis to Program Design

  11. Foreach Statement • Used to iterate or move through a collection • Array (Chapter 7) • General form • foreach (type identifier in expression) • statement; • Expression is the collection (array) • Type is the kind of values found in the array • Restriction on foreach—cannot change values • Access to the elements is read-only C# Programming: From Problem Analysis to Program Design

  12. Do…While Statements • Posttest • General form do { statement; } while ( conditional expression); Figure 6-12 Do…while loop C# Programming: From Problem Analysis to Program Design

  13. Do…While Example • int counter = 10; • do // No semicolon on this line • { • Console.WriteLine(counter + "\t" + Math.Pow(counter, 2)); • counter--; • } • while (counter > 6); • The output of this code is: • 10 100 • 9 81 • 8 64 • 7 49 C# Programming: From Problem Analysis to Program Design

  14. Nested Loops • Loop can be nested inside an outer loop • Inner nested loop is totally completed before the outside loop is tested a second time int inner; for (int outer = 0; outer < 3; outer++) { for(inner = 10; inner > 5; inner --) { Console.WriteLine("Outer: {0}\tInner: {1}", outer, inner); } } 15 lines printed C# Programming: From Problem Analysis to Program Design

  15. Recursion • Technique where a method calls itself repeatedly until it arrives at the solution • Algorithm has to be developed so as to avoid an infinite loop • To write a recursive solution, an algorithm has to be developed so as to avoid an infinite loop • Have to identify a base case • Base case is the simplest form of the solution C# Programming: From Problem Analysis to Program Design

  16. Recursive Call Figure 6-15 Recursive evaluation of n! C# Programming: From Problem Analysis to Program Design

  17. Unconditional Transfer of Control • Break • Used with switch statement • Place in the body of a loop to provide immediate exit • Be careful (Single Entry/Single Exit) • Continue • When reached, a new iteration of the nearest enclosing while, do…while, for, or foreach statement is started • Other jump statements • goto, throw, and return • Use sparingly C# Programming: From Problem Analysis to Program Design

  18. Deciding Which Loop to Use • Sometimes a personal choice • Body of the do…while always executed at least once • Posttest type • Numeric variable being changed by a consistent amount– for statement • While statement can be used to write any type of loop • Pretest type C# Programming: From Problem Analysis to Program Design

  19. LoanApplication Example Figure 6-16 Problem specification for the LoanApplication example C# Programming: From Problem Analysis to Program Design

  20. LoanApplication Example (continued) C# Programming: From Problem Analysis to Program Design

  21. LoanApplicationExample(continued) Figure 6-17 Prototype for the LoanApplication example C# Programming: From Problem Analysis to Program Design

  22. LoanApplicationExample(continued) Figure 6-18 Class diagrams C# Programming: From Problem Analysis to Program Design

  23. Formulas Used for LoanApplication Example C# Programming: From Problem Analysis to Program Design

  24. Properties for LoanApplication Example C# Programming: From Problem Analysis to Program Design

  25. Pseudocode –Loan Class Figure 6-19 Behavior of Loan class methods C# Programming: From Problem Analysis to Program Design

  26. Pseudocode – LoanApp Class Figure 6-20 Behavior of LoanApp class methods C# Programming: From Problem Analysis to Program Design

  27. Desk Check of LoanApplication Example C# Programming: From Problem Analysis to Program Design

  28. /* Loan.cs * Creates fields for the amount of loan, interest rate, and number of years. * Calculates amount of payment and produces an amortization schedule. */ using System; using System.Windows.Forms; namespace Loan { publicclass Loan { privatedouble loanAmount; privatedouble rate; privateint numPayments; privatedouble balance; privatedouble totalInterestPaid; privatedouble paymentAmount; privatedouble principal; privatedouble monthInterest; Loan class C# Programming: From Problem Analysis to Program Design

  29. // Constructors public Loan( ) { } public Loan(double loan, double interestRate, int years) { loanAmount = loan; if( interestRate < 1) rate = interestRate; else // In case directions aren't followed rate = interestRate / 100; // convert to decimal numPayments = 12 * years; totalInterestPaid = 0; } // Property accessing payment amount publicdouble PaymentAmount { get { return paymentAmount; } } C# Programming: From Problem Analysis to Program Design

  30. // Remaining properties defined for each fields as shown on Slide #50 // Determine payment amount based on number of years, // loan amount, and rate publicvoid DeterminePaymentAmount( ) { double term; term = Math.Pow((1 + rate / 12.0), numPayments); paymentAmount = ( loanAmount * rate / 12.0 * term) / (term - 1.0); } // Returns a string containing an amortization table publicstring ReturnAmortizationSchedule() { string aSchedule = "Month\tInt.\tPrin.\tNew"; aSchedule += "\nNo.\tPd.\tPd.\tBalance\n"; balance = loanAmount; C# Programming: From Problem Analysis to Program Design

  31. for (int month = 1; month <= numPayments; month++) { CalculateMonthCharges(month, numPayments); aSchedule += month + "\t“ + monthInterest.ToString("F") + "\t“ + principal.ToString("F") + "\t" + balance.ToString("C") + "\n"; } return aSchedule; } // Calculates monthly interest and new balance publicvoid CalculateMonthCharges(int month, int numPayments) { double payment = paymentAmount; monthInterest = rate / 12 * balance; C# Programming: From Problem Analysis to Program Design

  32. if (month == numPayments) { principal = balance; payment = balance + monthInterest; } else { principal = payment - monthInterest; } balance -= principal; } // Calculates interest paid over the life of the loan publicvoid DetermineTotalInterestPaid( ) { totalInterestPaid = 0; balance = loanAmount; C# Programming: From Problem Analysis to Program Design

  33. for (int month = 1; month <= numPayments; month++) { CalculateMonthCharges(month, numPayments); totalInterestPaid += monthInterest; } } } } C# Programming: From Problem Analysis to Program Design

  34. /* LoanApp.cs * Used for testing Loan class. Prompts user for input values. * Calls method to display payment amount and amortization * schedule. Allows more than one loan calculation. */ using System; using System.Windows.Forms; namespace Loan { class LoanApp { staticvoid Main( ) { int years; double loanAmount; double interestRate; string inValue; char anotherLoan = 'N'; LoanApp class C# Programming: From Problem Analysis to Program Design

  35. do { GetInputValues(out loanAmount, out interestRate, out years); Loan ln = new Loan(loanAmount, interestRate, years); ln.DeterminePaymentAmount( ); Console.WriteLine( ); Console.WriteLine(ln.ReturnAmortizationSchedule()); ln.DetermineTotalInterestPaid( ); Console.WriteLine("Payment Amount: {0:C}", ln.PaymentAmount); Console.WriteLine("Interest Paid over Life of Loan: " + ln.TotalInterestPaid); Console.Write("Do another Calculation? (Y or N)"); inValue = Console.ReadLine( ); anotherLoan = Convert.ToChar(inValue); } while ((anotherLoan == 'Y')|| (anotherLoan == 'y')); } C# Programming: From Problem Analysis to Program Design

  36. // Prompts user for loan data staticvoid GetInputValues(outdouble loanAmount, outdouble interestRate, outint years) { string sValue; Console.Write("Loan Amount: "); sValue = Console.ReadLine( ); loanAmount = Convert.ToDouble(sValue); Console.Write("Interest Rate (as a decimal value): "); sValue = Console.ReadLine( ); interestRate = Convert.ToDouble(sValue); Console.Write("Number of Years to Finance: "); sValue = Console.ReadLine( ); years = Convert.ToInt32(sValue); } } } C# Programming: From Problem Analysis to Program Design

  37. LoanApplication Example Figure 6-21 LoanApplication output C# Programming: From Problem Analysis to Program Design

  38. Coding Standards • Guidelines for Placement of Curly Braces • Spacing Conventions • Advanced Loop Statement Suggestions C# Programming: From Problem Analysis to Program Design

  39. Chapter Summary • Major strengths of programming languages attributed to loops • Types of loops • while • Counter-controlled • State-controlled • Sentinel-controlled • for • foreach • do…while C# Programming: From Problem Analysis to Program Design

  40. Chapter Summary (continued) • Conditional expressions used with loops • Nested loops • Unconditional transfer of control • Which use loop structures? • Loop structures for different types of applications C# Programming: From Problem Analysis to Program Design

More Related