Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

Computer Science 1620 Loops.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
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.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Control Structures II (Repetition)
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
Objectives You should be able to describe:
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Chapter 4 Program Control Statements
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
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,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Control Structures Repetition or Iteration or Looping Part II.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Control Structures RepetitionorIterationorLooping Part I.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Infinite for Loop If you omit the test condition, the value is assumed to be TRUE so the loop will continue indefinitely unless you provide some other.
Control Structures Repetition or Iteration or Looping Part II.
Introduction to Computer Programming
Chapter 6: Loops.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 2.2 Control Structures (Iteration)
Control Statements Kingdom of Saudi Arabia
Programming Fundamentals
JavaScript: Control Statements.
For & do/while Loops.
Repetition Control Structure
Chapter 2.2 Control Structures (Iteration)
Control Structures Part 1
Looping III (do … while statement)
2.6 The if/else Selection Structure
Objectives You should be able to describe: The while Statement
Control Statements Paritosh Srivastava.
Presentation transcript:

Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three iteration statements: the while statement, the do..while statement, and the for statement. Iteration statements are also called loops because of their cyclic nature.

THE while STATEMENT The syntax for the while statement is while (condition) statement; where condition is an integral expression and statement is any executable statement. If the value of the expression is zero (meaning “false”) then the statement is ignored and program execution immediately jumps to the next statement that follows the while statement. If the value of the expression is nonzero (meaning “true”) then the statement is executed repeatedly until the expression evaluates to zero. Note that the condition must be enclosed by parentheses. EX1: Using a while Loop to Compute a Sum of Consecutive Integers: int main() { int n,i=1; cout << "Enter a positive integer: "; cin >> n; long sum=0; while (i <= n) sum += i++; cout << "The sum of the first " << n << " integers is " << sum; }

EXAMPLE 4.3 Using a while Loop to Repeat a Computation This program prints the square root of each number input by the user. It uses a while loop to allow any number of computations in a single run of the program: int main() { double x; cout << "Enter a positive number: "; cin >> x; while (x > 0) { cout << "sqrt(" << x << ") = " << sqrt(x) << endl; cout << "Enter another positive number (or 0 to quit): "; cin >> x; }

TERMINATING A LOOP We have already seen how the break statement is used to control the switch statement. The break statement is also used to control loops. EX3 Using a break Statement to Terminate a Loop This program has the same effect as the one in Ex1 int main() { int n,i=1; cout << "Enter a positive integer: "; cin >> n; long sum=0; while (true) { if (i > n) break; // terminates the loop immediately sum += i++; } cout << "The sum of the first " << n << " integers is " << sum; }

THE do..while STATEMENT The syntax for the do..while statement is –do statement while (condition); where condition is an integral expression and statement is any executable statement. It repeatedly executes the statement and then evaluates the condition until that condition evaluates to false. The do..while statement works the same as the while statement except that its condition is evaluated at the end of the loop instead of at the beginning. This means that any control variables can be defined within the loop instead of before it. It also means that a do...while loop will always iterate at least once, regardless of the value of its control condition.

EXAMPLE 4 Using a do..while Loop to Compute a Sum of Consecutive Integers This program has the same effect as the one in Ex1: int main() { int n,i=0; cout << "Enter a positive integer: "; cin >> n; long sum=0; do sum += i++; while (i <= n); cout << "The sum of the first " << n << " integers is " << sum; }

THE for STATEMENT The syntax for the for statement is –for (initialization; condition; update) statement; where initialization, condition, and update are optional expressions, and statement is any executable statement. The three-part (initialization; condition; update) controls the loop. The initialization expression is used to declare and/or initialize control variable(s) for the loop; it is evaluated first, before any iteration occurs. The condition expression is used to determine whether the loop should continue iterating; it is evaluated immediately after the initialization; if it is true, the statement is executed. The update expression is used to update the control variable(s); it is evaluated after the statement is executed. So the sequence of events that generate the iteration are: 1. evaluate the initialization expression; 2. if the value of the condition expression is false, terminate the loop; 3. execute the statement; 4. evaluate the update expression; 5. repeat steps 2–4.

EXAMPLE 5 Using a for Loop to Compute a Sum of Consecutive Integers This program has the same effect as the one in Ex1: int main() { int n; cout << "Enter a positive integer: "; cin >> n; long sum=0; for (int i=1; i <= n; i++) sum += i; cout << "The sum of the first " << n << " integers is " << sum; }

More Examples Using a Descending for Loop This program prints the first ten positive integers in reverse order: int main() { for (int i=10; i > 0; i--) cout << " " << i; }

Using a for Loop with a Step Greater than One This program determines whether an input number is prime: int main() { long n; cout << "Enter a positive integer: "; cin >> n; if (n < 2) cout << n << " is not prime." << endl; else if (n < 4) cout << n << " is prime." << endl; else if (n%2 == 0) cout << n << " = 2*" << n/2 << endl; else { for (int d=3; d <= n/2; d += 2) if (n%d == 0) { cout << n << " = " << d << "*" << n/d << endl; exit(0); } cout << n << " is prime." << endl; }; }

More Examples More than One Control Variable in a for Loop int main() { for (int m=95, n=11; m%n > 0; m -= 3, n++) cout << m << "%" << n << " = " << m%n << endl; } Nesting for Loops –This program prints a multiplication table: #include // defines setw() #include // defines cout using namespace std; int main() { for (int x=1; x <= 12; x++) { for (int y=1; y <= 12; y++) cout << setw(4) << x*y; cout << endl; }

THE break STATEMENT We have already seen the break statement used in the switch statement. It is also used in loops. When it executes, it terminates the loop, “breaking out” of the iteration at that point. EXAMPLE Using a break Statement to Terminate a Loop This program has the same effect as the one in Example 4.1 on page 60. It uses a break statement to control the loop: int main() { int n,i=1; cout << "Enter a positive integer: "; cin >> n; long sum=0; while (true) { if (i > n) break; sum += i++; } cout << "The sum of the first " << n << " integers is " << sum; }

Using a break Statement with Nested Loops Since multiplication is commutative (e.g., 3×4 = 4×3), multiplication tables are often presented with the numbers above the main diagonal omitted. This program print a triangular multiplication table: int main() { for (int x=1; x <= 12; x++) { for (int y=1; y <= 12; y++) if (y > x) break; else cout << setw(4) << x*y; cout << endl; }

THE continue STATEMENT The break statement skips the rest of the statements in the loop’s block, jumping immediately to the next statement outside of the loop. The continue statement is similar. It also skips the rest of the statements in the loop’s block, but instead of terminating the loop, it transfers execution to the next iteration of the loop. It continues the loop after skipping the remaining statements in its current iteration. EXAMPLE Using continue and break Statements This little program illustrates the continue and break statements: int main() { int n; for (;;) { cout > n; if (n%2 == 0) continue; if (n%3 == 0) break; cout << "\tBottom of loop.\n"; } cout << "\tOutside of loop.\n"; }