SlideShare une entreprise Scribd logo
1  sur  38
Chapter 6 Loop structures
Introduction This chapter introduces: Input boxes List boxes Counters and accumulators Compound operators Loops Data validation DataTips Publishing an application with ClickOnce technology Chapter 5 – Slide 2
Chapter 5 – Slide 3 Overview An input box provides a quick and simple way to ask the user to enter data User types a value in the text box OK button returns a string value containing user input Cancel button returns an empty string Should not be used as a primary method of input Convenient tool for developing & testing applications
General Format Chapter 5 – Slide 4 InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos])
Example Usage To retrieve the value returned by the InputBox function, use the assignment operator to assign it to a variable For example, the following statement assigns the string value returned by the InputBox function to the string variable strUserInput The string value that appears inside the text box will be stored in the strUserInput variable after the OK button is clicked and the input box closes Chapter 5 – Slide 5 Dim strUserInput As String = InputBox("Enter the distance.",                                                                          "Provide a Value",                                                                          "150")
A ListBoxcontrol displays a list of items and also allows the user to select one or more items from the list Displays a scroll bar when all items cannot be shown To create a ListBox control: Double-click the ListBox icon in the Toolbox window Position and resize the control as necessary In Design mode, the list box appears as a rectangle The size of the rectangle determines the size of the list box Use the lst prefix when naming a list box (lstListBox) Listbox Overview
The Items Property The entries in a list box are stored in a property named Items The Items property holds an entire list of values from which the user may choose The list of values may be established at design time or runtime  Items are stored in a Collection called the Items Collection Chapter 5 – Slide 7
To store values in the Items property at design time: Select the ListBox control in the Designer window In the Properties window, click the Items (Collection) ellipsis button (...) Type each value on a separate line in the String Collection Editor dialog box Adding Items to the Items Collection
The SelectedItem Property The SelectedItemproperty contains the currently selected item from the list box For example: Chapter 5 – Slide 9 If lstItems.SelectedIndex <> -1 strItemName = lstItems.SelectedItem.ToString() End If
Loops overview A repetition structure, or loop causes one or more statements to repeat Each repetition of the loop is called an iteration Visual Basic has three types of loops: Do While Do Until For… Next The difference among them is how they control the repetition Chapter 5 – Slide 10
The Do While loop has two important parts: a Boolean expression that is tested for a True or False value a statement or group of statements that is repeated as long as the Boolean expression is true, calledConditionally executed statements The Do While Loop Expression true? Process True False Do While BooleanExpression statement (more statements may follow) Loop
intCount initialized to 0 Expression intCount < 10 is tested If True, execute body: "Hello" added to lstOutput Items Collection intCount increases by 1 Test expression again Repeat until intCount < 10 becomes False Example Do While Loop Dim intCount As Integer = 0 Do While intCount < 10 lstOutput.Items.Add("Hello") intCount += 1 Loop
Infinite Loops Chapter 5 – Slide 13 A loop must have some way to end itself Something within the body of the loop must eventually force the test expression to false In the previous example The loop continues to repeat intCount increases by one for each repetition Finally intCount is not < 10 and the loop ends If the test expression can never be false, the loop will continue to repeat forever  This is called an infinite loop
Counters generally initialized before loop begins 	' Start at zero 	Dim intCount As Integer = 0 Counter must be modified in body of loop 	' Increment the counter variable intCount += 1		 Loop ends when of value counter variable exceeds the range of the test expression 	' False after ten iterations intCount < 10		 A counter is a variable that is regularly incremented or decremented each time a loop iterates  Incrementmeans to add 1 to the counter’s value intX = intX + 1 intX += 1  Decrementmeans to subtract 1 from the counter’s value intX = intX - 1 intX -= 1 Counters
Previous Do While loops are in pretestform Expression is tested before the body of the loop is executed The body may not be executed at all Do While loops also have a posttestform The body of the loop is executed first Then the expression is evaluated Body repeats as long as expression is true A posttest loop always executes the body of the loop at least once Pretest and Posttest Do While Loops
The Posttest Do While Loop Chapter 5 – Slide 16 The Do While loop can also be written as a posttest loop: While BooleanExpression appears  after the  Loop keyword Tests its Boolean expression after  	each loop iteration Will always perform at least one iteration,  	even if its Boolean expression is false  to start with Do    Statement    (More statements may follow) Loop While BooleanExpression Statement(s) Boolean Expression True False
Example Posttest Do While Loop Chapter 5 – Slide 17 Dim intCount As Integer = 100 Do MessageBox.Show("Hello World!") intCount += 1 Loop While intCount < 10 intCount is initialized to 100 The statements in the body of the loop execute The expression intCount < 10 is tested The expression is False The loop stops after the first iteration
Keeping a Running Total Chapter 5 – Slide 18 Many programming tasks require you to calculate the total of a series of numbers Sales Totals Scores This calculation generally requires two elements: A loop that reads each number in the series and accumulates the total, called a running total A variable that accumulates the total, called anaccumulator
Logic for Keeping a Running Total Chapter 5 – Slide 19 Setting the accumulator variable to zero  before entering the loop is a critical step Set accumulator to 0 Is there another number to read? Yes (True) Read the next number Add the number to the  accumulator No (False)
The Do Until Loop Chapter 5 – Slide 20 A Do Until loop iterates until an expression is true Repeats as long as its test expression is False Ends when its test expression becomes True Can be written in either pretest or posttest form Pretest General Format: Do Until BooleanExpression    Statement    (More statements may follow) Loop Posttest General Format: Do    Statement    (More statements may follow) Loop Until BooleanExpression
The For...Next Loop Chapter 5 – Slide 21 Ideal for loops that require a counter, pretest form only For, To, and Next are keywords CounterVariable tracks number of iterations StartValue is initial value of counter EndValue is counter number of final iteration Optional Step Increment allows the counter to increment at a value other than 1 at each iteration of the loop For CounterVariable = StartValue To EndValue [Step Increment] statement (more statements may follow) Next [CounterVariable]
Example of For…Next Loop Chapter 5 – Slide 22 For intCount = 1 To 10 MessageBox.Show("Hello") Next Step 1:  intCount is set to 1 (the start value) Step 2:  intCount is compared to 10 (the end value)  If intCount is less than or equal to 10  Continue to Step 3 Otherwise the loop is exited Step 3: The MessageBox.Show("Hello") statement is executed Step 4: intCount is incremented by 1 Step 5: Go back to Step 2 and repeat this sequence
Flowchart of For…Next Loop Set intCount to 1 intCount <= 10? Display "Hello" Add 1 to intCount Yes No Chapter 5 – Slide 23
Specifying a Step Value Chapter 5 – Slide 24 The step value is the value added to the counter variable at the end of each iteration Optional and if not specified, defaults to 1 The following loop iterates 10 times with counter values 0, 10, 20, …, 80, 90, 100 Step value may be negative, causing the loop to count downward For intCount = 0 To 100 Step 10 MessageBox.Show(intCount.ToString()) Next For intCount = 10 To 1 Step -1 MessageBox.Show(intCount.ToString()) Next
User Input Loops Do loops often are written to end the loop when a certain value is entered by the user, or the user performs a certain action such as clicking the Cancel button in an input box
Summing a Series of Numbers Chapter 5 – Slide 26 The For...Next loop can be used to calculate the sum of a series of numbers Dim intCount As Integer ' Loop counter Dim intTotal As Integer = 0 ' Accumulator ' Add the numbers 1 through 100. For intCount = 1 To 100 intTotal += intCount Next ' Display the sum of the numbers. MessageBox.Show("The sum of 1 through 100 is “  & intTotal.ToString())
Validating Data You must test the data to ensure that it is accurate and that its use will not cause program exception. When using an input box, the data should be checked using the IsNumeric function and the If statements discussed in Chapter 5. If the data is not valid, the user must be notified of the error and an input box displayed to allow the user to enter valid data.
Creating a Nested Loop Any loop can be placed within another loop under the following conditions:  Interior loops must be completely contained inside the outer loop Must have a different control variable
Selecting the Best Loop ,[object Object]
If a loop condition must be tested before the body of the loop is executed, use a top-controlled Do While or Do Until loop. If the instructions within a loop must be executed one time regardless of the status of a condition, use a bottom-controlled Do While or Do Until loop
Use the keyword While if you want to continue execution of the loop while the condition is true. Use the keyword Until if you want to continue execution until the condition is true,[object Object]
Using a DataTip with Breakpoints With the program open in the code editing window, right-click line 47, which contains the code where you want to set a breakpoint, and then point to Breakpoint on the shortcut menu Click Insert Breakpoint on the submenu To run and test the program with the breakpoint, click the Start Debugging button on the Standard toolbar Click the Enter Speed button. Type 75 as the speed of the first vehicle Click the OK button in the input box
Using a DataTip with Breakpoints Point to the variable decVehicleSpeed on line 47 You can view the value in any other variable within execution scope by pointing to that variable. To illustrate, point to the variable decTotalOfAllSpeeds on line 47 Continue the program by clicking the Continue button on the Standard toolbar. Notice that the Continue button is the same as the Start Debugging button Point to the decTotalOfAllSpeeds variable
Using a DataTip with Breakpoints
Publishing an Application with ClickOnce Deployment After an application is completely debugged and working properly, you can deploy the project Deploying a project means placing an executable version of the program on your hard disk, on a Web server, or on a network server When programming using Visual Basic 2010, you can create a deployed program by using ClickOnce Deployment The deployed version of the program you create can be installed and executed on any computer that has the .NET framework installed
Publishing an Application with ClickOnce Deployment With the program open, click Build on the menu bar Click Publish Radar on the Build menu Change the default location from publishto a file location. To publish to a USB drive, type the drive letter. In this example, enter E: for a USB drive Click the Next button. If necessary, click the From a CD-ROM or DVD-ROM radio button Click the Next button. If necessary, click the The application will not check for updates radio button
Publishing an Application with ClickOnce Deployment Click the Next button Click the Finish button To view the finished result, minimize the Visual Studio window, and then double-click Computer on the Windows 7 Start menu. Double-click the USB drive icon to view the published installation folder To install the application, double-click the setup file After installation, the program will run. To run the installed application again, click the Start button on the Windows taskbar. Point to All Programs, click Radar on the All Programs menu, and then click Radar on the Radar submenu
Publishing an Application with ClickOnce Deployment

Contenu connexe

Tendances

Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusDhivyaSubramaniyam
 
Lab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and PointersLab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and Pointersenidcruz
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine LearningStudent
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming LanguageExplore Skilled
 
Instrumentation and measurements
Instrumentation and measurementsInstrumentation and measurements
Instrumentation and measurementsTuba Tanveer
 
Pseudocode
PseudocodePseudocode
PseudocodeGuy09
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basicsSabik T S
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
Python - Functions - Azure Jupyter Notebooks
Python - Functions - Azure Jupyter NotebooksPython - Functions - Azure Jupyter Notebooks
Python - Functions - Azure Jupyter NotebooksAdri Jovin
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit IssuesAndrey Karpov
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingHemantha Kulathilake
 

Tendances (17)

Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Repitition Structure
Repitition StructureRepitition Structure
Repitition Structure
 
Lab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and PointersLab7: More Arrays, Strings, Vectors, and Pointers
Lab7: More Arrays, Strings, Vectors, and Pointers
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
Instrumentation and measurements
Instrumentation and measurementsInstrumentation and measurements
Instrumentation and measurements
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basics
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Python - Functions - Azure Jupyter Notebooks
Python - Functions - Azure Jupyter NotebooksPython - Functions - Azure Jupyter Notebooks
Python - Functions - Azure Jupyter Notebooks
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit Issues
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & Branching
 
Pseudocode By ZAK
Pseudocode By ZAKPseudocode By ZAK
Pseudocode By ZAK
 

Similaire à Loop structures chpt_6

Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docxCMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docxclarebernice
 
Chapter 06
Chapter 06Chapter 06
Chapter 06llmeade
 
Advanced Computer Programming..pptx
Advanced Computer Programming..pptxAdvanced Computer Programming..pptx
Advanced Computer Programming..pptxKrishanthaRanaweera1
 
C++ Loops General Discussion of Loops A loop is a.docx
C++ Loops  General Discussion of Loops A loop is a.docxC++ Loops  General Discussion of Loops A loop is a.docx
C++ Loops General Discussion of Loops A loop is a.docxhumphrieskalyn
 
Csc1100 lecture05 ch05
Csc1100 lecture05 ch05Csc1100 lecture05 ch05
Csc1100 lecture05 ch05IIUM
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxmonicafrancis71118
 
1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdf1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdfJavier Crisostomo
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxAASTHA76
 
Csphtp1 05
Csphtp1 05Csphtp1 05
Csphtp1 05HUST
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
04a intro while
04a intro while04a intro while
04a intro whilehasfaa1017
 
Notes2
Notes2Notes2
Notes2hccit
 

Similaire à Loop structures chpt_6 (20)

Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
03b loops
03b   loops03b   loops
03b loops
 
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docxCMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
CMIS 102 Hands-On LabWeek 6OverviewThis hands-on lab .docx
 
Chapter 06
Chapter 06Chapter 06
Chapter 06
 
Advanced Computer Programming..pptx
Advanced Computer Programming..pptxAdvanced Computer Programming..pptx
Advanced Computer Programming..pptx
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
C++ Loops General Discussion of Loops A loop is a.docx
C++ Loops  General Discussion of Loops A loop is a.docxC++ Loops  General Discussion of Loops A loop is a.docx
C++ Loops General Discussion of Loops A loop is a.docx
 
Csc1100 lecture05 ch05
Csc1100 lecture05 ch05Csc1100 lecture05 ch05
Csc1100 lecture05 ch05
 
C# Loops
C# LoopsC# Loops
C# Loops
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdf1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdf
 
Chapter 07
Chapter 07Chapter 07
Chapter 07
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Lecture5
Lecture5Lecture5
Lecture5
 
06.Loops
06.Loops06.Loops
06.Loops
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
 
Csphtp1 05
Csphtp1 05Csphtp1 05
Csphtp1 05
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
04a intro while
04a intro while04a intro while
04a intro while
 
Notes2
Notes2Notes2
Notes2
 

Dernier

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 

Dernier (20)

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 

Loop structures chpt_6

  • 1. Chapter 6 Loop structures
  • 2. Introduction This chapter introduces: Input boxes List boxes Counters and accumulators Compound operators Loops Data validation DataTips Publishing an application with ClickOnce technology Chapter 5 – Slide 2
  • 3. Chapter 5 – Slide 3 Overview An input box provides a quick and simple way to ask the user to enter data User types a value in the text box OK button returns a string value containing user input Cancel button returns an empty string Should not be used as a primary method of input Convenient tool for developing & testing applications
  • 4. General Format Chapter 5 – Slide 4 InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos])
  • 5. Example Usage To retrieve the value returned by the InputBox function, use the assignment operator to assign it to a variable For example, the following statement assigns the string value returned by the InputBox function to the string variable strUserInput The string value that appears inside the text box will be stored in the strUserInput variable after the OK button is clicked and the input box closes Chapter 5 – Slide 5 Dim strUserInput As String = InputBox("Enter the distance.", "Provide a Value", "150")
  • 6. A ListBoxcontrol displays a list of items and also allows the user to select one or more items from the list Displays a scroll bar when all items cannot be shown To create a ListBox control: Double-click the ListBox icon in the Toolbox window Position and resize the control as necessary In Design mode, the list box appears as a rectangle The size of the rectangle determines the size of the list box Use the lst prefix when naming a list box (lstListBox) Listbox Overview
  • 7. The Items Property The entries in a list box are stored in a property named Items The Items property holds an entire list of values from which the user may choose The list of values may be established at design time or runtime Items are stored in a Collection called the Items Collection Chapter 5 – Slide 7
  • 8. To store values in the Items property at design time: Select the ListBox control in the Designer window In the Properties window, click the Items (Collection) ellipsis button (...) Type each value on a separate line in the String Collection Editor dialog box Adding Items to the Items Collection
  • 9. The SelectedItem Property The SelectedItemproperty contains the currently selected item from the list box For example: Chapter 5 – Slide 9 If lstItems.SelectedIndex <> -1 strItemName = lstItems.SelectedItem.ToString() End If
  • 10. Loops overview A repetition structure, or loop causes one or more statements to repeat Each repetition of the loop is called an iteration Visual Basic has three types of loops: Do While Do Until For… Next The difference among them is how they control the repetition Chapter 5 – Slide 10
  • 11. The Do While loop has two important parts: a Boolean expression that is tested for a True or False value a statement or group of statements that is repeated as long as the Boolean expression is true, calledConditionally executed statements The Do While Loop Expression true? Process True False Do While BooleanExpression statement (more statements may follow) Loop
  • 12. intCount initialized to 0 Expression intCount < 10 is tested If True, execute body: "Hello" added to lstOutput Items Collection intCount increases by 1 Test expression again Repeat until intCount < 10 becomes False Example Do While Loop Dim intCount As Integer = 0 Do While intCount < 10 lstOutput.Items.Add("Hello") intCount += 1 Loop
  • 13. Infinite Loops Chapter 5 – Slide 13 A loop must have some way to end itself Something within the body of the loop must eventually force the test expression to false In the previous example The loop continues to repeat intCount increases by one for each repetition Finally intCount is not < 10 and the loop ends If the test expression can never be false, the loop will continue to repeat forever This is called an infinite loop
  • 14. Counters generally initialized before loop begins ' Start at zero Dim intCount As Integer = 0 Counter must be modified in body of loop ' Increment the counter variable intCount += 1 Loop ends when of value counter variable exceeds the range of the test expression ' False after ten iterations intCount < 10 A counter is a variable that is regularly incremented or decremented each time a loop iterates Incrementmeans to add 1 to the counter’s value intX = intX + 1 intX += 1 Decrementmeans to subtract 1 from the counter’s value intX = intX - 1 intX -= 1 Counters
  • 15. Previous Do While loops are in pretestform Expression is tested before the body of the loop is executed The body may not be executed at all Do While loops also have a posttestform The body of the loop is executed first Then the expression is evaluated Body repeats as long as expression is true A posttest loop always executes the body of the loop at least once Pretest and Posttest Do While Loops
  • 16. The Posttest Do While Loop Chapter 5 – Slide 16 The Do While loop can also be written as a posttest loop: While BooleanExpression appears after the Loop keyword Tests its Boolean expression after each loop iteration Will always perform at least one iteration, even if its Boolean expression is false to start with Do Statement (More statements may follow) Loop While BooleanExpression Statement(s) Boolean Expression True False
  • 17. Example Posttest Do While Loop Chapter 5 – Slide 17 Dim intCount As Integer = 100 Do MessageBox.Show("Hello World!") intCount += 1 Loop While intCount < 10 intCount is initialized to 100 The statements in the body of the loop execute The expression intCount < 10 is tested The expression is False The loop stops after the first iteration
  • 18. Keeping a Running Total Chapter 5 – Slide 18 Many programming tasks require you to calculate the total of a series of numbers Sales Totals Scores This calculation generally requires two elements: A loop that reads each number in the series and accumulates the total, called a running total A variable that accumulates the total, called anaccumulator
  • 19. Logic for Keeping a Running Total Chapter 5 – Slide 19 Setting the accumulator variable to zero before entering the loop is a critical step Set accumulator to 0 Is there another number to read? Yes (True) Read the next number Add the number to the accumulator No (False)
  • 20. The Do Until Loop Chapter 5 – Slide 20 A Do Until loop iterates until an expression is true Repeats as long as its test expression is False Ends when its test expression becomes True Can be written in either pretest or posttest form Pretest General Format: Do Until BooleanExpression Statement (More statements may follow) Loop Posttest General Format: Do Statement (More statements may follow) Loop Until BooleanExpression
  • 21. The For...Next Loop Chapter 5 – Slide 21 Ideal for loops that require a counter, pretest form only For, To, and Next are keywords CounterVariable tracks number of iterations StartValue is initial value of counter EndValue is counter number of final iteration Optional Step Increment allows the counter to increment at a value other than 1 at each iteration of the loop For CounterVariable = StartValue To EndValue [Step Increment] statement (more statements may follow) Next [CounterVariable]
  • 22. Example of For…Next Loop Chapter 5 – Slide 22 For intCount = 1 To 10 MessageBox.Show("Hello") Next Step 1: intCount is set to 1 (the start value) Step 2: intCount is compared to 10 (the end value) If intCount is less than or equal to 10 Continue to Step 3 Otherwise the loop is exited Step 3: The MessageBox.Show("Hello") statement is executed Step 4: intCount is incremented by 1 Step 5: Go back to Step 2 and repeat this sequence
  • 23. Flowchart of For…Next Loop Set intCount to 1 intCount <= 10? Display "Hello" Add 1 to intCount Yes No Chapter 5 – Slide 23
  • 24. Specifying a Step Value Chapter 5 – Slide 24 The step value is the value added to the counter variable at the end of each iteration Optional and if not specified, defaults to 1 The following loop iterates 10 times with counter values 0, 10, 20, …, 80, 90, 100 Step value may be negative, causing the loop to count downward For intCount = 0 To 100 Step 10 MessageBox.Show(intCount.ToString()) Next For intCount = 10 To 1 Step -1 MessageBox.Show(intCount.ToString()) Next
  • 25. User Input Loops Do loops often are written to end the loop when a certain value is entered by the user, or the user performs a certain action such as clicking the Cancel button in an input box
  • 26. Summing a Series of Numbers Chapter 5 – Slide 26 The For...Next loop can be used to calculate the sum of a series of numbers Dim intCount As Integer ' Loop counter Dim intTotal As Integer = 0 ' Accumulator ' Add the numbers 1 through 100. For intCount = 1 To 100 intTotal += intCount Next ' Display the sum of the numbers. MessageBox.Show("The sum of 1 through 100 is “ & intTotal.ToString())
  • 27. Validating Data You must test the data to ensure that it is accurate and that its use will not cause program exception. When using an input box, the data should be checked using the IsNumeric function and the If statements discussed in Chapter 5. If the data is not valid, the user must be notified of the error and an input box displayed to allow the user to enter valid data.
  • 28. Creating a Nested Loop Any loop can be placed within another loop under the following conditions: Interior loops must be completely contained inside the outer loop Must have a different control variable
  • 29.
  • 30. If a loop condition must be tested before the body of the loop is executed, use a top-controlled Do While or Do Until loop. If the instructions within a loop must be executed one time regardless of the status of a condition, use a bottom-controlled Do While or Do Until loop
  • 31.
  • 32. Using a DataTip with Breakpoints With the program open in the code editing window, right-click line 47, which contains the code where you want to set a breakpoint, and then point to Breakpoint on the shortcut menu Click Insert Breakpoint on the submenu To run and test the program with the breakpoint, click the Start Debugging button on the Standard toolbar Click the Enter Speed button. Type 75 as the speed of the first vehicle Click the OK button in the input box
  • 33. Using a DataTip with Breakpoints Point to the variable decVehicleSpeed on line 47 You can view the value in any other variable within execution scope by pointing to that variable. To illustrate, point to the variable decTotalOfAllSpeeds on line 47 Continue the program by clicking the Continue button on the Standard toolbar. Notice that the Continue button is the same as the Start Debugging button Point to the decTotalOfAllSpeeds variable
  • 34. Using a DataTip with Breakpoints
  • 35. Publishing an Application with ClickOnce Deployment After an application is completely debugged and working properly, you can deploy the project Deploying a project means placing an executable version of the program on your hard disk, on a Web server, or on a network server When programming using Visual Basic 2010, you can create a deployed program by using ClickOnce Deployment The deployed version of the program you create can be installed and executed on any computer that has the .NET framework installed
  • 36. Publishing an Application with ClickOnce Deployment With the program open, click Build on the menu bar Click Publish Radar on the Build menu Change the default location from publishto a file location. To publish to a USB drive, type the drive letter. In this example, enter E: for a USB drive Click the Next button. If necessary, click the From a CD-ROM or DVD-ROM radio button Click the Next button. If necessary, click the The application will not check for updates radio button
  • 37. Publishing an Application with ClickOnce Deployment Click the Next button Click the Finish button To view the finished result, minimize the Visual Studio window, and then double-click Computer on the Windows 7 Start menu. Double-click the USB drive icon to view the published installation folder To install the application, double-click the setup file After installation, the program will run. To run the installed application again, click the Start button on the Windows taskbar. Point to All Programs, click Radar on the All Programs menu, and then click Radar on the Radar submenu
  • 38. Publishing an Application with ClickOnce Deployment
  • 39. References Microsoft Visual Basic 2010 Comprehensive. Shelly Cashman. Course Technology.© 2011. 1st edition. Starting out with Visual Basic. Tony Gaddis. Pearson Addison-Wesley .© 2011. 3rd edition