Repetition Structures

Similar documents
Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Unit 7. Lesson 7.1. Loop. For Next Statements. Introduction. Loop

Iteration Loops. The Do While Loop (Continued) Looping Subtasks

Microsoft Visual Basic 2005: Reloaded

REPETITION CONTROL STRUCTURE LOGO

Decision Structures. Start. Do I have a test in morning? Study for test. Watch TV tonight. Stop

Chapter 8. Arrays and More Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of

To enter the number in decimals Label 1 To show total. Text:...

Year 12 : Visual Basic Tutorial.

Mr.Khaled Anwar ( )

Tutorial 03 understanding controls : buttons, text boxes

Programming Language 2 (PL2)

Introduction To Programming. Chapter 5: Arrays and More

VB FUNCTIONS AND OPERATORS

In this tutorial we will create a simple calculator to Add/Subtract/Multiply and Divide two numbers and show a simple message box result.

Review. October 20, 2006

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Copyright 2014 Pearson Education, Inc. Chapter 5. Lists and Loops. Copyright 2014 Pearson Education, Inc.

ECE 122. Engineering Problem Solving with Java

Repetition. October 4, Chapter 6 - VB 2005 by Schneider 1

You will have mastered the material in this chapter when you can:

DEVELOPING OBJECT ORIENTED APPLICATIONS

Loops / Repetition Statements

SNS COLLEGE OF ENGINEERING

Learning VB.Net. Tutorial 10 Collections

3. Can every Do-Loop loop be written as a For-Next loop? Why or why not? 4. Name two types of files that can be opened and used in a VB program.

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

SNS COLLEGE OF ENGINEERING,

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Learning VB.Net. Tutorial 19 Classes and Inheritance

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

C4.3, 4 Lab: Conditionals - Select Statement and Additional Input Controls Solutions

Computer Programming: C++

Control Structures II. Repetition (Loops)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

PROBLEM SOLVING WITH LOOPS. Chapter 7

Learning VB.Net. Tutorial 17 Classes

MIS 216 SPRING 2018 PROJECT 4

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Visual Basic 2008 The programming part

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Lab 3 The High-Low Game

Making Decisions and Working with Strings

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Chapter 2B: Lists and Loops

Repetition and Loop Statements Chapter 5

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

APPM 2460: Week Three For, While and If s

Chapter 5. Lists and Loops Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of

More about Loops and Decisions

ISM 3253 Exam I Spring 2009

Computing Science Unit 1

Why Is Repetition Needed?

Condition Controlled Loops. Introduction to Programming - Python

Laboratory 5: Implementing Loops and Loop Control Strategies

Programming with Visual Studio Higher (v. 2013)

Fundamentals of Programming Session 13

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Repetition Structures Chapter 9

Chapter 3 Structured Program Development

Introduction to Scientific Computing

Microsoft Visual Basic 2015: Reloaded

Over and Over Again GEEN163

CMPT 110 MIDTERM OCTOBER 18, 2001

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Increment and the While. Class 15

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Outline. Program development cycle. Algorithms development and representation. Examples.

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Quick Reference Guide

Introduction. C provides two styles of flow control:

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Lecture 7 Tao Wang 1

VISUAL BASIC II CC111 INTRODUCTION TO COMPUTERS

VISUAL BASIC 2005 EXPRESS: NOW PLAYING

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES


C Programming for Engineers Structured Program

STUDENT LESSON A12 Iterations

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

Microsoft Visual Basic 2015: Reloaded

Chapter 5: Loops and Files

11.3 Function Prototypes

Using loops and debugging code

Chapter 5: Control Structures II (Repetition)

COSC 122 Computer Fluency. Iteration and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Nonvisual Arrays and Recursion. by Chris Brown under Prof. Susan Rodger Duke University June 2012

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Java Outline (Upto Exam 2)

Transcription:

Repetition Structures There are three main structures used in programming: sequential, decision and repetition structures. Sequential structures follow one line of code after another. Decision structures follow code based on conditions. Programmers use the repetition structure (also called looping or iteration structure) to instruct the computer to repeat one or more instructions, either a specified number of times OR until a condition (known as the loop condition) is met. Within the repetition structures there are three forms: For Next, Do While and Do Until. Although any of the three forms of repetition structure can be used to repeat instructions a specified number of times, the For Next loop is usually used in these situations as it requires less coding. The FOR NEXT Loop Syntax: The For Next loop takes the form: For counter = startvalue To endvalue Step stepvalue statements Next counter The For Next loop (or automatic counter loop) repeats one or more statements a specified number of times. notice that the syntax begins with the FOR statement and ends with the Next statement counter is the name of a numeric variable that keeps track of the number of times the loop is processed the startvalue, endvalue and stepvalue items control how many times to process the loop startvalue tells the loop where to begin stopvalue tells the loop where to stop stepvalue determines how much to add to (or subtract from) the counter each time loop is processed if Step and stepvalue are omitted, then VB uses a value of +1 The For Next loop performs the following 3 tasks 1. The loop initializes the counter to the startvalue. This is done just once at the beginning. 2. If stepvalue is positive, the loop checks to see if counter is greater than endvalue (if stepvalue negative then loop checks if counter less than endvalue). If it is, the loop stops, if not, then the loop statements are processed.

3. The loop adds the stepvalue onto the counter and repeats steps 1-2 until counter is greater than (or less than if stepvalue is negative) endvalue. In the example below the variable intcount is the counter, the startvalue is 1, the endvalue is 20 and the stepvalue is +1 For intcount = 1 to 20 txtcounter.text = intcount Next intcount Start Declare intcount variable for counter The For Next loop is represented in the flowchart by a hexagon. Four values are recorded inside the hexagon: the name of the counter, the startvalue, endvalue and stepvalue. Note that the endvalue is preceded by a > (greater than sign) intcount 1 >20 1 display intcount Stop The loop initializes the counter (intcount) to the startvalue 1. Loop then compares the current value of the counter to the end value. While every value of counter is less than 20, the loop continues and prints value of intcount. Finally the loop increments the counter by the step value 1, then the program flow loops back

Counters and Accumulators Counters are often required in algorithms to keep track of the number of times a user does something, such as the number of times a mark is entered in order to calculate an average. Counters are variables that are incremented by a constant value. The statement for incrementing or updating a counter takes the form: counter = counter + constant In an assignment statement, the expression on the right side of the equals sign is evaluated first and is then assigned to the variable on the left hand side. This makes it possible to use the current value of counter in the expression itself. Example intcounter = intcounter + 1 The above increments counter by + 1 each time statement executed A counter should be initialized when it is declared as a static variable, thus it will only be initialized once. Accumulators are useful for keeping a running total or sum of values, such as the total dollar value of items purchased. Accumulators are incremented by changing amounts. The statement for incrementing or updating an accumulator takes the form: accumulator= accumulator + value Example: sngtotal = sngtotal + sngitemcost The above adds value of sngitemcost to sngtotal each time the statement is executed

Lab #9 ~ Factorials The factorial of a number is the product of all the positive integers from 1 to the number. For example, 3 factorial, written as 3! = 3*2*1 = 6. Create an application using a For Next loop to compute the factorial of a number. Interface Form frmfactorial Factorial Calculator Label lblenternumber Enter A Number Text Box txtnumber Button cmdcalculate Calculate Factorial Label Label lblfactorialmessage lblfactorial Variables o Number o Factorial o Counter - integer entered by the user - integer result -integer to keep track of loop counter to number. Flowchart Start Get the number from the user. intcounter 1 >Number 1 Factorial = factorial *intcounter Display factorial End What does the pseudocode look like?

Code: Factorial Calculator written by your computer teacher, this day updated by you, today Public Class frmfactorial ***************************** Calculates the factorial based on the number enetered by the user. post: The factorial is shown in a label. Private Sub cmdcalculatefactorial_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdcalculatefactorial.click variables declared - only used within this procedure Dim intnumber As Integer Dim intfactorial As Integer Dim intcounter As Integer intnumber = Val(txtNumber.Text) get number from user intfactorial = 1 factorial must be initialized to one (otherwise multiply by zero) For intcounter = 1 To intnumber intfactorial = intfactorial * intcounter Next intcounter lblmessage.text = "Factorial is: " lblfactorialresult.text = intfactorial ***************************** Resets the labels for the answer so that when the user enters a new number, the result is cleared. post: The labels for the answers are cleared. Private Sub txtnumber_textchanged(byval sender As System.Object, ByVal e As System.EventArgs) Handles txtnumber.textchanged lblmessage.text = Nothing lblfactorialresult = Nothing End Class Save often as you work through this lab and test that your program works.

The Do While and the Do Until Loops When it is not known exactly how many times the loop will be required to repeat a set of instructions, then a Do While loop or Do until loop must be used. Both loops require a condition which often contains variables, mathematical, relational or logical operators. Just like the condition in an If Then Else statement, the loop condition must also evaluate to True or false. The condition determines if the loops statements or will be executed. Syntax: The Do While loop takes the form: Do While condition statements Loop Syntax: The Do Until loop takes the form: Do statements Loop until condition The Do While loop repeats one or more statements while a condition is true. The Do While loop begins with the Do While statement and ends with the Loop statement. The condition is located at the start of the loop and loop statements are only executed if the condition evaluates to True. If the condition evaluates to False, then the statements are not executed. Programmers call the Do While loop a pre-test loop as the loop tests the condition before executing any statements in the loop. Depending on how the condition evaluates, the statements in a Do While loop may not be executed at all. The Do Until loop repeats one or more statements until a condition becomes true. The Do Until loop begins with the Do statement and ends with the Loop Until statement. The condition is located at the end of the loop and loop statements are only executed if the condition evaluates to False. If the condition evaluates to True, then the statements are not executed again. Programmers call the Do Until loop a post-test loop as the loop tests the condition only after executing the statements in the loop. The statements then in a Do Until loop are always executed at least once.

Examples: Dim intcount as integer intcount = 1 Do While intcount <= 3 Print intcount intcount = intcount + 1 Loop Dim intcount as integer intcount = 1 Do Print intcount intcount = intcount + 1 Loop Until intcount > 3 Lab # 10 ~ Average Scores The average of a set of scores is calculated by dividing the sum of the scores by the number of scores. Use one text box to enable user to enter as many scores as they would like, until a -1 is entered. The text box should be disabled until the user clicks the Enter Scores button. The form should look as follows, with the following control names and text: Form frmaveragescore Average Score Calculator labels lblinformation Select Enter Scores lblnumberscores lblaveragemessage lblaverage lblsumofscores # of Scores The Average is: Average Sum of Scores Buttons cmdenterscores Enter Scores cmdaveragescore Average Score Variables Number of scores integer, declared globally Sum of scores integer to represent the total of the scores entered tempscore string that represents the entered value new score to represent the value of the temp score FLAG constant to represent -1 (entered to indicate the end of the scores

Pseudocode: cmdenterscores_click Prompt user to enter score Do while entered score is not equal to Nothing and the score is not equal to -1 Increment counter by 1 Score = value of entered score Add score to sum of scores Prompt user for next score Loop Show sum of scores Show number of scores that have been entered cmdaveragescores If the number of scores = 0, then Average = 0 Else Average = sum of scores entered / number of scored entered Display the average in the label. End if

Code: Average Score Calculator written by your computer teacher, this day updated by you, today Users enter scores in Input Boxes and an entry of -1 terminates entering scores. Public Class frmaveragescores global variables Dim intnumberofscores As Integer Dim intsumofscores As Integer ******************************** Gets the scores from the user in the form of input boxes. -1 is entered to indicate the end of entered scores. post: sum of the scores and the number of scores entered Private Sub cmdenterscores_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdenterscores.click Const FLAG As Integer = -1 Dim strtempscore As String Dim intnewscore As Integer lblaverage.text = Nothing lblnumberofscores.text = 0 get scores strtempscore = InputBox("Enter a score [ -1 to stop]", "Scores") Do While strtempscore <> Nothing And Val(strTempScore) <> -1 intnewscore = Val(strTempScore) intnumberofscores = intnumberofscores + 1 intsumofscores = intsumofscores + intnewscore strtempscore = InputBox("Enter a score [ -1 to stop]", "Scores") Loop lblsumofscores.text = intsumofscores lblnumberofscores.text = intnumberofscores ******************************** Calculates the average of entered scores pre: the number of scores and the sum of the scores entered post: the average is displayed for the user Private Sub cmdaveragescore_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdaveragescore.click Dim sngaverage As Single

If intnumberofscores > 0 Then sngaverage = intsumofscores / intnumberofscores lblaverage.text = sngaverage Else lblaverage.text = 0 End If End Class Save often as you work through this lab and test that your program works.

Lab #11 ~ Fibonacci Sequence A Fibonacci sequence is a sequence of numbers that is generated from 2 starting values called seeds. The 2 seeds are the first 2 numbers in the sequence. The seeds are then added together to generate the third number in the sequence. Each additional number is created by adding the 2 previous numbers. For example if the 2 seeds are 1 and 1, then the sequence is 1, 1, 2, 3, 5, 8 while seeds of 3 and 6 will generate 3, 6, 9, 15, 24 Create an application that gets 2 seed values from the user that will generate a Fibonacci sequence of 50 numbers. To display such a long series of numbers you should use a textbox rather than a label. Use the Textbox properties below to display the sequence. Dock setting dock to bottom sizes textbox so bottom right and left borders are anchored to the form ReadOnly set to True when textbox used to display info, user cannot type into it Multiline set to true to display multiple lines WordWrap set to true to wrap lines of text Scrollbars set to vertical to allow vertical scrolling The Form should look as follows with the property changes listed: Form frmfibonacci Fibonacci Sequence Builder Labels lblfirstnumber First Number Text Boxes txtfirstnumber txtsecondnumber lblsecondnumber lblinformation lblfibonaccisequence Second Number Enter two numbers Fibonacci Sequence txtsequence Button cmdgenerate Generate Sequence

One possible solution is: Code: Fibonacci Sequence Calculator written by your computer teacher, this day updated by you, today Users enters two numbers and a Fibonacci like sequence is generated from these numbers and displayed for the user. Public Class frmfibonacci Generates the list of numbers based on two entered post: Fibonacci like sequence displayed if two numbers are entered. Private Sub cmdgenerate_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles cmdgenerate.click variables Dim lngfirstnumber As Long Long used otherwise overflow error Dim lngsecondnumber As Long Dim intcounter As Integer Dim lngnextnumber As Long End If End Class If txtfirstnumber.text = Nothing Or txtsecondnumber.text = Nothing Then MessageBox.Show("You must enter two numbers", "Two Numbers Required") Else lngfirstnumber = Val(txtFirstNumber.Text) lngsecondnumber = Val(txtSecondNumber.Text) txtsequence.text = lngfirstnumber & ", " & lngsecondnumber loop to generate next 48 numbers in sequence For intcounter = 3 To 50 lngnextnumber = lngfirstnumber + lngsecondnumber lngfirstnumber = lngsecondnumber lngsecondnumber = lngnextnumber txtsequence.text = txtsequence.text & ", " & lngnextnumber Next intcounter Can you think of another? Infinite Loops Logic errors can lead to infinite loops. If the program stops responding (cannot click on anything), right-clicking on the Windows Taskbar and selecting Close from the menu, and then select Close the Program to end the application.