Solving Problems with Repetition

Post on 21-Mar-2016

30 views 4 download

description

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 - PowerPoint PPT Presentation

Transcript of Solving Problems with Repetition

Solving Problems with Repetition

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

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.

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…

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.

The activity diagram for this program might look like

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’);

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.

What if you want to write the code this way?

In this case, use a while loop.a while loop may not everexecute the body of the loop.

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

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!

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.

Let’s design this algorithmIt will use loops and decisions …

Prompt“Do it again?”

Get inputFrom theuserInputValid

?Display an

errormessage

no

yes

Loop back to thetop of this activity

Response= ‘y’

?

yesnoquit

// 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.”);

// 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.

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 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.

First – our up front boilerplate

using System;

Class Program{ static void Main( ) {

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

// 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

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’); }}

Counting LoopsWhen you want to repeat a blockof code a fixed number of times

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

What kind of a loop?

do{

} while(/*expession */);

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.

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

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

for (int i = 1; i < 11; i++){ // calculate n!

WriteLine($“ {n:d}! = {nFactorial:d1}”);

}

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() { 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

General format for loops

do{ statement(s);} while(condition);

while(condition){ statement(s)}

for(initializer; condition; iterator){ statement(s)}

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.

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}”);}

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}”);}

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);

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

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

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

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.

Step OneWrite down everything you know about the problem.

Loan amount = 1000.00

Monthly Payment = 50.00

Interest Rate = 18%

Step TwoWrite down what you are looking for

Months to Pay

Total Interest

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.

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

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

Write a program that generates the first 15 Fibonacci numbers.