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.

Slides:



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

Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
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.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Computer Science 1620 Programming & Problem Solving.
© 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
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.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
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.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
© 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.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
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.
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,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Designing While Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
(C)opyright 2000 Scott/Jones Publishers Introduction to Flowcharting.
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.
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)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
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#
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.
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.
REPETITION CONTROL STRUCTURE
Repetition (While-Loop) version]
Loop Structures.
Chapter 4 – Control Structures Part 1
Lecture 07 More Repetition Richard Gesick.
Chapter 6: Repetition Statements
Chapter 5: Control Structures II (Repetition)
Presentation transcript:

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 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 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 if (yesNo != ‘y’ && yesNo != ‘n’) 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 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.

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

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

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! 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(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 students make 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++) { 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); }

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

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

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

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

Write a program that generates the first 15 Fibonacci numbers.