Solving Problems with Repetition
description
Transcript of Solving Problems with Repetition
![Page 1: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/1.jpg)
Solving Problems with Repetition
![Page 2: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/2.jpg)
ObjectivesAt the end of this topic, students should be able to:Correctly use a while statement in a C# programCorrectly use break and continue statements in a C# programCorrectly use a do-while statement in a C# programCorrectly use a for statement in a C# programCreate simple algorithms to solve looping problems andcreate UML activity diagrams to describe their algorithms
![Page 3: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/3.jpg)
Loop Problems
It is very common to encounter problems thatrequire the program to process several differentsets of data using the same algorithm. Consider,for example, the following problem statements.
![Page 4: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/4.jpg)
Write a program that prints out n! for n = 1 through 10.
Write a program that reads data from a file until thereis no more data to read.
Write a program that calculates the postage for 10different packages, all of different weights.
Add up the first 15 value entered by the user
Etc…
![Page 5: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/5.jpg)
Write a program that prompts the user for atemperature in degrees Celsius, converts thattemperature into degrees Fahrenheit, and displaysthe answer.
After displaying the results, the program asksthe user if another conversion is to be done.If the user responds with a ‘y’ the program repeatsthis sequence another time. If the user respondswith ‘n’, the program terminates.
![Page 6: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/6.jpg)
The activity diagram for this program might look like
![Page 7: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/7.jpg)
The do StatementThe perfect tool to do thiskind of processing is the do-while statement. A do-while statement allows the program to execute the same statement or block multiple times.
do{ Write(“give me a temperature :”); tempC = double.Parse(ReadLine( ) ); tempF = tempC * 1.8 + 32; WriteLine($“The F temp is {tempF}“); Write(“Do it again? ”); response = char.Parse(ReadLine( ) ); response = char.ToLower(response);
} while(response == ‘y’);
![Page 8: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/8.jpg)
Write(“give me a temperature :”); tempC = double.Parse(ReadLine( ) ); tempF = tempC * 1.8 + 32; WriteLine($“The F temp is {tempF:F2}”); Write(“Do it again? ”); response = char.Parse(ReadLine( ) ); response = char.ToLower(response);
do{
} while(response == ‘y’ );
This is the body of the loop.
In a do loop, the body of the loopwill always get executed at least one time.
Testing against user input like this,the variable response is calleda sentinel.
Notice where thesemicolon goes
do-while syntax
The condition istested at the endof the loop.
![Page 9: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/9.jpg)
What if you want to write the code this way?
![Page 10: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/10.jpg)
In this case, use a while loop.a while loop may not everexecute the body of the loop.
![Page 11: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/11.jpg)
Write(“give me a temperature :”); tempC = double.Parse(ReadLine( ) ); tempF = tempC * 1.8 + 32; WriteLine($“The F temp is {tempF:F2}“); Write(“Do it again? ”); response = char.Parse(ReadLine( ) ); response = char.ToLower(response);
while (response == ‘y’){
}
This is the body of the loop.
In a while loop, the body of the loopmay never be executed.
In a while loop, thecondition is tested atthe top of the loop.
while syntax
![Page 12: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/12.jpg)
break and continuebreak – 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!
![Page 13: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/13.jpg)
Using a Loop toValidate 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.
![Page 14: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/14.jpg)
Let’s design this algorithmIt will use loops and decisions …
![Page 15: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/15.jpg)
Prompt“Do it again?”
Get inputFrom theuserInputValid
?Display an
errormessage
no
yes
Loop back to thetop of this activity
Response= ‘y’
?
yesnoquit
![Page 16: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/16.jpg)
// prompt to play again – make sure response is validWrite(“Do you want to play again(y or n)?: “);yesNo = char.Parse(ReadLine( ) );yesNo = char.ToLower(yesNo);
// see if response is valid – print a message if it’s notif (yesNo != ‘y’ && yesNo != ‘n’) WriteLine(“\nSorry, but that is not a valid response.”);
![Page 17: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/17.jpg)
// prompt to play again – make sure response is validWrite(“Do you want to play again(y or n)?: “);yesNo = char.Parse(ReadLine( ) );yesNo = char.ToLower(yesNo);
// see if response is valid – print a message if it’s notif (yesNo != ‘y’ && yesNo != ‘n’) WriteLine(“\nSorry, but that is not a valid response.”);
What kind of a loop should we use?
do{
} while ( yesNo != ‘y’ && yesNo != ‘n’);
Hint: we want to always executeThe loop at least one time.
![Page 18: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/18.jpg)
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.
![Page 19: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/19.jpg)
Prompt userFor avalue
Get inputFrom the
user
Display theresult
Prompt“Play Again?”
Get inputFrom the
user
InputValid
?Display an
errormessage
no Playagain
?
yes noend
Notice that there areTwo loops, one inside ofThe other.
![Page 20: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/20.jpg)
First – our up front boilerplate
using System;
Class Program{ static void Main( ) {
![Page 21: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/21.jpg)
Second – declare and initialize the variables we will use
int number = 0; // a user entered valuechar yesNo = ‘N’; // store use response to do it again
![Page 22: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/22.jpg)
// prompt, get user input, and display itWrite(“Enter an integer value: “);number = int.Parse(ReadLine( ) );WriteLine(“You typed the number {0}“, number);
Prompt userFor avalue
Get inputFrom the
user
Display theresult
![Page 23: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/23.jpg)
using System;Using static System.Console;
class Program{ static void Main() { int number; char yesNo;
do // main loop { Write("Enter an integer value: "); number = int.Parse(ReadLine( ) ); WriteLine($"nYou typed the number {number}"); do { Write("Do you want to play again (y or n)? "); yesNo = char.Parse(ReadLine( ) ); yesNo = char.ToLower(yesNo); if ( yesNo != 'y' && yesNo != 'n') WriteLine("Sorry, that is not a valid response."); } while (yesNo != ‘y’ && yesNo != ‘n’); } while (yesNo == ‘y’); }}
![Page 24: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/24.jpg)
Counting LoopsWhen you want to repeat a blockof code a fixed number of times
![Page 25: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/25.jpg)
Print out n! for the values of n between 1 and 10
![Page 26: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/26.jpg)
What kind of a loop?
do{
} while(/*expession */);
![Page 27: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/27.jpg)
int nFactorial = 0;int n = 1;do{ // calculate n!
WriteLine($“ {n:d}! = {nFactorial:d}”); n++;} while (n < 11);
When written this way, n is called a limit.Note that n must change inside of the loop.
![Page 28: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/28.jpg)
There is a better kind of loop we can use for a counting loop.
![Page 29: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/29.jpg)
The for StatementThe for statement is best used when you knowexactly how many times you want to executethe loop.
for ( ){ WriteLine(count);}
initialization evaluation incrementint count = 0; count < LIMIT; count++
Initialize
evaluatecondition
body of loop
increment
![Page 30: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/30.jpg)
for (int i = 1; i < 11; i++){ // calculate n!
WriteLine($“ {n:d}! = {nFactorial:d1}”);
}
![Page 31: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/31.jpg)
How would you calculate n! ?Hint: we need another loop …
![Page 32: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/32.jpg)
n = i;nFactorial = i;
while ( n != 1){ nFactorial = nFactorial * --n;}
![Page 33: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/33.jpg)
using System;
class Program{ static void Main() { int nFactorial = 0, n = 0;
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; }
WriteLine($"{i:d}! = {nFactorial:d}"); }
}}
This is an exampleof nested loops
![Page 34: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/34.jpg)
General format for loops
do{ statement(s);} while(condition);
while(condition){ statement(s)}
for(initializer; condition; iterator){ statement(s)}
![Page 35: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/35.jpg)
Loops - Poor Programming Style
There are a couple of common errors that studentsmake when using for loops. While the programs work,the code is hard to maintain, and these errors should be avoided.
![Page 36: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/36.jpg)
Terminating a for loop by changing the index
int userInput = 0;
for(int j = 0; j < MAX; j++){ Write(“Enter an integer value, or zero to quit: “); userInput = int.Parse(ReadLine( ) ); if (userInput == 0) j = MAX; WriteLine($“You entered the value {userInput:d}”);}
![Page 37: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/37.jpg)
Terminating a for loop using a break
int userInput = 0;
for(int j = 0; j < MAX; j++){ Write(“Enter an integer value, or zero to quit: “); userInput = int.Parse(ReadLine( ) ); if (userInput == 0) break; WriteLine($“You entered the value {userInput:d}”);}
![Page 38: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/38.jpg)
This is a better way to write this code
int userInput = 0;
do{ Write(“Enter an integer value, or zero to quit: “); userInput = int.Parse(ReadLine( ) ); if (userInput != 0) WriteLine(“You entered the value {userInput:d}”);} while(userInput != 0);
![Page 39: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/39.jpg)
Write a program that uses a while loop toprint out the integers 1 through 10.
Write a program that uses a do-while loop toprint out the integers 1 through 10.
Write a program that uses a for loop toprint out the integers 1 through 10.
Practice
![Page 40: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/40.jpg)
PracticeWrite a program that displays the multiplicationtables between 2 and 12. Display the output incolumns, so that it all appears on one screen. Yourtable should be nicely lined up like the following:
2 3 4 5 6 7 8 9 10 11 122 4 6 8 10 12 14 16 18 20 22 243 6 9 12 15 18 21 24 27 30 33 364 8 12 16 20 24 28 32 36 40 44 48
etc . . .
Hint: use nestedcounting loops
![Page 41: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/41.jpg)
PracticeWrite a program that prints out the following pattern.The only output statements you may use in your programare Console.Write(‘*’); Console.WriteLine( );
* ** *** **** ***** ******
Hint: use nestedcounting loops
![Page 42: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/42.jpg)
PracticeYou just purchased a new computer that cost $1000.00. Youdid not have to make a down payment, and your payments are$50.00 a month. The interest rate on your purchase is 18% peryear. How many payments will you have to make to pay off theloan and what is the total interest that you will pay over the lifeof the loan.
Each month when you make a payment, your payment first paysthe 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.
![Page 43: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/43.jpg)
Step OneWrite down everything you know about the problem.
Loan amount = 1000.00
Monthly Payment = 50.00
Interest Rate = 18%
![Page 44: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/44.jpg)
Step TwoWrite down what you are looking for
Months to Pay
Total Interest
![Page 45: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/45.jpg)
Interest CalculationEach month when you make a payment, your payment first paysthe interest for that month. The monthly interest rate is 1.5%, sothe 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 leftafter paying the interest, so subtracting this from the loan balancewill make the new balance $965.00.
The next month, repeat the process, starting with the new balance, $965.00.
![Page 46: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/46.jpg)
Pseudo codePseudo code is an English-like description of the programmingsteps 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
![Page 47: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/47.jpg)
Fibonacci Numbers
The sequence of Fibonacci numbers is defined by
f1 = 1f2 = 1fn = fn-1 + fn-2
That is, each number in the sequence is equal toto the sum of the two previous numbers
![Page 48: Solving Problems with Repetition](https://reader036.fdocuments.us/reader036/viewer/2022062502/5681603d550346895dcf6008/html5/thumbnails/48.jpg)
Write a program that generates the first 15 Fibonacci numbers.