Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Similar documents
5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Chapter 5: Loops and Files

Looping. Arizona State University 1

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Object-Oriented Programming in Java

Lecture 7 Tao Wang 1

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Increment and the While. Class 15

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

REPETITION CONTROL STRUCTURE LOGO

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Loops / Repetition Statements

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Introduction. C provides two styles of flow control:

Structured Programming. Dr. Mohamed Khedr Lecture 9

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

LECTURE 5 Control Structures Part 2

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Control Structures of C++ Programming (2)

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 5: Control Structures II (Repetition)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Programming for Engineers Iteration

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Quiz Determine the output of the following program:

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

An Introduction to Programming with C++ Sixth Edition. Chapter 8 More on the Repetition Structure

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Repetition and Loop Statements Chapter 5

Chapter 4: Loops and Files

Chapter 4: Control structures. Repetition

Chapter 3 Structured Program Development in C Part II

DELHI PUBLIC SCHOOL TAPI

Why Is Repetition Needed?

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Iterative Languages. Scoping

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 4: Control structures

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Chapter 7 Array. Array. C++, How to Program

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

A Beginner s Guide to Programming Logic, Introductory. Chapter 5 Looping

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

In this chapter you will learn:

(6-1) Iteration in C H&K Chapter 5. Instructor - Andrew S. O Fallon CptS 121 (February 11, 2019) Washington State University

Assignment: 1. (Unit-1 Flowchart and Algorithm)

Loops and Files. of do-while loop

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Lecture 7: General Loops (Chapter 7)

Chapter 4: Loops and Files

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

C++ PROGRAMMING SKILLS Part 2 Programming Structures

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Computers Programming Course 7. Iulian Năstac

Flow Control. CSC215 Lecture

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Chapter 7. Additional Control Structures

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Homework #3 CS2255 Fall 2012

CS110D: PROGRAMMING LANGUAGE I

Iteration. CSE / ENGR 142 Programming I. while loops. Chapter 5. Motivating Loops. Loop to Add 5 Numbers 1996 UW CSE H - 1

3 The L oop Control Structure

Dept. of CSE, IIT KGP

n Group of statements that are executed repeatedly while some condition remains true

Information Science 1

Chapter 2: Introduction to C++

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Information Science 1

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Iteration Loops. The Do While Loop (Continued) Looping Subtasks

Chapter 3. More Flow of Control

CSCI 1061U Programming Workshop 2. C++ Basics

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Fundamentals of Programming Session 13

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Lecture # 6. Repetition. Review. If Else Statements Comparison Operators Boolean Expressions Nested Ifs. Switch Statements.

Control Structures II. Repetition (Loops)

Repetition Structures II

204111: Computer and Programming

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Transcription:

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Chapter 6 : (Control Structure- Repetition) Using Decrement or Increment While Loop Do-While Loop FOR Loop Nested Loop Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

1 The Increment and Decrement Operators Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix) a variable: ++val; val++; Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Increment and Decrement Operators (cont..) -- is the decrement operator. It subtracts one from a variable. val--; is the same as val = val - 1; -- can be also used before (prefix) or after (postfix) a variable: --val; val--; Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-5

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley (Program Continues)

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-7

Prefix vs. Postfix ++ and -- operators can be used in complex statements and expressions In prefix mode (++val, --val) the operator increments or decrements, then returns the value of the variable In postfix mode (val++, val--) the operator returns the value of the variable, then increments or decrements Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-8

Prefix vs. Postfix - Examples int num, val = 12; cout << val++; // displays 12, // val is now 13; cout << ++val; // sets val to 14, // then displays it num = --val; // sets val to 13, // stores 13 in num num = val--; // stores 13 in num, // sets val to 12 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-9

Notes on Increment, Decrement Can be used in expressions: result = num1++ + --num2; Must be applied to something that has a location in memory. Cannot have: result = (num1 + num2)++; Can be used in relational expressions: if (++num > limit) pre- and post-operations will cause different comparisons Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-10

2 Introduction to Loops: The while Loop Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Introduction to Loops: The while Loop Loop: a control structure that causes a statement or statements to repeat General format of the while loop: while (expression) statement; statement; can also be a block of statements enclosed in { } Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-12

while Loop How It Works while (expression) statement; expression is evaluated if true, then statement is executed, and expression is evaluated again if false, then the the loop is finished and program statements following statement execute Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-13

The Logic of a while Loop Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-14

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-15

How the Loop in Lines 9 through 13 Works Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-16

Flowchart of the Loop Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-17

while is a Pretest Loop expression is evaluated before the loop executes. The following loop will never execute: int number = 6; while (number <= 5) { cout << "Hello\n"; number++; } Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-18

Watch Out for Infinite Loops The loop must contain code to make expression become false Otherwise, the loop will have no way of stopping Such a loop is called an infinite loop, because it will repeat an infinite number of times Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-19

An Infinite Loop int number = 1; while (number <= 5) { cout << "Hello\n"; } Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-20

3 Using the while Loop for Input Validation Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Using the while Loop for Input Validation Input validation is the process of inspecting data that is given to the program as input and determining whether it is valid. The while loop can be used to create input routines that reject invalid data, and repeat until valid data is entered. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-22

Using the while Loop for Input Validation (cont..) Here's the general approach, in pseudocode: Read an item of input. While the input is invalid Display an error message. Read the input again. End While Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-23

Input Validation Example cout << "Enter a number less than 10: "; cin >> number; while (number >= 10) { cout << "Invalid Entry!" << "Enter a number less than 10: "; cin >> number; } Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-24

Flowchart using Input Validation Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-25

Input Validation Example from Program 5-4 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-26

4 The do-while Loop Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The do-while Loop do-while: a posttest loop execute the loop, then test the expression General Format: do statement; // or block in { } while (expression); Note that a semicolon is required after (expression) Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-28

The Logic of a do-while Loop Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-29

do-while Example int x = 1; do { cout << x << endl; } while(x < 0); Although the test expression is false, this loop will execute one time because do-while is a posttest loop. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-30

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-31

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-32

do-while Loop Notes Loop always executes at least once Execution continues as long as expression is true, stops repetition when expression becomes false Useful in menu-driven programs to bring user back to menu to make another choice (see Program 5-7 in the book) Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-33

5 The for Loop Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The for Loop Useful for counter-controlled loop General Format: for(initialization; test; update) statement; // or block in { } No semicolon after 3 rd expression or after the ) Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-35

for Loop - Mechanics for(initialization; test; update) statement; // or block in { } 1) Perform initialization 2) Evaluate test expression If true, execute statement If false, terminate loop execution 3) Execute update, then re-evaluate test expression Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-36

for Loop - Example int count; for (count = 1; count <= 5; count++) cout << "Hello" << endl; Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-37

A Closer Look at the Previous Example Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-38

Flowchart for the Previous Example Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-39

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-40

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-41

A Closer Look at Lines 13 through 14 in Program 5-8 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-42

Flowchart for Lines 13 through 14 in Program 5-8 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-43

When to Use the for Loop In any situation that clearly requires an initialization a false condition to stop the loop an update to occur at the end of each iteration Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-44

The for Loop is a Pretest Loop The for loop tests its test expression before each iteration, so it is a pretest loop. The following loop will never iterate: for (count = 11; count <= 10; count++) cout << "Hello" << endl; Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-45

for Loop - Modifications You can have multiple statements in the initialization expression. Separate the statements with a comma: Initialization Expression int x, y; for (x=1, y=1; x <= 5; x++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-46

for Loop Modifications (cont..) You can also have multiple statements in the test expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++, y++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Update Expression Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-47

for Loop Modifications (cont..) You can omit the initialization expression if it has already been done: int sum = 0, num = 1; for (; num <= 10; num++) sum += num; Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-48

for Loop Modifications(cont..) You can declare variables in the initialization expression: int sum = 0; for (int num = 0; num <= 10; num++) sum += num; The scope of the variable num is the for loop. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-49

6 Summaries Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Deciding Which Loop to Use while: pretest loop; loop body may not be executed at all do-while: posttest loop; loop body will always be executed at least once for: pretest loop with initialization and update expression; useful with counters, or if precise number of repetitions is needed Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-51

Repetition Structure Pattern 1: WHILE Here must be a False condition True Here must be a True while (condition) { Repeated_Actions; } Repeated_Actions False Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Repetition Structure (cont..) Example: Calculate the average of odd numbers 1 to 9 sum = 0 i =1 i < 11 True sum = sum + i i = i+2 False sum = 0; i=1; while (i<11) { sum = sum + i; i = i + 2; } avrg = sum/5.0; av rg = sum /5 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Pattern 2: DO -WHILE Repetition Structure (cont..) True The iterating part must be a True Repeated_Actions do { Repeated_Actions; } while(condition); condition False Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Example: Prints numbers 1 to 10 Repetition Structure (cont..) True i =1 PRINT i i = i + 1 i=1; do { printf( %d\n,i); i = i + 1; } while (i<11); i <11 False Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Pattern 3: FOR Repetition Structure (cont..) initialize for (initialize; condition; update) { } Repeated_Actions; condition or True Repeated_Actions update False initialize; while (condition) { Repeated_Actions; update; } Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

total = 0 i=1 i<11 True total = total + i i=i+1 Repetition Structure (cont..) Example: Print the total of numbers 1 to 10 PRINT total False total = 0; or total = 0; i=1; while (i<11) Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley for (i=1; i<11; i++) { } { } total = total + i; printf( %d,total); total = total + i; i++; printf( %d,total);

7 Nested Loops Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Nested Loops A nested loop is a loop inside the body of another loop Inner (inside), outer (outside) loops: for (row=1; row<=3; row++) //outer for (col=1; col<=3; col++)//inner cout << row * col << endl; Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-59

Lines from Program 5-14 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-60

Nested Loops - Notes Inner loop goes through all repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is product of number of repetitions of the two loops. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-61