Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.

Slides:



Advertisements
Similar presentations
Programming with Microsoft Visual Basic th Edition
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Copyright © 2012 Pearson Education, Inc. Chapter 11 MORE WINDOWS CONTROLS & STANDARD DIALOG BOXES.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
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.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 What are the different types of loops? ◦ Do….While  Performs statements within loop while a condition is true ◦ Do….Until  Performs statements within.
Chapter 12: How Long Can This Go On?
File I/O 11_file_processing.ppt
Chapter 4: Loops and Files
Loops ISYS 350. A Box of Chocolate Repeat this process until box is empty: – Take one chocolate from the box – Eat the chocolate – Box has more chocolate?
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
File Input and Output (I/O) Engineering 1D04, Teaching Session 7.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Class Average Application Introducing the Do...Loop While and Do...Loop Until.
Loops ISYS 350. Compute the sum of a list of numbers: Example: 5, 2, 10, 8, 4 Process: Sum= 0 Get a number from the list Sum = Sum + the number Repeat.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 5A Repetition (Concepts)
JavaScript, Fourth Edition
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Loops ISYS 350. Two Types of Loops while loop for loop.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 13 How Long Can This Go On?
Unit 6 Repetition Processing Instructor: Brent Presley.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Input Boxes, List Boxes, and Loops Chapter 5. 2 Input Boxes Method for getting user’s attention to obtain input. InputBox() for obtaining input MessageBox()
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Loops ISYS 350. Two Types of Loops while loop for loop.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Loops ISYS 350. Two Types of Loops while loop for loop.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Loops ISYS 350.
Loops ISYS 350.
Chapter 5: Loops and Files.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Loops ISYS 350.
Loops ISYS 350.
CIS 16 Application Development Programming with Visual Basic
Loops ISYS 350.
Loops ISYS 350.
CIS16 Application Development and Programming using Visual Basic.net
Topics Introduction to File Input and Output
Loops ISYS 350.
Loops ISYS 350.
Loops ISYS 350.
Topics Introduction to File Input and Output
Presentation transcript:

Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers

Topics 5.1 More About ListBoxes 5.2 The while Loop 5.3 The ++ and – Operators 5.4 The for Loop 5.5 The do-while Loop 5.6 Using Files for Data Storage 5.7 The OpenFileDialog and SaveFileDialog Controls 5.8 Random Numbers 5.9 The Load Event Copyright © 2012 Pearson Education, Inc.

5.1 More About ListBoxes ListBox controls have various methods and properties that you can use in code to manipulate the ListBox’s contents The Items.Add method allows you to add an item to the ListBox control ListBoxName.Items.Add(Item); –where ListBoxName is the name of the ListBox control; Item is the value to be added to the Items property The Items.Clear method can erase all the items in the Items proeprty employeeListBox.Items.Clear(); The Count property reports the number of items stored in the ListBox

Sample Codes You can add string literals private void addButton_Click(object sender, EventArgs e) { namesListBox.Items.Add("Chris"); namesListBox.Items.Add("Alicia"); } You can add values of other types as well private void addButton_Click(object sender, EventArgs e) { namesListBox.Items.Add(10); namesListBox.Items.Add(20); namesListBox.Items.Add(17.5); } Copyright © 2012 Pearson Education, Inc.

5.2 The while Loop The while loop causes a statement or set of statements to repeat as long as a Boolean expression is true The simple logic is: While a Boolean expression is true, do some task A while loop has two parts: –A Boolean expression that is tested for a true or false value –A statement or set of statements that is repeated a long as the Boolean expression is true Copyright © 2012 Pearson Education, Inc. Boolean Expression Statement(s) True False

Structure of a while Loop In C#, the generic format of a while loop is: while (BooleanExpression) { Statements; } The first line is called the while clause Statements inside the curly braces are the body of the loop When a while loop executes, the Boolean expression is tested. If true, the statements are executed Each time the loop executes its statement or statements, we say the loop is iterating, or performing an iteration Copyright © 2012 Pearson Education, Inc.

The while Loop is a Pretest Loop A while loop tests its condition before performing an iteration. It is necessary to declare a counter variable with initial value int count = 1; So the while clause can test its Boolean expression while (count < 5) { } Inside the curly braces, there must exist a statement that defines increment (or decrement) of the counter while (count < 5) { ….. counter = count + 1; } Copyright © 2012 Pearson Education, Inc.

Sample Code private void goButton_Click(object sender, EventArgs e) { int count = 1; while (count <= 5) { MessageBox.Show(“Hello!”); count = count + 1; } The counter has an initial value of 1 Each time the loop executes, 1 is added to counter The Boolean expression will test whether counter is less than or equal 5. So the loop will stop when counter equals 5. Copyright © 2012 Pearson Education, Inc.

Infinite Loops An infinite loop is a loop that will repeats until the program is interrupted There are few conditions that cause a while loop to be an infinite loop. A typical scenario is that the programmer forgets to write code that makes the test condition false In the following example, the counter is never increased. So, the Boolean expression is never false. int count = 1; while (count <= 5) { MessageBox.Show(“Hello”); } Copyright © 2012 Pearson Education, Inc.

5.3 The ++ and -- Operators To increment a variable means to increase its value, and to decrement a variable means to decrease its value C# provides the ++ and -- operator to increment and decrement variables Adding 1 to a variable can be written as: count = count + 1; or count++; or count += 1; Subtracting 1 from a variable can be written as: count = count – 1; or count --; or count -= 1; Copyright © 2012 Pearson Education, Inc.

Postfix Mode vs. Prefix Mode Postfix mode means to place the ++ and -- operators after their operands count++; Prefix mode means to place the ++ and -- operators before their operands --count; Copyright © 2012 Pearson Education, Inc.

5.4 The for Loop The for loop is specially designed for situations requiring a counter variable to control the number of times that a loop iterates You must specify three actions: –Initialization: a one-time expression that defines the initial value of the counter –Test: A Boolean expression to be tested. If true, the loop iterates. –Update: increase or decrease the value of the counter A generic form is: for (initializationExpress; testExpression; updateExpression) { } The for loop is a pretest loop Copyright © 2012 Pearson Education, Inc.

Sample Code int count; for (count = 1; count <= 5; count++) { MessageBox.Show(“Hello”); } The initialization expression assign 1 to the count variable The expression count <=5 is tested. If true, continue to display the message. The update expression add 1 to the count variable Start the loop over Copyright © 2012 Pearson Education, Inc. // declare count variable in initialization expression for (int count = 1; count <= 5; count++) { MessageBox.Show(“Hello”); }

Other Forms of Update Expression In the update expression, the counter variable is typically incremented by 1. But, this is not a requirement. //increment by 10 for (int count = 0; count <=100; count += 10) { MessageBox.Show(count.ToString()); } You can decrement the counter variable to make it count backward //counting backward for (int count = 10; count >=0; count--) { MessageBox.Show(count.ToString()); } Copyright © 2012 Pearson Education, Inc.

5.5 The do-while Loop The do-while loop is a posttest loop, which means it performs an iteration before testing its Boolean expression. In the flowchart, one or more statements are executed before a Boolean expression is tested A generic format is: do { statement(s); } while (BooleanExpression); Copyright © 2012 Pearson Education, Inc. Boolean Expression Statement(s) True False

Sample Codes Will you see the message box? int number = 1 do { MessageBox.Show(number.ToString()); } while (number < 0); Will you see the message box? int number = 1 while (number < 0) { MessageBox.Show(number.ToString()); } Copyright © 2012 Pearson Education, Inc.

5.6 Using File for Data Storage When a program needs to save data for later use, it writes the data in a file There are always three steps: –Open the file: create a connection between the file and the program –Process the file: either write to or read from the file –Close the file: disconnect the file and the program In general, there are two types of files: –Text file: contains data that has been encoded as test using scheme such as Unicode –Binary file: contains data that has not been converted to text. You cannot view the contents of binary files with a text editor. This chapter only works with text files Copyright © 2012 Pearson Education, Inc.

File Accessing A file object is an object that is associated with a specific file and provides a way for the program to work with that file The.NET Framework provide two classes to create file objects through the System.IO namespace –StreamWriter: for writing data to a text file –StreamReader: for reading data from a text file You need to write the following directives at the top of your program Using System.IO; Copyright © 2012 Pearson Education, Inc.

Writing Data to a File Start with creating a StreamWriter object StreamWriter outputFile; Use one of the File methods to open the file to which you will be writing data. Sample File methods are: –File.CreateText –File.AppendText Use the Write or WriteLine method to write items of data to the file Close the connection. Copyright © 2012 Pearson Education, Inc.

Sample Code StreamWriter outputFile; outputFile = File.CreateText(“courses.txt”); outputFile.WriteLine(“Introduction to Computer Science”); outputFile.WriteLine(“English Composition”); outputFile.Write(“Calculus I”); outputFile.Close(); The WriteLine method writes an item of data to a file and then writes a newline characters which specifies the end of a line The Write method writes an item to a file without a newline character Copyright © 2012 Pearson Education, Inc.

CreateText vs. AppendText The previous code uses the File.CreateText method for the following reasons: –It creates a text file with the name specified by the argument. If the file already exists, its contents are erased –It creates a StreamWriter object in memory, associated with the file –It returns a reference to the StreamWriter object When there is a need not to erase the contents of an existing file, use the AppendText method StreamWriter outputFile; outputFile = File.AppendText(“Names.txt”); outputFile.WriteLine(“Lynn”); outputFile.WriteLine(“Steve”); outputFile.Close(); Copyright © 2012 Pearson Education, Inc.

Specifying the Location of an Output File If you want to open a file in a different location, you can specify a path as well as filename in the argument Be sure to prefix the string with character StreamWriter outputFile; outputFile = Copyright © 2012 Pearson Education, Inc.

Reading Data from a File Start with creating a StreamReader object StreamReader inputFile; Use the File.OpenText method to open the file to which you will be writing data inputFile = FileOpenText(“students.txt”); Use the Read or ReadLine method to write items of data to the file –StreamReader.ReadLine: Reads a line of characters from the current stream and returns the data as a string. –StreamReader.Read: Reads the next character or next set of characters from the input stream. Close the connection Copyright © 2012 Pearson Education, Inc.

Reading a File with a Loop StreamReader objects have a Boolean property named EndOfStream that signals whether or not the end of file has been reached You can write a loop to detect the end of the file. while (inputFile.EndOfStream == false) { } Or while (!inputFile.EndOfStream) { } Copyright © 2012 Pearson Education, Inc.

5.7 The OpenFileDialog and SaveFileDialog Controls The OpenFileDialog and SaveDialog controls allow your application to display standard Windows dialog boxes for opening and saving files Unlike Label, Button, and TextBox, they are invisible controls The OpenFileDialog control displays a standard Windows Open dialog box. The SaveDialog control displays a standard Windows Save As dialog box Copyright © 2012 Pearson Education, Inc.

Displaying an Open Box When adding an OpenFileDialog control to the form, it does not appear on the form, but in an area at the bottom of the Designer called the component tray In code, you can display an Open Dialog box by calling the ShowDialog method private void button1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } Copyright © 2012 Pearson Education, Inc.

Detecting the User’s Selection The showDialog method returns a value that indicates which button the user clicks to dismiss the dialog box –If the user clicked the Open button, the value DialogResult.OK is returned –If the user clicked the Cancel button, the value DialogResult.Cancel is returned –The following is an example that calls the ShowDialog method to determine the user’s choice: if (openFile.ShowDialog() == DialogResult.OK) { } else if (openFile.ShowDialog() == DialogResult.Cancel) { } else { } Copyright © 2012 Pearson Education, Inc.

The Filename and InitialDirectory Property When the user selects a file with the Open dialog box, the file’s path and filename are stored in the control’s Filename property The following is an example of how to open the selected file: if (openFile.ShowDialog() == DialogResult.OK) { inputFile = File.OpenText(openFile.Filename); } else { } You can specify a directory to be initially displayed with the InitialDirectory property. For example, openFile.InitialDirectory = “C:\Data”; Copyright © 2012 Pearson Education, Inc.

Displaying a Save As Dialog Box Use the following to call the SaveFileDialog control’s ShowDialog method saveFile.ShowDialog(); Use the following to detect the user’s choice if (saveFile.ShowDialog() == DialogResult.OK) { } Use the following to open the selected file if (saveFile.ShowDialog() == DialogResult.OK) { outputFile = File.CreateText(openFile.Filename); } Copyright © 2012 Pearson Education, Inc.

5.8 Random Numbers The.NET Framework provides the Random class to generate random numbers. To create an object, use: Random rand = new Random(); Two commonly used methods to generate random numbers are: –Next: randomly create an integer –NextDouble: randomly create a floating-point number from 0.0 to 1.0 Examples, rand.Next(); rand.NextDouble(); Copyright © 2012 Pearson Education, Inc.

Syntax of Random.Next Method Random.Next generates a random number whose value ranges from zero to 2,147,483,647 It also allow you to generate a random number whose value ranges from zero to some other positive number. The syntax is: Random.Next(max+1); For example, to create a random number from 0 to 99, use: rand.Next(10); Copyright © 2012 Pearson Education, Inc.

5.9 The Load Event When running an application, the application’s form is loaded into memory and an event known as Load takes place To create a Load event handler, simply double click the form in the Designer An empty Load event handler looks like: private void Form1_Load(object sender, EventArgs e) { } Any code you write inside the Load event will execute when the form is launched. For example, private void Form1_Load(object sender, EventArgs e) { MessageBox.Show(“Prepare to see the form!”); } Copyright © 2012 Pearson Education, Inc.