0% found this document useful (0 votes)
79 views

C Sharp (C#) : Benadir University

This document provides an overview of Chapter 5 from a C# course. The chapter covers various loop structures like while, for, do-while loops. It also discusses manipulating list boxes, using the ++ and -- operators, reading and writing to files, and generating random numbers. The document includes code examples for each topic.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

C Sharp (C#) : Benadir University

This document provides an overview of Chapter 5 from a C# course. The chapter covers various loop structures like while, for, do-while loops. It also discusses manipulating list boxes, using the ++ and -- operators, reading and writing to files, and generating random numbers. The document includes code examples for each topic.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

C Sharp(C#)

Course: C#

Class: Batch13

Lecturer: Eng. Hassan Abdi Arale (Arale)


BENADIR UNIVERSITY
Faculty of Computer Science and IT
C Sharp(C#)

Chapter Five

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 Random Numbers
• 5.8 The Load Event
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 property
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);
}
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
Boolean True
Expression Statement(s)

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
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;
}
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.
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”);
}
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;
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;
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


Sample Code
int count;
for (count = 1; count <= 5; count++) // declare count variable in initialization expression
{ for (int count = 1; count <= 5; count++)
{
MessageBox.Show(“Hello”);
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
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());
}
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: Statement(s)

do
{
Boolean True
statement(s); Expression
} while (BooleanExpression);
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());
}
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
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;
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.
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
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();
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
• StreamWriter outputFile;
outputFile = File.CreateText(@”C:\Users\chris\Documents\Names.txt”);
Reading Data from a File
• Start with creating a StreamReader object
StreamReader inputFile;

• Use the File.OpenText method to open the file from which you will be
reading data
inputFile = FileOpenText(“students.txt”);

• Use the Read or ReadLine method to read items of data from 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


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) { }
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();
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(100);
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!”);
}
That is……………….

Questions?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy