Week 4: Control Structures - Repetition

Slides:



Advertisements
Similar presentations
Lecture 3: Control Structures - Selection BJ Furman 10SEP2012.
Advertisements

Session 5 JavaScript/JScript: Control Structures II Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Introducing Algorithms, Pseudocode and.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
true (any other value but zero) false (zero) expression Statement 2
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
C++ for Engineers and Scientists Third Edition
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Flow of Control Java Programming Mrs. C. Furman January 5, 2009.
Control Structures Session 03 Mata kuliah: M0874 – Programming II Tahun: 2010.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (Switch, do-while, break) Outline 4.7The.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 04 Control Statements: Part II. OBJECTIVES In this part you will learn: if…else Double-Selection Statement. while Repetition Statement.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Lecture 2 Control Structure. Relational Operators -- From the previous lecture Relational Operator Meaning == is equal to < is less than > is greater.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CHAPTER#3 PART1 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc.
Week 8: Decisions Bryan Burlingame 21 October 2015.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter#3 Part1 Structured Program Development in C++
CPS120: Introduction to Computer Science Decision Making in Programs.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
CPS120: Introduction to Computer Science Decision Making in Programs.
C++ Programming Lecture 5 Control Structure I (Selection) – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
 2003 Prentice Hall, Inc. All rights reserved. 1 Basic C++ Programming.
Control Statements: Part1  if, if…else, switch 1.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - JavaScript: Control Structures II Outline 9.1 Introduction 9.2 Essentials of Counter-Controlled.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Branching statements.
Introduction to Computer Programming
Chapter 4 – C Program Control
The if…else Selection Statement
REPETITION CONTROL STRUCTURE
- Standard C Statements
JavaScript: Control Statements I
Engineering Problem Solving with C++, Etter/Ingber
CSC113: Computer Programming (Theory = 03, Lab = 01)
JavaScript: Control Statements.
JavaScript: Control Statements I
Structured Program
3 Control Statements:.
Control Statements Paritosh Srivastava.
Presentation transcript:

Week 4: Control Structures - Repetition BJ Furman 17SEP2012

The Plan for Today Review control structures Repetition structures Sequence Selection Repetition Repetition structures While Do/While For Repetition structure example

Learning Objectives Explain the three basic types of control structures Explain how the three kinds of repetition structures work Apply the concept of repetition control structures to a practical problem

Control Structures - Review All programs can be written in terms of three control structures (like building blocks) Sequence ‘Built-in’ to C Unless otherwise directed, one statement after the next is executed Selection (three types: IF, IF-ELSE, SWITCH) Depending on a condition, select between one statement or another If var1 is greater than 10, do this…, else do that… Repetition (three types: WHILE, DO-WHILE, FOR) Depending on a condition, execute one or more statements repeatedly Your first programs were simply been a grouping of statements, which are executed one after the next from the beginning of the program to the end. This, ‘one after the next’ flow of a program is called a sequence structure. Such simple, sequential programs have their place, but there is much more that can be done by applying the other two control structures: selection and repetition, to control the flow of which statements are executed. In this lecture, we are going to look into the third control structures: repetition

Selection Structure - Review Three kinds of selections structures IF (also called, ‘single-selection’) if condition is true Perform action if condition is false, action is skipped IF/ELSE (also called, ‘double-selection’) else (if condition is false) Perform a different action SWITCH (also called ‘multiple-selection’) Allows selection among many actions depending on the value of a variable or expression

Repetition Structure Often need to repeat an action or calculation Ex. Find and print the distance traveled by an object dropped from a height at t = 0 sec each second over the next 10 seconds Repetition structures are often called ‘loops’ t=10 Up until now, you would have had to write 10 lines of code to calculate D at t=0, 1, 2, … 10 seconds and 10 print statements. This would be tedious to say the least! Let’s use the repetition structure to leverage what the computer can do well (execute actions quickly). A dynamics problem (ME 101) mg Equation of motion

3 Types of Repetition Structures while do/while for while tests a condition at the beginning of the loop condition must first be true for the loop to run even once do/while tests a condition at the end of the loop loop will run at least once for facilitates initializing and incrementing the variable that controls the loop Especially helpful for: Looping for a known number of times Loops that count or that need to increment a variable

while Loop – Pseudocode wording WHILE condition is TRUE, repeat: Statement1 Statement2 Etc. END WHILE

while Loop - Flowchart View Statement is executed while condition is true Note that the condition must first be true in order for the statement to be executed even once statement TRUE FALSE condition

while loop C syntax statement1; /* execute this statement */ General form of a while loop: while(condition) /* while condition is TRUE (i.e., ! = 0) */ statement1; /* execute this statement */ When condition becomes false (i.e. == 0), looping stops and the next statement is executed Compound statement form: while(condition) { statement1; statement2; statement3; // etc. } As the flow of control enters the while loop, the expression is evaluated. If the expression is not equal to zero (i.e. true), then statement1 is executed. The expression is evaluated again, and if it is not equal to zero (i.e. true), then statement1 is executed. The process is repeated until the expression becomes false. Then statement1 is skipped, and control goes to the next statement after statement1. If you put a semicolon at the end of the while (condition) line, this is equivalent to telling the program to do nothing while the result of the condition evaluation is non-zero). Basically the program will sit looping at that line until the condition evaluates to zero!!!

Distance Dropped Program Development Define the problem Calculate and print the distance traveled each second by an object dropped from a height in a standard gravitational field beginning at t = 0 sec over the next 10 seconds Simplify Assume v0 and d0 are both zero Inputs – are there any? Outputs time distance No inputs are required from the user under the specifications of the problem.

Solution Algorithm Pseudocode Start Declare variables: ____ Flowchart Declare variables t <= 10? print t, d Start Initialize variables t = t +1 T F Stop Pseudocode Start Declare variables: ____ d (distance traveled) t (time) (Are these good names?) Initialize variables While time is less than or equal to 10 s calculate d print time print distance increment time Stop while loop Go over the pseudocode and show the equivalence of the flowchart. distance would be a better name than d for the distance travelled, and time would be a better name than t for the time

Solution Code free_fall_d_vs_time.c Implements the program for the freely falling mass Show code in a separate file, like in PDF format, so you can zoom. How might this program be improved? Prompt user for end time Prompt user for time increment Declare and initialize in one line

Practice - Procedure Procedure Write code from flowchart or pseudocode Divide into groups of 4 Introduce yourselves Together (all four in the group) Define the problem Determine inputs and outputs Split into pairs (sub-groups) One pair – pseudocode the algorithm Other pair – flowchart the algorithm Swap one from each pair and share pseudocode and flowchart Write code from flowchart or pseudocode

Practice - Problem Write a program that calculates the average exam score for a class Specifications Prompts user for the number of scores to average Prompts user for each score Echoes each score entered Calculates the average score Prints out the average score

Practice - Solution

do/while Loop Structure General form of a do/while loop: do statement1; /* execute this statement */ while (condition); /* while condition is TRUE */ When condition becomes false, looping stops, and the next statement after the while is executed Note: statement1 will be executed at least once Remember: to DO more than one statement in the loop, enclose the statements in curly braces { } called a compound statement As the flow of control enters the while loop, statement1 is executed. The loop continues if condition is not equal to zero (i.e. true). Note that statement1 is executed at least once, even if condition is false.

do/while Structure – Flow Chart statement is executed at least once statement TRUE FALSE condition

for Loop Structure General form of a for loop: for(expression1; expression2; expression3) statement1; /* execute this statement */ expression1 initializes the variable controlling the loop i = 0; expression2 is the condition for continuing the loop i <= 10; expression3 increments the control variable i++ /* same as i=i+1 */ Note that there is NO semicolon after expression3! or after the closing parenthesis To execute more than one statement in the for loop, enclose them in curly braces { } The for loop gathers together in one line the elements needed to control the loop. This is helpful when the expression1 and expression3 are simple assignment and expression3 is a relatively straightforward relational expression. While and for loops are interchangeable and a matter of preference.

for Loop Structure – Flow Chart expression1 T F expression2 statement expression3 Initializes the loop control variable: ex. i = 0; Tests the loop control variable to see if it is time to quit looping: ex. i < 10; Increments the loop control variable: ex. i++

for Loop Example double_it.c Prints out a table of integers from 0 to 10 in one column and twice their value in a second column Show program from Ch in pdf

break and continue Statements break immediately exits from a loop Recall its use in the switch selection structure continue skips remaining statements in the body of a repetition structure int x; for(x=1; x<=10; x++) { if(x == 5) break; printf("%d ", x); } printf("Broke out at x == %d\n",x); 1 2 3 4 Broke out at x == 5 int x, y; for(x=1; x<=10; x++) { if(x == 5) y = x; continue; } printf("%d ", x); printf("Skipped x == %d\n",y); 1 2 3 4 6 7 8 9 10 Skipped x == 5 In the for loop, the increment expression is executed, then the loop-continuation test is evaluated. Adapted from Deitel & Deitel, C How to Program, 3rd ed., p. 119

Appendix – Recap of Selection Structures

Selection Structure Three kinds of selections structures if (also called, ‘single-selection’) if condition is true Perform action if condition is false, action is skipped if/else (also called, ‘double-selection’) else (if condition is false) Perform a different action switch (also called ‘multiple-selection’) Allows selection among many actions depending on the value of a variable or expression

IF statement (single-selection) Syntax if(expression) /* if expression is TRUE (not equal to zero) */ statement1; /* then execute this statement */ statement2; /* otherwise execute this statement */ Notes Indent statements Can have multiple statements Enclose a ‘block’ of statements using { } (curly braces) if( x <= 2 ) { statement1; statement2; } statement3; Note: an expression is an entity that evaluates to a single number. An expression is TRUE if it is non-zero. Example if(7), is the expression true or not? The block of statements is called a ‘compound’ statement. Note how the curly brackets are aligned, and how the statements in the block are indented, so that it makes it obvious where the block begins, where it ends, and which statements make up the block. Note comments. Two styles will work for most C compilers: /* */ the clean C version and // the C++ version

IF statement example Pseudocode (notice indentation!) C code If speed is greater than 65 mph print “You’re speeding!” C code if(speed > 65) printf(“You’re speeding!\n”); C code with statement block /* statements below executed only if speed > 65 is true */ { printf(“Slow down!\n”); printf(“Keep speed below 65 MPH\n”);

Single Selection IF - Flowchart connector Print “You’re speeding!” TRUE FALSE Speed > 65 flow line action symbol decision symbol

IF-ELSE statement - Double Selection Syntax if(expression) /* if expression is TRUE */ statement1; /* execute this statement */ else /* else execute the following statement */ statement2; Notes: If expression is non-zero, statement1 is executed, then the program continues with the statement after statement2, i.e., statement2 is skipped If expression is equal to zero, statement1 is skipped and statement2 is executed, then the program continues with the statement after statement2

Double-Selection IF - Flowchart FALSE TRUE Print “Within limit” Speed > 65 Print “Over speed limit!”

IF-ELSE statement example Pseudocode (notice indentation!) If speed is greater than 65 mph print “Over speed limit!” else print “Within speed limit” C code if(speed > 65) printf(“Over speed limit!\n”); printf(“Within limit\n”);

Relational Operators Important for constructing the decision expression Practice 5 < 7 result is ____ 5 > 7 result is _____ 7 <= 7 result is ____ 8 >= 7 result is ____ 5 == 5 result is ____ 5 == 7 result is ____ 5.0 == 5 result is ___ 6 != 5 result is ____ Discuss these Adapted from H. Cheng chap04.ppt, slide 5

Compound Condition - && Logical operators for more complex decisions Logical AND operator && (double ampersand) if(switch1 = = 0 && switch2 = = 1) turn on the motor The condition evaluates to TRUE if and only if BOTH expressions on either side of && evaluate to TRUE Note operator precedence Otherwise condition evaluates to FALSE Beware of ‘short circuit evaluation’ Make the condition most likely to be FALSE the left-most condition Note that evaluation of the condition continues until the truth or falsity of the condition is determined. Thus, if switch1 is not equal to zero, the compound condition is false, and the second relational test will not be done!

Compound Condition - | | Logical operators for more complex decisions, cont. Logical OR operator | | (double vertical bar) if(switch1 = = 0 || switch2 = = 1) turn on the motor The condition evaluates to TRUE if one or the other or both expressions on either side of && evaluate to TRUE Note operator precedence Otherwise condition evaluates to FALSE Beware of ‘short circuit evaluation’ Make the condition most likely to be TRUE the left-most condition Note that evaluation of the condition continues until the truth or falsity of the condition is determined. Thus, if switch1 is not equal to zero, the compound condition is false, and the second relational test will not be done! See p. 118 in D&D

Nesting selection structures Selection structures can be stacked and nested to handle more sophisticated decision/action functionality Ex. Figuring grades Pseudocode  Notes: “an else is always associated with the nearest previous if” (Darnell & Margolis, 1996) Use braces ({ })to clarify the association of the else for other situations where the decision structure is more complicated Grade Determination for Overall Percentage (OP) OP >= 90 ‘A’ 80 <= OP < 90 ‘B’ 70 <= OP < 80 ‘C’ 60 <= OP < 70 ‘D’ OP < 60 ‘F’ Adapted from Deitel & Deitel, C How to Program, 3rd ed., p. 64

Nesting If/else – C Code – Two Ways Or Adapted from Deitel & Deitel, C How to Program, 3rd ed., p. 64

SWITCH Good when faced with testing multiple alternatives that depend on a single variable The test is done once Must be an integral expression int or char NOT float, double case items must be constant integral expressions No variables The structure is very organized and readable

SWITCH - Flowchart Adapted from Deitel & Deitel, C How to Program, 6th ed., p. 111

Review 38

References Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York. Cheng, H. H. (2010). C for Engineers and Scientists: An Interpretive Approach, McGraw-Hill, New York. Deitel, H. M. & Deitel, P. J. (2001). C How to Program, 3rd ed., Prentice-Hall, New Jersey. 39

Nesting selection structures Selection structures can be stacked and nested to handle more sophisticated decision/action functionality /* File: ifc.c */ #include <stdio.h> int main () { int i; i = 10; if(i==2 || i == 4) printf("i = 2 or 4\n"); } else if(i == 10) printf("i = 10\n"); else printf("i = %d\n", i); return 0; Adapted from H. Cheng chap05.ppt, slide 12

Operators Adapted from H. Cheng chap04.ppt, slide 5