Download presentation
Presentation is loading. Please wait.
Published byCyrus Drews Modified over 9 years ago
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-while statement 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- while statement. 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
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); do { } while(response == ‘y’ ); This is the body of the loop. In a do loop, the body of the loop will always get executed at least one time. Testing against user input like this, the variable response is called a sentinel. Notice where the semicolon goes do-while syntax The condition is tested at the end of the loop.
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
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’) { } This is the body of the loop. In a while loop, the body of the loop may never be executed. In a while loop, the condition is tested at the top of the loop. while syntax
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
Prompt “Do it again?” Get input From the user Input Valid ? Display an error message no yes Loop back to the top of this activity Response = ‘y’ ? yes no 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
// 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? do { } while ( yesNo != ‘y’ && yesNo != ‘n’); Hint: we want to always execute The loop at least one time.
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 Prompt “Play Again?” Get input From the user Input Valid ? Display an error message no Play again ? yesno end Notice that there are Two loops, one inside of The other.
20
First – our up front boilerplate using System; Class Program { static void Main( ) {
21
Second – declare and initialize the variables we will use int number = 0; // a user entered value char yesNo = ‘N’; // store use response to do it again
22
// 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); Prompt user For a value Get input From the user 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
int nFactorial = 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. for ( ) { Console.WriteLine(count); } initialization evaluationincrement int count = 0;count < LIMIT;count++ Initialize evaluate condition body of loop increment
30
for (int i = 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() { int nFactorial = 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
Loops - Poor Programming Style There are a couple of common errors that students make when using for loops. While the programs work, the code is hard to maintain, and these errors should be avoided.
36
Terminating a for loop by changing the index int userInput = 0; for(int j = 0; j < MAX; j++) { Console.Write(“Enter an integer value, or zero to quit: “); userInput = int.Parse(Console.ReadLine( ) ); if (userInput == 0) j = MAX; Console.WriteLine(“You entered the value {0:d}”, userInput); }
37
Terminating a for loop using a break int userInput = 0; for(int j = 0; j < MAX; j++) { Console.Write(“Enter an integer value, or zero to quit: “); userInput = int.Parse(Console.ReadLine( ) ); if (userInput == 0) break; Console.WriteLine(“You entered the value {0:d}”, userInput); }
38
This is a better way to write this code int userInput = 0; do { Console.Write(“Enter an integer value, or zero to quit: “); userInput = int.Parse(Console.ReadLine( ) ); if (userInput != 0) Console.WriteLine(“You entered the value {0:d}”, userInput); } while(userInput != 0);
39
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
40
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
41
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
42
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.
43
Step One Write down everything you know about the problem. Loan amount = 1000.00 Monthly Payment = 50.00 Interest Rate = 18%
44
Step Two Write down what you are looking for Months to Pay Total Interest
45
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.
46
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
47
Fibonacci Numbers The sequence of Fibonacci numbers is defined by f 1 = 1 f 2 = 1 f n = f n-1 + f n-2 That is, each number in the sequence is equal to to the sum of the two previous numbers
48
Write a program that generates the first 15 Fibonacci numbers.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.