1. Example 1 – Averages 2. Example 2 – Rolling Dice 3. Example 3 – Number Analysis 4. Example 4 - Divisibility ( while ) Additional Examples on for Loops.

Slides:



Advertisements
Similar presentations
Chapter 5: Control Structures II (Repetition)
Advertisements

UNIT 3 PROBLEM SOLVING WITH LOOP AND CASE LOGIC STRUCTURE
 Control structures  Algorithm & flowchart  If statements  While statements.
Exercise 4 1. Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the.
Repeating Actions While and For 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.
True BASIC Ch. 6 Practice Questions. What is the output? PRINT X LET X = -1 PRINT X FOR X = 4 TO 5 STEP 2 PRINT X NEXT X PRINT X END.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
CS150 Introduction to Computer Science 1
1 10/9/06CS150 Introduction to Computer Science 1 for Loops.
CHAPTER 2 ANALYSIS OF ALGORITHMS Part 2. 2 Running time of Basic operations Basic operations do not depend on the size of input, their running time is.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
What is the out put #include using namespace std; void main() { int i; for(i=1;i
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 3P. 1Winter Quarter Structured Engineering.
BBS Yapısal Programlama (Structured Programming)1 From problem to program In “real world”… Problem in Natural language Top Down Design in pseudo-code.
Consecutive Numbers Algebra I.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
1 Loops & More WHILE loops FOR loops Range operator Running totals Random Numbers.
Library Functions... 1.Old functions 2.Vocabulary 3.Rounding numbers 4.Generating random numbers 5.mod() 6.Properties of mod() 7.Ex1: even or odd? 8.Ex2:
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.
More While Loop Examples CS303E: Elements of Computers and Programming.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
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.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Unit 2 – Algorithms & Pseudocode. Algorithms Computer problems solved by executing series of action in order Procedure –The Actions to execute –The Order.
EXERCISES for ALGORITHMS WRITING
Counter-Controlled Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Library Functions... 1.Old functions 2.Vocabulary 3.Rounding numbers 4.Generating random numbers 5.mod() 6.Properties of mod() 7.Ex1: even or odd? 8.Ex2:
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
1 Lecture 3 Control Structures else/if and while.
Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Lecture 5: Stopping with a Sentinel. Using a Sentinel Problem Develop a class-averaging program that will process an arbitrary number of grades each time.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Chapter 7 Problem Solving with Loops
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
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.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
Computer Science I: Understand how to evaluate expressions with DIV and MOD Random Numbers Reading random code Writing random code Odds/evens/…
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Pendalaman Materi Conditional dan Repetition (Pengulangan)
Lecture 5: Layers of Control. Nested while Loops Problem Multiplying two numbers and outputting the result only if they are both less than 5. (i.e. Start.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Computer Programming 12 Lesson 6 – Loop structure By: Dan Lunney.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (while) Outline 3.7The While Repetition.
Loops & More 1.Conditionals (review) 2.Running totals and Running products 3.the for loop, examples 4.Nesting for loops, examples 5.Common errors 1.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Algorithm: procedure in terms of
while Repetition Structure
Lecture 7: Repeating a Known Number of Times
for Repetition Structures
Consecutive Numbers Algebra I.
Repetition and Loop Statements
The for-loop and Nested loops
Intro to Nested Looping
Intro to Nested Looping
EPSII 59:006 Spring 2004.
Computer Science I: Get out your notes.
Incremental Programming
REPETITION Why Repetition?
Presentation transcript:

1. Example 1 – Averages 2. Example 2 – Rolling Dice 3. Example 3 – Number Analysis 4. Example 4 - Divisibility ( while ) Additional Examples on for Loops 1

Ex 1: average, algorithm Generate 10 random values (between 0 and 1) and compute average %initialize variables %loop 10 times %generate 1 random value ]0-1[ %display the value %calculate running total %calculate, display average 2

Ex 1: average, display result %initialize variables sum = 0; average = 0; %loop 10 times for x = 1:10 value = rand; %generates 1 random value ]0-1[ fprintf(‘value %02d is %.3f\n’, x, value); sum = sum + value; %running total end %calculate, display average fprintf(‘The average is %.3f.\n’, sum/10); 3

Ex 1: average, Output Result 4 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 >>

Ex 2: rolling dice, algorithm Prompt the user for the number of dice to roll. Generate that many random numbers (each between 1 and 6). Indicate all rolls on the screen, and display the sum of all dice. % prompt user how many dice to roll % set sum to zero % loop that many times %generate one value (between 1 and 6) %display value of each die %compute running total %display total 5

Ex 2: rolling dice, display % prompt user how many dice to roll totalDice = input(‘How many dice will you roll? ’); sumDice = 0; %set sum to zero % loop that many time for roll = 1:totalDice %generate one value (between 1 and 6) dieValue = ceil(rand*6); %display value of each die fprintf(‘Roll %d gave %d.\n’, roll, dieValue); %compute running total sumDice = sumDice + dieValue; end fprintf(‘Sum = %d\n’,sumDice); %display total 6

Ex 2: Output Result >> How many dice will you roll? 3 Roll 1 gave 2 Roll 2 gave 4 Roll 3 gave 6 Sum = 12 >> 7

Ex 3: Combine for / rand / mod Develop a program that generates 200 random integers between 1 and 100 both included. Count the nb. of odd values, nb. of even values, Also compute the percentages of odd and even values. Display all results to the screen. 8 Random Values Analyzer Nb. of odd values Nb. of even values % of odd values % of even values SCREENSCREEN (NO INPUTS)

Ex 3: An algorithm %loop to generate 200 whole numbers for %generate 1 random integer [1-100] if % odd Increment odd counter else %default to even Increment even counter end % Compute odd and even percentages % Print out results 9 Note: counters need to be INITIALIZED to 0. Before or inside the loop?

Ex 3: An algorithm %set up both counters at zero  CRUCIAL %loop to generate 200 whole numbers for %generate 1 random integer [1-100] if % odd Increment odd counter else %default to even Increment even counter end % Compute odd and even percentages % Print out results 10

Ex 3: Solution (1/2), analyzing % set up both counters at zero odd_cnt = 0; even_cnt = 0; %loop to create/analyze numbers for ct = 1:200 value = floor(rand*100) + 1; %generate integer if mod(value,2) == 1 %odd number odd_cnt = odd_cnt + 1; else %had to be even by default! even_cnt = even_cnt + 1; end 11 Notice the lack of semicolons (;) in FOR and IF statements Mod by 2 mod(2,2)0 mod(3,2)1 mod(4,2)0 mod(5,2)1 mod(6,2)0 mod(15,2)1

Ex 3: Solution (2/2), show results %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); 12

Ex 4: Display the first ten multiples of “5 and 7” Clear up the problem Start counting at 0 and display the first ten multiples of “5 and 7” together. For example: 35 is both a multiple of 5 and 7. The number of times the loop needs to count is unknown unless you previously solve the problem!!! Therefore a while loop is used. %while 10 numbers have not been displayed  this implies keeping track of how many numbers have been displayed. Use mod(.., 5) and mod(.., 7) combined. 13

Ex 4: algorithm number = 0; % start number at zero nb_displayed = 0; % set how many nb have been displayed to zero % while 10 nbs have not been displayed while nb_displayed <10 %could be: nb_displayed!=10 %if divisible by both 5 AND 7 if mod(number,5)==0 && mod(number,7)==0 disp(number) % display number % increment how many nb displayed by +1 nb_displayed = nb_displayed +1; end number = number +1; %go to next number end 14

Wrapping Up Go ahead, try to code these. See if you can make it run. Change them a bit: generate 20 high-scores (0 to 50) Find the maximum. Only count the top 5. Note that most examples required some nested construct within the loop. Only practicing with random little ‘dumb’ examples like these will help you… 15