0% found this document useful (0 votes)
37 views34 pages

Starting Out With Visual: Fourth Edition

Uploaded by

Omar Dhoore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views34 pages

Starting Out With Visual: Fourth Edition

Uploaded by

Omar Dhoore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Starting out with Visual C#

Fourth Edition

Chapter 5
Loops, File, and Random
Numbers

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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

‒ 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

• The Count property reports the number of items stored in the


ListBox
Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Sample Codes
• You can add string literals

• You can add values of other types as well

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Structure of a while Loop
• In C#, the generic format of a while loop is:

• 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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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

• So the while clause can test its Boolean expression

• Inside the curly braces, there must exist a statement that


defines increment (or decrement) of the counter

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Sample Code (1 of 4)

• 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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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.

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
  and
5.3 The increment   Operators
and decrement

• To increment a variable means to increase its value, and to decrement a variable


means to decrease its value
• This C# provides the   and   operator to increment and decrement variables

• Adding 1 to a variable can be written as:

• Subtracting 1 from a variable can be written as:

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Postfix Mode v s Prefix Mode
ersu

• Postfix mode means to place the   and   operators


after their operands

• Prefix mode means to place the   and   operators


before their operands

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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:

• The for loop is a pretest loop

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Sample Code (2 of 4)

• 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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Other Forms of Update Expression
• In the update expression, the counter variable is typically
incremented by 1. But, this is not a requirement.

• You can decrement the counter variable to make it count


backward

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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:

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Sample Code (3 of 4)
• Will you see the message box?

• Will you see the message box?

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Writing Data to a File
• Start with creating a StreamWriter object

• Use one of the File methods to open the file to which you will
be writing data. Sample File methods are:

• Use the Write or WriteLine method to write items of data to


the file
• Close the connection.

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Sample Code (4 of 4)

• 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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
CreateText v s AppendText ersu

• 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

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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 the @ character

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Reading Data from a File
• Start with creating a StreamReader object

• Use the File.OpenText method to open the file to which you will be
writing data

• 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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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.

• Or

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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 © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Displaying an Open Box (1 of 2)
• 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

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Displaying an Open Box (2 of 2)
• In code, you can display an Open dialog box by calling the
ShowDialog method:

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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:

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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:

• You can specify a directory to be initially displayed with the


InitialDirectory property. For example,

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Displaying a Save as Dialog Box
• Use the following to call the SaveFileDialog control’s
ShowDialog method

• Use the following to detect the user’s choice

• Use the following to open the selected file

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
5.8 Random Numbers
• The .NET Framework provides the Random class to generate random
numbers.
• To create an object, use:

• 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,

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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:

• For example, to create a random number from 0 to 99, use:

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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:

• Any code you write inside the Load event will execute when
the form is launched. For example,

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Copyright

Copyright © 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved

You might also like