CS 1023 Intro to Engineering Computing 3: Computer Programming Looping Statements Mark Kerstetter Department of Computer Science Western Michigan University.

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
CS0004: Introduction to Programming Repetition – Do Loops.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Repeating Actions While and For Loops
ITC 240: Web Application Programming
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.
More loops Horstmann Ch 7 continued.. The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition?
Do Loops A Do..Loop terminates based on a condition that is specified Execution of a Do..Loop continues while a condition is True or until a condition.
Chapter 5: Control Structures II (Repetition)
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
More loops Linag, Chpt 3, pp The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition? loop-body.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
The switch Statement, DecimalFormat, and Introduction to Looping
Java Unit 9: Arrays Declaring and Processing Arrays.
CIS 115 Lecture 8. There are 3 control structures common to most computer languages that determine the flow, or path of execution, of the code:  Sequential.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
CPS120 Introduction to Computer Science Iteration (Looping)
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
CPS120: Introduction to Computer Science Decision Making in Programs.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
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,
Algorithm Design.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CPS120 Introduction to Computer Science Iteration (Looping)
Loops and Files. 5.1 The Increment and Decrement Operators.
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.
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 Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
While ( number
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
PHY 107 – Programming For Science. Today’s Goal  How to use while & do / while loops in code  Know & explain when use of either loop preferable  Understand.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
REPETITION CONTROL STRUCTURE
Department of Computer Science Western Michigan University
Chapter 3: Decisions and Loops
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Looping and Repetition
Presentation transcript:

CS 1023 Intro to Engineering Computing 3: Computer Programming Looping Statements Mark Kerstetter Department of Computer Science Western Michigan University © Spring 2012

Conditions n n Generally used to control what to do next? n n Expressions that evaluate to True or False n n In C Programs conditions … o Follow keyword if o Follow keyword while o Contained within ( and ) n n Relational Operations: >=, >, = =, !=, <, <= o Compare numeric expressions o Compare characters and character strings n n Boolean (Logical) Operations: ! (not), && (and), | | (or) o Only used with logical expressions, i.e., those whose values are True or False o Never used with numeric or character expressions Important! = does not compare = = compares => and =< and =! are not legal

Looping Statements n Flow Control Statements – Repeating Instructions (Loops) Three kinds of loops o while-loop-statement – pre-test loop o do-while-loop-statement – post-test loop o for-loop-statements – counting loop n When to use loops? o Write pseudo code simply. Note repeated patterns. Repeats indicate loop. F E.g. Read 1 st x & y coordinates, Write coordinates, Read 2 nd x & y coordinates, Write coordinates, Read 3 rd x & y coordinates, Write coordinates, etc. F E.g., Calculate first tax return, calculate the next tax return, calculate the next tax return, calculate the next tax return, etc. n Loops vs. Selections o Do NOT use a loop to make an either-or decision. Use an if or if-else. o Use loops to repeat statements.

while-loop Statement n Flow Control Statements – Repeating Instructions (Loops) o while-loop statement – pre-test loop F Always checks at the beginning of another potential loop F Enters the “body of the loop” (repeating statements) another time when the condition is true. F while (condition) { statement(s) to be repeated another time ; } 1.{ and } needed to surround multiple statements that need to be repeated. 2.Value altering the condition must change within the body. ; while-statement ends here! Caution! A common mistake when writing while-loops or for-loops is to place a semicolon immediately at the end of the first line of the loop statement thus creating an empty loop. ? Body of Loop F T

Examples of while-loop Statement while (forestedAcres < desiredLimit) { /* Calculate new growth using formula */ /* Compute forestedAcres from new growth and established growth, i.e. previous forestedAcres */ } Timber Regrowth Simulation while (1==1) { printf(“This is the song that never ends,\n”); printf(“It just goes on and on my friend\n“); printf(“Some people started sing it, not knowing what it was,\n”); printf(“And they’ll continue singing it forever just because -\n”); } Song that Never Ends! What controls # of repeats? Variables in condition that control while-loop. 1. forestedAcres 2. desiredLimit The body of the loop must contain statements that cause one or more of these variables to change or the loop may never end! Infinite Loop!

do-while-loop Statement n Flow Control Statements – Repeating Instructions (Loops) o do-while-loop statement – post-test loop F Always executes the body of the loop at least once F Checks the condition at the bottom of the loop and repeats the “body of the loop” when the condition is true F do { statement(s) to be repeated another time ; } while (condition) ; 1.{ and } needed to surround multiple statements that need to be repeated. 2.Value altering the condition must change within the body. do-while-statement ends here! Statements end with a semicolon (;). F ? Body of Loop T

Examples of do-while-loop Statement do { /* Play Next Game */ printf(“Want to play again? “); } while (getchar() == ‘Y’); Computer Games do { /* Enter Next Transaction */ printf(“Want another transaction? “); answer = getchar(); } while (answer == ‘Y’ || answer == ‘y’); ATM Transactions do { /* Play Next Game */ printf(“Want to play again? “); answer = getchar(); } while (answer == ‘Y’ || answer == ‘y’); Better Alternative Code Declare answer to contain character data type. char answer; ? Body of Loop T F

n Flow Control Statements – Repeating Instructions (Loops) o for-loop-statements – counting loop F Used to repeat some instructions a specified number of time repeat count known before starting the loop F Can count up or count down… in single unit steps, e.g., +1 or -1 In multiple unit steps, e.g., in 2’s, 3’s, -5’s etc. F Acts like a while-loop since it tests before attempting the body F for ( starting value; stopping condition; how value changes ) { statement(s) to be repeated ; } for-loop Statement 1.{ and } needed to surround multiple statements that need to be repeated. 2.Control variable keeping track of the count can be used inside the body, but should not be changed inside the body. ; for-statement ends here! Caution! A common mistake when writing while-loops or for-loops is to place a semicolon immediately at the end of the first line of the loop statement thus creating an empty loop. ? Body of Loop F T loop control variable initialized, tested, and updated

Examples of for-loop Statement for (year=1; year<=20; ++year) { /* Compute the timber growth for*/ /* the next year and display it */ } Timber Growth Table for (k=1; k<=50; ++k) { /* Process Next Item in List */ } Process a List of Items for (beer=99; beer>=3; --beer) { printf(“%2d bottles of beer on the wall,\n“, beer); printf(“%2d bottles of beer!\n”, beer); printf(“Take one down, and pass it around.\n”) printf(“%2d bottles of beer on the wall.\n\n”, beer – 1); } 99 Bottles of Beer! Another Example Forest Regrowth Make a table of forest regrowth for 20 years using the annual regrowth formula. ? Body of Loop F T

Examples of for-loop Statement for (row=1; row<=50; ++row) { for (column=1; column<=25; ++column) { /* Display Next Table Entry */ printf(“%8.2f ”, table[row,column]); } printf(“\n”); } Display Tables degToRad = 2*3.142/360; for (degrees=0; degrees<=360; degrees = degrees + 15) { printf(“%3d\t%10.4f\n”, degrees, sin(degrees*degToRad)); } Step Sizes Other than +1 or -1 Nested Loops A nested loop is one loop inside of another loop. Here we use the first loop to establish a table’s row index and the inner loop to get the element column index.. This example of an array element will be explained in a later class.