1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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

True or false A variable of type char can hold the value 301. ( F )
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Computer Science 1620 Programming & Problem Solving.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
What is the out put #include using namespace std; void main() { int i; for(i=1;i
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
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 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
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,
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
GAME102 - INTRO WHILE LOOPS G. MacKay. Fundamental Control Structures  STRAIGHT LINE  CONDITIONAL  LOOPS.
Control Structures Repetition or Iteration or Looping Part II.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
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.
Review the following : Flowcharting Variable declarations Output Input Arithmetic Calculations Conditional Statements Loops.
Control Structures RepetitionorIterationorLooping Part I.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Overview Go over parts of quiz? Another iteration structure for loop.
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.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
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.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
C++ Programming: CS102 LOOP. Not everything that can be counted counts, and not every thing that counts can be counted. −Albert Einstein Who can control.
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.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Chapter 4 Repetition Structures
Introduction to Computer Programming
Repetitive Structures
REPETITION CONTROL STRUCTURE
TOPIC 4: REPETITION CONTROL STRUCTURE
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe: The while Statement
Chapter 4 Repetition Structures
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Programming Fundamental
Presentation transcript:

1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Loops Break and continue statements Software development process Algorithms 2 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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 statement in a C++ program Correctly use a for statement in a C++ program Describe the stages of software development Create simple algorithms to solve computing problems and create UML activity diagrams to describe their algorithms 3 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

The while statement allows the program to execute the same statement multiple times. while ( count <= MAX ) { cout << count << ‘ ‘; count ++; } is count <= MAX ? cout << count << ‘ ‘; count++; true this is called the limit Inside the loop, you must always do something to the variable being tested, so that the program will eventually exit the loop false 4 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

// Using a While Statement with a limit // main class declaration int main ( ) { const int MAX = 5; int count = 1; while ( count <= MAX ) { cout << count; count++; } while the limit has not been reached … change the number being compared to the limit 5 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

// Using a While Statement with a sentinel int main ( ) { int value = 1; while ( value != 0 ) { cout << "Enter in a digit between 0 and 9, use 0 to quit:"; cin >> value; cout << "You typed " << value; } cout << "Goodbye!"; } the sentinel in this case is 0 get another value to compare with the sentinel 6 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

... const int MAX = 5; cout << “Enter an integer between 0 and 5; cin >> input; while ( input MAX ) { cout << “Invalid input. Try again”; cin >> input; }... 7 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

// Nested While int main ( ) { const int COUNT = 3; const int TIMES = 2; int valueOne, valueTwo; valueOne = 0; while ( valueOne <= COUNT ) { cout << "In outer loop, valueOne = " << valueOne; valueTwo = 0; while ( valueTwo <= TIMES ) { cout << " In inner loop, valueTwo = " << valueTwo; valueTwo++; } valueOne++; } cout << "Goodbye!"; } 8 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

break – breaks immediately out of a loop/switch. continue – skip the rest of the loop and go back and go through the loop another time. 9 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

do { count++; cout << count; } while ( count < LIMIT); count = count +1; cout << count; is count < LIMIT ? true false in a do statement, the loop will always be executed at least once! 10 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Validating 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. 11 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Write the code ….. 12 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

First – our up front boilerplate #include using namespace std; int main ( ) { 13 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Second – declare the variables we will use int number; // a user entered value char yesNo; // store use response to do it again bool okay = true, notDone = false; // some flags 14 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Prompt user For a value Get input From the user Display the result number 15 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

// prompt, get user input, and display it cout << <\nEnter an integer value: “; cin >> number; cout << “\nYou typed the number “ << number; 16 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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 yesNo 17 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

// prompt to play again – make sure response is valid cout << <\nDo you want to play again(y or n)?: “; cin >> yesNo; if(cin.rdbuf()->in_avail()!=0) cin.ignore(80, ‘\n’); // get rid of extra characters // see if response is valid – print a message if its not okay = (yesNo == ‘y’ || yesNo == ‘n’); if (!okay) cout << “\nSorry, but that is not a valid response.”; 18 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

// prompt to play again – make sure response is valid cout << <\nDo you want to play again(y or n)?: “; cin >> yesNo; if(cin.rdbuf()->in_avail()!=0) cin.ignore(80, ‘\n’); // get rid of extra characters // see if response is valid – print a message if its not okay = (yesNo == ‘y’ || yesNo == ‘n’); if (!okay) cout << “\nSorry, but that is not a valid response.”; Then here is the first loop – stay in loop until there is a valid response do { } while (!okay); 19 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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 20 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

#include using namespace std; int main ( ) { int number; char yesNo; bool okay = true, notDone = true; do // main loop { cout << "\nEnter an integer value: "; cin >> number; cout << "\nYou types the number " << number; do { cout << "\nDo you want to play again (y or n)? "; cin >> yesNo; if(cin.rdbuf()->in_avail()!=0) cin.ignore ( 80, '\n'); // get rid of extra characters okay = ( yesNo == 'y' || yesNo == 'n'); if ( !okay ) cout << "\nSorry, that is not a valid response.” } while (!okay); if (yesNo == 'n') notDone = false; } while (notDone); } 21 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Apply this code to the guessing game in the following slide Practice 22 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

int main ( ) { // We will generate numbers between 0 and 10 const int MAX = 10; int answer, guess; randomize ( ); answer = rand( ) % 11; cout << "I am thinking of a number between 0 and "; cout << MAX << " What is it? "; cin >> guess; if(cin.rdbuf()->in_avail()!=0) cin.ignore(80,’\n’); if ( guess == answer ) cout << "Congratulations. You guessed it.\n"; else { cout << "That is not correct, sorry. "; cout << "The number was " << answer << ‘\n’; } cout << "Thanks for playing.\n"; } 23 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

The for statement is best used when you know exactly how many times you want to execute the loop. for ( ) { cout << count; } initialization evaluationincrement int count = 0;count < LIMIT;count++ Initialize evaluate condition body of loop increment 24 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

The comma operator is used to evaluate a list of expressions, but only return the value in the last expression. goodNum = (first = 2, second = first + 1); this expression is evaluated first then this expression is evaluated and the result is assigned to goodNum. 25 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

establish the requirements create the design implement the code test the implementation 26 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

The steps that we come up with to solve a problem are called an algorithm. An algorithm is like a recipe in a cookbook. Once you come up with an algorithm to solve a particular problem, you can apply it to other similar problems. 27 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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. 28 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Write down everything you know about the problem. Loan amount = Monthly Payment = Interest Rate = 18% 29 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Write down what you are looking for Months to Pay Total Interest 30 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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, $ Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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 32 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

We can create what is called an Activity Diagram to show these steps pictorially. interest = balanceDue x monthlyRate paymentBalance = payment - interest balanceDue = balanceDue – paymentBalance 33 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

We know that we will do this same calculation each month, for some number of months. This suggests that we put the code we just developed into a loop of some kind. The pseudo code to describe this might be something like while the loan is unpaid, do the following: interest = balanceDue x monthlyRate paymentBalance = payment – interest balanceDue = balanceDue - paymentBalance 34 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

interest = balanceDue x monthlyRate paymentBalance = payment - interest balanceDue = balanceDue – paymentBalance is the loan paid off? yes no 35 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

To complete the pseudo code and the diagram, we just need to take care of initializing some things: interest = balanceDue x monthlyRate paymentBalance = payment - interest balanceDue = balanceDue – paymentBalance is the loan paid off? yes no monthlyRate =.015 balanceDue = payment = Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

double balanceDue = ; double monthlyRate =.015; double payment = 50.00; double interest = balanceDue * monthlyRate; double paymentBalance = payment – interest; balanceDue = balanceDue – paymentBalance; What kind of loop? If there is a balance on the loan, we must go through the loop. If not, we can quit. 37 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

double balanceDue = ; double monthlyRate =.015; double payment = 50.00; double interest = balanceDue * monthlyRate; double paymentBalance = payment – interest; balanceDue = balanceDue – paymentBalance; do { } while (balanceDue > 0); 38 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Well, what did the problem ask for? * The number of months it takes to pay off the loan * the total interest paid during the life of the loan Nope …. we haven’t calculated these yet. How would you fix the program to add these calculations? 39 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

double balanceDue = ; double monthlyRate =.015; double payment = double totalInterest = 0.0; int monthsToPay = 0; double interest = balanceDue * monthlyRate; totalInterest += interest; monthsToPay++; double paymentBalance = payment – interest; balanceDue = balanceDue – paymentBalance; do { } while (balanceDue > 0); 40 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

Well …. almost. We probably ought to print out the results. 41 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

double balanceDue = ; double monthlyRate =.015; double payment = double totalInterest = 0.0; int monthsToPay = 0; double interest = balanceDue * monthlyRate; totalInterest += interest; monthsToPay++; double paymentBalance = payment – interest; balanceDue = balanceDue – paymentBalance; do { } while (balanceDue > 0); cout << Months to pay off loan = “ << monthsToPay << “\n”; cout << “Total interest = “; cout.setf (ios::fixed); cout.setf (ios::showpoint); cout.precision (2); cout << totalInterest << “\n”; 42 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

43 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

double balanceDue = ; double monthlyRate =.015; double payment = double totalInterest = 0.0; int monthsToPay = 0; double interest = balanceDue * monthlyRate; totalInterest += interest; monthsToPay++; double paymentBalance = payment – interest; balanceDue = balanceDue – paymentBalance; do { } while (balanceDue > 0); cout << Months to pay off loan = “ << monthsToPay << “\n”; cout << “Total interest = “; cout.setf (ios::fixed); cout.setf (ios::showpoint); cout.precision (2); cout << totalInterest << “\n”; #include using std::cin; using std::cout; using std::ios; int main( ) { { 44 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.

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 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.