1 Loops & More WHILE loops FOR loops Range operator Running totals Random Numbers.

Slides:



Advertisements
Similar presentations
Chapter Chapter 4. Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times.
Advertisements

CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
Computer Science 1620 Loops.
Chapter 4 Repetitive Execution. 2 Types of Repetition There are two basic types of repetition: 1) Repetition controlled by a counter; The body of the.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
The University of Texas – Pan American
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 5: Control Structures II (Repetition)
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.
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014
1. Definition and General Structure 2. Small Example 1 3. Simplified Structure 4. Short Additional Examples 5. Full Example 2 6. Common Error The for loop.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
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.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
1. Example 1 – Averages 2. Example 2 – Rolling Dice 3. Example 3 – Number Analysis 4. Example 4 - Divisibility ( while ) Additional Examples on for Loops.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
2Object-Oriented Program Development Using C++ 3 Basic Loop Structures Loops repeat execution of an instruction set Three repetition structures: while,
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
1 Final Project Introduction 1. Final Project The descriptions provided here are only acting as summaries – please see the complete description on your.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CPS120 Introduction to Computer Science Iteration (Looping)
Review while loops Control variables Example Infinite loop
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
EGR 115 Introduction to Computing for Engineers Loops and Vectorization – Part 1 Monday 13 Oct 2014 EGR 115 Introduction to Computing for Engineers.
COMP Loop Statements Yi Hong May 21, 2015.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 4: Control Structures (Part 2) Xiang Lian The University of Texas – Pan American Edinburg, TX
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Introduction to Computer Programming
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
MATLAB: Structures and File I/O
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Control Structure Senior Lecturer
Outline Altering flow of control Boolean expressions
Iteration: Beyond the Basic PERFORM
Types of Flow of Control
Chapter 3 – Control Structures
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Faculty of Computer Science & Information System
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Loop Statements & Vectorizing Code
More Loops Topics Relational Operators Logical Operators for Loops.
Loop Statements & Vectorizing Code
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

1 Loops & More WHILE loops FOR loops Range operator Running totals Random Numbers

2 Review Review while loops while (time < 3.15) Review infinite loop while (true) Introduce for loop for x = 1:10 Introduce range operator x=1:10 or x=1:2:10 Sum elements in a loop Compute average of values Get min/max values from a loop

3 WHILE Loop - Review Generally you have a loop control variable This variable has 3 phases Initialization of variable Change of variable Condition to continue running the loop Example: the loop control variable is x x = 0;  1. initialization while ( x < 10)  2. condition x = x + 1;  3. change loop variable fprintf('%02d\n', x); end

4 Loops Review Infinite Loop  The loop condition never becomes false and the loop runs, and runs… Use CTRL-C in the command window to break it (or alt-F4 if infinite loop with dialog boxes)

5 Loop Review Why is this an infinite loop in MATLAB? x = 9; % 1. initialization while ( x > 10) % 2. condition fprintf('%02d\n', x); x = x + 1; % 3. change loop variable end

6 Trap a user for a value Ask a user for a value between 1 to 10 What if they don't give the proper value? Two approaches: –Ask first, then loop –Make bad and loop

7 Validate input, cont. Ask first, then loop: numValues = input('Value from 1-10: '); % ask first while (numValues 10) numValues = input('Error! Enter a value 1-10: '); end Make bad, then loop: numValues = -1; % makes loop run at least once while (numValues 10) numValues = input('Value from 1-10: '); end

8 FOR Loop Generally used for a fixed number of iterations You know you want to go from 1 to 100, by ones for syntax does all 3 parts of the loop in one line  initialization, change, condition for k = 1:100 disp(k); end The symbol : is a new operator, it's the range operator. The range is from 1 to 100, by ones. We say “in steps of one” If you want to loop in steps of 2, use 1:2:100

9 Range Operator [:] for loops use the range operator to specify a range of values to loop over (to iterate) Syntax: variable = start : increment : end : increment is optional – defaults to : 1 if omitted

10 Range Operator, cont. Examples: (in all examples, there is an implied loop body and end ) % loop 10 times for x = 1:10 % It is not necessary that the values be integers for y = 1.2 : 2.3 : % Can use negative steps for z = 10:-2:1 So… when does it stop? Steps of -2 will never “hit” the value of 1…

11 Range Operator, cont. The loop continues as long as the value is “in the range” specified for ctr=1:3:10 % as long as 1 <= ctr <= 10 for val=-5:2:5 % as long as -5 <= val <= 5 for thing=5:-3:0 % as long as 5 >= thing >= 0

12 FOR loops, cont. Which brings up a very important issue: It is possible to change the loop counter while in the body of a FOR loop This is normally not a good idea since the value will revert back in the next loop iteration

13 FOR loops, cont. for cnt=1:5 fprintf('%d\n', cnt); cnt = cnt * 2; end Output: >> Notice that the variable changed back at the top of the loop

14 Nested FOR loops Generate a table of output that looks like a clock for every second of the day for hr= 0:23 % all hours for day for min = 0:59 % all minutes per hour for sec = 0:5:59 % all seconds per min per hour fprintf('%02d:%02d:%02d\n', hr, min, sec); end Test the Code! Write a program that prints all days of the year for the decade, Year, Month, Days

15 Loops: Running Totals / Running Products Loops are useful for accumulating or summing values..computing averages, totals etc. (“running totals”, “running products”) Running total: –Start with a variable for the sum initialized to 0 sum = 0; –Each time through loop add a value to the sum: sum = sum + number; Running product: –Start with a variable for the product, initialized to 1 prod = 1; –Each time through loop, multiply: prod = prod * number;

16 Loops: Running total % initialize values total = 0; value = 0; %loop when value positive or zero while value >=0 fprintf( ' Negative values quit…\n ' ) value = input( ' Enter a positive integer: ' ); if value >=0 %add value if positive total = total + value ; end % of if end % of while %display result fprintf('total = %d\n ', total);

17 Loops: Compute Average 1.Initialize sum before the loop sum = 0; 2.Keep a running total in the loop: sum = sum + number; 3.After loop, divide by count average = sum / iterations;

18 FOR Loop: Average Generate 10 random values between 0 and 1 then compute average %initialize variables sum = 0; average = 0; %loop 10 times for x = 1:10 value = rand; %generate 1 random value ]0-1[ fprintf('value %02d is %.3f\n', x, value); sum = sum + value; end %calculate, display average average = sum / 10; fprintf ('the average is %.3f\n', average);

19 Output results Second run: value 01 is value 02 is value 03 is value 04 is value 05 is value 06 is value 07 is value 08 is value 09 is value 10 is The average is First run: value 01 is value 02 is value 03 is value 04 is value 05 is value 06 is value 07 is value 08 is value 09 is value 10 is The average is 0.558

20 FOR Loop: Roll Dice 10 times Combine the for loop, with ceil, and rand %loop 10 times for x = 1:10 %generate a die roll dice = ceil(rand*6); %display fprintf('roll %d is %d\n', x, dice); end roll 1 is 1 roll 2 is 6 roll 3 is 6 roll 4 is 5 roll 5 is 5 roll 6 is 5 roll 7 is 3 roll 8 is 4 roll 9 is 2 roll 10 is 5

21 Loops: Find Min / Max Trying to find a min value or max value First time through the loop, set the minimum and the maximum value to the number. if (count == 1) min = number; max = number; end Each subsequent time, determine if number is greater than maximum if so, change maximum to contain this new biggest value if (number > max) max = number; end There are also functions min() and max() – we will use them later with vectors & arrays

22 Loops: Find Min / Max N = input('How many values? '); for count=1:N number = input('Please give me a number: '); if count==1 min_val = number; max_val = number; end % of if if number > max_val max_val = number; end if number < min_val min_val = number; end end % of for

23 Taboos Don't use these words in your programs: global persistent break continue error exit quit MAJOR points lost for using these in your programs!

24 Combine FOR / rand() / mod() Write a program that picks 200 random integers between Determine how many are odd and how many are even Print out the # of odd values, # even values, and compute the percentages of odd and even values

25 An algorithm for ??? pick rand number if odd Increment odd counter else Increment even counter end % Compute odd percentage % Compute even percentage % Print out results Note counters need to be INITIALIZED to 0. Before or in the loop?

26 Solution % set up counters odd_cnt = 0; even_cnt = 0; %loop to create/analyze numbers for cnt=1:200 value = floor(rand()*100) + 1; if mod(value, 2) == 1 % odd number odd_cnt = odd_cnt + 1; else % even number even_cnt = even_cnt + 1; end %calculate/display results odd_pct = 100* odd_cnt / 200; even_pct = 100 * even_cnt / 200; fprintf('%.2f% were odd,', odd_pct); fprintf('and %.2f% were even\n', even_pct); Notice the lack of semicolons (;) in FOR and IF statements

27 How long to generate random #'s Write a program that generates random numbers from 1 – 100 Keep running program 'til every number gets one occurrence. That's an array problem, have to do that in a week or so…

28 Final Project Introduction

29 Final Project The descriptions provided here are only acting as summaries – please see the complete description on your section's website. Goal Create a project of your choosing within the constraints specified by your instructor. The goal of your project is to logically implement as many of the semester topics as possible, consistent with your project's purpose.

30 Final Project, cont. While all topics contribute to the grading of the project, heavy emphasis is assigned to the proper use of: Algorithm Complexity and efficiency Programmer-defined functions Loops File I/O

31 Final Project, cont. Connect 4 Hunting Database MP3 player Keyboard DDR Drum Hero Will a beam break? Fuel efficiency and gas cost Ball and wall collision Automatic toll system Forces in a car crash Electrical circuit analysis Examples of past projects: Audio Analysis Serial Port IM Thermistor Data Collection Bezier Curve Fit Unit Conversion Tournament Generation Deal or No Deal Load and moment distribution on a beam w/ plotting Captain's Jack Sparrow's magical compass

32 Final Project, cont. Possible areas for new projects: Genealogy Thermodynamics Computational Fluid Dynamics Image / Visual Processing Model Rocket / RC Plane Telemetry 2D / 3D environment modeling Orbital Mechanics

33 Final Project, cont. Extra Credit is provided for: Innovative project concepts Advanced programming techniques Exceptional program development

34 Final Project, cont. Today is Tuesday October 2, 2012 Projects will be due around December 5. This gives you about 8 weeks. - One week to pick a topic - Two weeks to plan and modify your design - Five weeks to code, revise, and test Past students have quoted about 30 hours dedicated to the project. If we assume virtually all of that was coding, you can plan on spending 6 hours per week on the coding portion – IF you give yourself enough time.

35 Final Project, cont. Begin planning! - Find an idea: what interests you? - Discuss with your instructor - Layout a plan for what it will entail - You should be coding by Oct. 22! - If you start early, there is time to revise