Solving Problems with Repetition Version 1.0. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C#

Slides:



Advertisements
Similar presentations
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.
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
CS0004: Introduction to Programming Repetition – Do Loops.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Topic 6 – Repetition and Loops. CISC 105 – Topic 6 Program Repetition Repetition refers to the repeats of certain program statements within a program.
Chapter 5: Control Structures II (Repetition)
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Objectives You should be able to describe:
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Introduction to Computer Programming in c
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Chapter 5: Control Structures II (Repetition)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Control Structures RepetitionorIterationorLooping Part I.
Designing While Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Method Parameters and Overloading Version 1.0. Topics The run-time stack Pass-by-value Pass-by-reference Method overloading Stub and driver methods.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
General Condition Loop A general condition loop just loops while some condition remains true. Note that the body of the loop should (eventually) change.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
Repetition (While-Loop) version]
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Chapter 4 – Control Structures Part 1
Lecture 07 More Repetition Richard Gesick.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lesson #5 Repetition and Loops.
Chapter 5: Control Structures II (Repetition)
Looping and Repetition
Presentation transcript:

Solving Problems with Repetition Version 1.0

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

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 integers. 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 activity diagram for this program might look like

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

Console.Write(“give me a temperature :”); tempC = double.Parse(Console.ReadLine( ) ); tempF = tempC * ; 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.

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.

Console.Write(“give me a temperature :”); tempC = double.Parse(Console.ReadLine( ) ); tempF = tempC * ; 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

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 …

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

// 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 okay = (yesNo == ‘y’ || yesNo == ‘n’); if ( !okay ) Console.WriteLine(“\nSorry, but that is not a valid response.”);

// 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 okay = (yesNo == ‘y’ || yesNo == ‘n’); if ( !okay ) Console.WriteLine(“\nSorry, but that is not a valid response.”); What kind of a loop should we use? do { } while (!okay); Hint: we want to always execute The 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 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.

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

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 bool okay = true, notDone = false; // some flags

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

using System; class Program { static void Main() { int number; char yesNo; bool okay = true, notDone = true; 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); okay = ( yesNo == 'y' || yesNo == 'n'); if ( !okay ) Console.WriteLine("Sorry, that is not a valid response."); } while (!okay); if (yesNo == 'n') notDone = false; } while (notDone); } Note that (!okay) is exactly The same as writing ! (okay == true), or ( okay != true)

Counting Loops When you want to repeat a block of 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 nFactorialn = 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. for ( ) { Console.WriteLine(count); } initialization evaluationincrement int count = 0;count < LIMIT;count++ Initialize evaluate condition body of loop increment

for (int i = 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() { 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

General format for loops do statement while(expression); while(expression) statement for(initializer; control; iterator) statement Where a statement is a: single statement or block statement

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: etc... Hint: use nested counting loops

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

Practice You just purchased a new computer that cost $ 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 = Monthly Payment = 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 $ , or $ 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 $ The next month, repeat the process, starting with the new balance, $

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