440 likes | 527 Views
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
E N D
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
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.
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…
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.
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’);
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.
What if you want to write the code this way?
In this case, use a while loop. a while loop may not ever execute the body of the loop.
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.
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!
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.
Let’s design this algorithm It will use loops and decisions …
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
// 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.”);
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’);
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.
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
First – our up front boilerplate using System; Class Program { static void Main( ) {
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
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
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’); } }
Counting Loops When you want to repeat a block of code a fixed number of times
What kind of a loop? do { } while(/*expession */);
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.
There is a better kind of loop we can use for a counting loop.
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
for (inti = 1; i < 11; i++) { // calculate n! Console.WriteLine(“ {0}! = {1}”, n, nFactorial); }
How would you calculate n! ? Hint: we need another loop …
n = i; nFactorial = i; while ( n != 1) { nFactorial = nFactorial * --n; }
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
General format for loops do { statement(s); } while(condition); while(condition) { statement(s) } for(initializer; condition;iterator) { statement(s) }
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.
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
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
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.
Step One Write down everything you know about the problem. Loan amount = 1000.00 Monthly Payment = 50.00 Interest Rate = 18%
Step Two Write down what you are looking for Months to Pay Total Interest
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.
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
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
Write a program that generates the first 15 Fibonacci numbers.