1 / 44

Solving Problems with Repetition

Solving Problems with Repetition. Objectives. At the end of this topic, students should be able to:. Correctly use a while statement in a C# program Correctly use break and continue statements in a C# program Correctly use a do-while statement in a C# program

ollie
Download Presentation

Solving Problems with Repetition

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. Solving Problems with Repetition

  2. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly use break and continue statements in a C# program Correctly use a do-whilestatement in a C# program Correctly use a for statement in a C# program Create simple algorithms to solve looping problems and create UML activity diagrams to describe their algorithms

  3. Loop Problems It is very common to encounter problems that require the program to process several different sets of data using the same algorithm. Consider, for example, the following problem statements.

  4. Write a program that prints out n! for n = 1 through 10. Write a program that reads data from a file until there is no more data to read. Write a program that calculates the postage for 10 different packages, all of different weights. Add up the first 15 value entered by the user Etc…

  5. Write a program that prompts the user for a temperature in degrees Celsius, converts that temperature into degrees Fahrenheit, and displays the answer. After displaying the results, the program asks the user if another conversion is to be done. If the user responds with a ‘y’ the program repeats this sequence another time. If the user responds with ‘n’, the program terminates.

  6. The activity diagram for this program might look like

  7. The do Statement The perfect tool to do this kind of processing is the do-whilestatement. A do-while statement allows the program to execute the same statement or block multiple times. do { Console.Write(“give me a temperature :”); tempC = double.Parse(Console.ReadLine( ) ); tempF = tempC * 1.8 + 32; Console.WriteLine(“The F temp is {0}“, tempF); Console.Write(“Do it again? ”); response = char.Parse(Console.ReadLine( ) ); response = char.ToLower(response); } while(response == ‘y’);

  8. do-while syntax do { } while(response == ‘y’ ); Console.Write(“give me a temperature :”); tempC = double.Parse(Console.ReadLine( ) ); tempF = tempC * 1.8 + 32; Console.WriteLine(“The F temp is {0}“, tempF); Console.Write(“Do it again? ”); response = char.Parse(Console.ReadLine( ) ); response = char.ToLower(response); This is the body of the loop. The condition is tested at the end of the loop. In a do loop, the body of the loop will always get executed at least one time. Notice where the semicolon goes Testing against user input like this, the variable response is called a sentinel.

  9. What if you want to write the code this way?

  10. In this case, use a while loop. a while loop may not ever execute the body of the loop.

  11. while syntax In a while loop, the condition is tested at the top of the loop. while (response == ‘y’) { } Console.Write(“give me a temperature :”); tempC = double.Parse(Console.ReadLine( ) ); tempF = tempC * 1.8 + 32; Console.WriteLine(“The F temp is {0}“, tempF); Console.Write(“Do it again? ”); response = char.Parse(Console.ReadLine( ) ); response = char.ToLower(response); This is the body of the loop. In a while loop, the body of the loop may never be executed.

  12. break and continue break – breaks immediately out of a loop. continue – skip the rest of the loop and go back to the loop’s condition another time. Only use these statements when you have no other option!

  13. Using a Loop to Validate Input A common programming problem is to do something, and then ask the user if they want to do it again. If the user answers “yes” you do it again. If the user answers “no” you stop. If the user answers neither, tell him to try the answer again.

  14. Let’s design this algorithm It will use loops and decisions …

  15. Loop back to the top of this activity Prompt “Do it again?” Get input From the user Input Valid ? no Display an error message yes yes no Response = ‘y’ ? quit

  16. // prompt to play again – make sure response is valid Console.Write(“Do you want to play again(y or n)?: “); yesNo = char.Parse(Console.ReadLine( ) ); yesNo = char.ToLower(yesNo); // see if response is valid – print a message if it’s not if (yesNo != ‘y’ && yesNo!= ‘n’) Console.WriteLine(“\nSorry, but that is not a valid response.”);

  17. What kind of a loop should we use? Hint: we want to always execute The loop at least one time. do { // prompt to play again – make sure response is valid Console.Write(“Do you want to play again(y or n)?: “); yesNo = char.Parse(Console.ReadLine( ) ); yesNo = char.ToLower(yesNo); // see if response is valid – print a message if it’s not if (yesNo != ‘y’ && yesNo != ‘n’) Console.WriteLine(“\nSorry, but that is not a valid response.”); } while( yesNo != ‘y’ && yesNo != ‘n’);

  18. Let’s use this algorithm in a complete program. It simply asks the user to type a number. The number is displayed. The user is then asked if they want to do it again.

  19. Prompt user For a value Get input From the user Display the result Notice that there are Two loops, one inside of The other. Prompt “Play Again?” Get input From the user Input Valid ? no yes no Play again ? Display an error message end

  20. First – our up front boilerplate using System; Class Program { static void Main( ) {

  21. Second – declare and initialize the variables we will use intnumber = 0; // a user entered value char yesNo = ‘N’; // store use response to do it again

  22. Prompt user For a value Get input From the user // prompt, get user input, and display it Console.Write(“Enter an integer value: “); number = int.Parse(Console.ReadLine( ) ); Console.WriteLine(“You typed the number {0}“, number); Display the result

  23. using System; class Program { static void Main() { int number; char yesNo; do // main loop { Console.Write("Enter an integer value: "); number = int.Parse(Console.ReadLine( ) ); Console.WriteLine("nYou typed the number {0}", number); do { Console.Write("Do you want to play again (y or n)? "); yesNo = char.Parse(Console.ReadLine( ) ); yesNo = char.ToLower(yesNo); if ( yesNo != 'y' && yesNo != 'n') Console.WriteLine("Sorry, that is not a valid response."); } while (yesNo != ‘y’ && yesNo != ‘n’); } while (yesNo == ‘y’); } }

  24. Counting Loops When you want to repeat a block of code a fixed number of times

  25. Print out n! for the values of n between 1 and 10

  26. What kind of a loop? do { } while(/*expession */);

  27. intnFactorial = 0; int n = 1; do { // calculate n! Console.WriteLine(“ {0}! = {1}”, n, nFactorial); n++; } while (n < 11); When written this way, n is called a limit. Note that n must change inside of the loop.

  28. There is a better kind of loop we can use for a counting loop.

  29. The for Statement The for statement is best used when you know exactly how many times you want to execute the loop. Initialize evaluation increment initialization evaluate condition for ( ) { Console.WriteLine(count); } int count = 0; count < LIMIT; count++ body of loop increment

  30. for (inti = 1; i < 11; i++) { // calculate n! Console.WriteLine(“ {0}! = {1}”, n, nFactorial); }

  31. How would you calculate n! ? Hint: we need another loop …

  32. n = i; nFactorial = i; while ( n != 1) { nFactorial = nFactorial * --n; }

  33. using System; class Program { static void Main() { intnFactorial = 0, n = 0; Console.WriteLine("This program computes n ! For n = 1 to 10\n"); for (int i = 1; i < 11; i++) { n = i; nFactorial = i; while (n != 1) { nFactorial = nFactorial * --n; } Console.WriteLine("{0}! = {1}", i, nFactorial); } } } This is an example of nested loops

  34. General format for loops do { statement(s); } while(condition); while(condition) { statement(s) } for(initializer; condition;iterator) { statement(s) }

  35. Practice Write a program that uses a while loop to print out the integers 1 through 10. Write a program that uses a do-while loop to print out the integers 1 through 10. Write a program that uses a for loop to print out the integers 1 through 10.

  36. Practice Write a program that displays the multiplication tables between 2 and 12. Display the output in columns, so that it all appears on one screen. Your table should be nicely lined up like the following: 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36 4 8 12 16 20 24 28 32 36 40 44 48 etc . . . Hint: use nested counting loops

  37. Practice Write a program that prints out the following pattern. The only output statements you may use in your program are Console.Write(‘*’); Console.WriteLine( ); * ** *** **** ***** ****** Hint: use nested counting loops

  38. Practice You just purchased a new computer that cost $1000.00. You did not have to make a down payment, and your payments are $50.00 a month. The interest rate on your purchase is 18% per year. How many payments will you have to make to pay off the loan and what is the total interest that you will pay over the life of the loan. Each month when you make a payment, your payment first pays the interest for that month. The monthly interest rate is 1.5%. Once the interest is paid, the balance of you payment goes towards the balance of the loan.

  39. Step One Write down everything you know about the problem. Loan amount = 1000.00 Monthly Payment = 50.00 Interest Rate = 18%

  40. Step Two Write down what you are looking for Months to Pay Total Interest

  41. Interest Calculation Each month when you make a payment, your payment first pays the interest for that month. The monthly interest rate is 1.5%, so the first month the interest will be 1.5% x $1000.00, or $15.00. Once the interest is paid, the balance of you payment goes towards the balance of the loan. The first month you will have $35.00 left after paying the interest, so subtracting this from the loan balance will make the new balance $965.00. The next month, repeat the process, starting with the new balance, $965.00.

  42. Pseudo code Pseudo code is an English-like description of the programming steps taken to solve a problem. Write the pseudo code required to calculate the new balance each month interest = balanceDue x monthlyRate paymentBalance = payment – interest balanceDue = balanceDue - paymentBalance

  43. Fibonacci Numbers The sequence of Fibonacci numbers is defined by f1 = 1 f2 = 1 fn = fn-1 + fn-2 That is, each number in the sequence is equal to to the sum of the two previous numbers

  44. Write a program that generates the first 15 Fibonacci numbers.

More Related