0% found this document useful (0 votes)
12 views43 pages

CSC221 Lecture 3

Uploaded by

iceomgbbh345
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)
12 views43 pages

CSC221 Lecture 3

Uploaded by

iceomgbbh345
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/ 43

Week Three

Loops & Random Numbers


The CSC221 Team
[2023|2024]
Main Text for this Course
Title
Starting out with Visual C#

Author
Tony Gaddis

Download for your progressive learning


LECTURE OUTLINE

 More about ListBoxes


 ComboBoxes
 Iteration/Loop Control Structure
 The while Loop
 The for Loop
 The do-while Loop
 Random Numbers
Monday, April 24, 2023
More about ListBoxes

 The Items.Add Method:


 It adds items to a ListBox control at run time.

 The Items.Clear Method:


 It erases all the items in the Items property at run time.

 The Items.Count Property:


 It reports the number of items stored in the ListBox. If the ListBox is empty, the
Items.Count property equals 0.
4
 As shown in the image on the left, the ListBox’s name is namesListBox and the
Button control’s name is addButton.

 At run time, when you click the addButton control, the names shown in the
image on the right are added to the nameListBox control.

The Number List Application 5


The Number List Application

6
The while loop

 The while loop causes a statement or


set of statements to repeat as long as a
Boolean expression is true.

7
The while loop

 The while Loop Is a Pretest Loop


 The while loop is known as a pretest loop, which means it tests its condition before
performing an iteration..
 Counter Variables
 A Counter variable is commonly used to control the number of times that a loop iterates.
 Infinite Loops
 An infinite loop continues to repeat until the program is interrupted. Infinite loops usually occur
when the programmer forgets to write code inside the loop that makes the test condition false

8
Classwork 1: Using Loop to Calculate and account Balance

 When you complete the application, it will allow the user to enter
an account’s starting balance into the startingBalTextBox control
and the number of months that the account will be left to earn
interest into the monthsTextBox control.
 When the user clicks the calculateButton control, the application
calculates the account’s balance at the end of the time period.
 The account’s monthly interest rate is 0.005, and the interest is
compounded monthly.
9
Solution
 Design the form and use the
started names for all the
controls as depicted in the
diagram

10
private void calculateButton_Click(object sender, EventArgs e)
{
// Constant for the monthly interest rate.
const decimal INTEREST_RATE = 0.005m;

// Local variables
decimal balance; // The account balance
int months; // The number of months
int count = 1; // Loop counter, initialized with 1

// Get the starting balance.. First if starts here


if (decimal.TryParse(startingBalTextBox.Text, out balance))
{
// Get the number of months. Second if starts here
if (int.TryParse(monthsTextBox.Text, out months))
{
// The following loop calculates the ending balance.
while (count <= months)
{ // while loop starts here.
// Add this month's interest to the balance.
balance = balance + (INTEREST_RATE * balance);

Solution 11
// Add one to the loop counter.
count = count + 1;
} // end of while.
// Display the ending balance.
endingBalanceLabel.Text = balance.ToString("c");
} // second if ends here.
else {
// Invalid number of months was entered.
MessageBox.Show("Invalid value for months.");
}
} // first if ends here.
else {
// Invalid starting balance was entered.
MessageBox.Show("Invalid value for starting balance.");
}
} // function ends here.

Solution (Cont’d) 12
The ++ and -- operator

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


means to decrease its value.

 C# provides special operators to increment and decrement variables.


 ++ is for the increment operation
 -- is for the decrement operation

13
The for loop

 The for loop is ideal for performing a known number of iterations..


 When you write a for loop, you specify three actions:
 Initialization: This action takes place when the loop begins. It happens only
once.
 Test: A Boolean expression is tested. If the expression is true, the loop
iterates. Otherwise, the loop stops.
 Update: This action takes place at the end of each loop iteration.
14
The for loop

 The for Loop is a pretest Loop


 The general format of the for loop:

for (InitializationExpression; TestExpression; UpdateExpression)


{
statement;
statement;
etc.
}

15
Classwork 2 - The for loop

 Your friend Amanda just inherited a European sports car from her uncle. Amanda lives in
the United States, and she is afraid she will get a speeding ticket because the car’s
speedometer works in kilometers per hour.
 She has asked you to write a program that displays a table of speeds in kilometers per
hour with their values converted to miles per hour.
 The formula for converting kilometers per hour to miles per hour is:

16
Classwork 2 (Cont’d) - The for loop
 In the formula, MPH is the speed in miles per hour and KPH
is the speed in kilometers per hour.

 The table that your program displays should show speeds


from 60 kilometers per hour through 130 kilometers per hour,
in increments of 10, along with their values converted to
miles per hour.

 The table should look something like this:


17
private void displayButton_Click(object sender, EventArgs e)
{
// Constants
const int START_SPEED = 60;
const int END_SPEED = 130;
const int INTERVAL = 10;
const double CONVERSION_FACTOR = 0.6214;
// Variables
int kph; // Kilometers per hour
double mph; // Miles per hour
// Display the table of speeds.
for (kph = START_SPEED; kph <= END_SPEED; kph += INTERVAL)
{
// Calculate miles per hour.
mph = kph * CONVERSION_FACTOR;
// Display the conversion.
outputListBox.Items.Add(kph + " KPH is the same as " + mph + " MPH");
}
}
Solution 18
The do-while Loop
 The do-while loop is a posttest loop, which means it
performs an iteration before testing its Boolean
expression.
 General format of the do-while loop:
do
{
statement;
statement;
etc.
} while (BooleanExpression);
19
The ComboBox

 A combo box is like a list box that has been combined with a text
box.
 There are three different styles of combo boxes:
 Drop-down combo box
 Simple combo box
 Drop-down list combo box.
 You can select a combo box’s style with its DropDownStyle property.
20
With the drop-down list combo box
style, the user may not type text
With the simple style of combo This is the default setting for the directly into the combo box. An item
box, the list of items does not drop combo box Drop Down style must be selected from the list. At run
down but is always displayed. property. time, a drop-down list combo box
As with the drop-down combo box, At run time, a drop-down combo box appears, as shown in the image on the
this style allows the user to select an like the one shown in the middle left in the rightmost figure. When the
item from the list or type text appears. When the user clicks the user clicks the down arrow, a list of
directly into the text box area. down arrow, a list drops down as items appears, as shown in the image
shown in the image on the right in the on the right in the figure.
figure.

Three different styles of ComboBox 21


Similarities between ListBoxes and ComboBoxes

 They both display a list of items to the user.


 They both have Items, Items.Count, SelectedIndex, SelectedItem,
and Sorted properties.
 They both have Items.Add and Items.Clear methods.
 All these properties and methods work the same with combo boxes
and list boxes
22
 In this example, a ComboBox is filled with numbers 1 to
10 (each value on a line).

 If the “Double” button is clicked, the selected value in


the ComboBox is doubled and the resultant value is
added to the ListBox.

 Similar operations pertain to the “Triple” and “Square”


buttons which triple and return the square of selected
value respectively.

 “Remove Item” removes an item from the ListBox while Use the “Items” property to fill up
“Clear” removes all the item in the ListBox at once. a ComboBox with items

Example with a ComboBox 23


private void button3_Click(object sender, EventArgs e)
{
if (comboBox1.Text != string.Empty)
{
int number = int.Parse(comboBox1.Text);
int d_number = number * 2;
listBox1.Items.Add(d_number);
}
else
{
MessageBox.Show("No item was selected");
}
}

Implementing the “Double” button 24


private void button3_Click(object sender, EventArgs e)
{
if (comboBox1.Text != string.Empty)
{
int number = int.Parse(comboBox1.Text);
int t_number = number * 3;
listBox1.Items.Add(t_number);
}
else
{
MessageBox.Show("No item was selected");
}
}

Implementing the “Triple” button 25


private void button3_Click(object sender, EventArgs e)
{
if (comboBox1.Text != string.Empty)
{
int number = int.Parse(comboBox1.Text);
int s_number = number * number;
listBox1.Items.Add(s_number);
}
else
{
MessageBox.Show("No item was selected");
}
}

Implementing the “Square” button 26


private void button2_Click(object sender, EventArgs e)
{ // CL
listBox1.Items.Clear();
}

private void button1_Click(object sender, EventArgs e)


{ // RI
if(listBox1.SelectedItems.Count > 0)
listBox1.Items.Remove(listBox1.SelectedItem);
else
MessageBox.Show("No item was selected");
}

“Clear” (CL) and “Remove Item” (RI) buttons 27


Random Numbers

 Random numbers are used in a variety of applications. The .NET Framework


provides the Random class that you can use in C# to generate random numbers.
 Random numbers are useful for lots of different programming tasks:
 Games
 Simulation programs.
 Statistical programs that must randomly select data for analysis.
 Computer security to encrypt sensitive data

28
Random Numbers

 The .NET Framework provides a class named Random that you can use in C# to generate
random numbers. First you create an object from the Random class with a statement such
as this:
Random rand = new Random();

29
The Next Method

 Once you have created a Random object, you can call its Next method to get a random
integer number. The following code shows an example:
// Declare an int variable.
int number;
// Create a Random object.
Random rand = new Random();
// Get a random integer and assign it to number.
number = rand.Next();

30
The NextDouble Method

 You can call a Random object’s NextDouble method to get a random floating-point
number between 0.0 and 1.0 (not including 1.0). The following code shows an example:
// Declare a Double variable.
double number;
// Create a Random object.
Random rand = new Random();
// Get a random number and assign it to number.
number = rand.NextDouble();

31
Classwork 4
(Random Number)
 Create an application that simulates the tossing of a coin. Each time the user tosses the
coin, the application uses a Random object to get a random integer in the range of 0
through 1.

 If the random number is 0, it means the tails side of the coin is up, and if the random
number is 1, it means the heads side is up.

 The application displays an image of a coin showing either heads or tails, depending on the
value of the random number.
32
Solution

33
private void tossButton_Click(object sender, EventArgs e)
{
// Variable to indicate which side is up
int sideUp;
// Create a Random object.
Random rand = new Random();
// Get a random integer in the range of 0 through 1, 0 means tails up, 1 means heads up.
sideUp = rand.Next(2);
// Display the side that is up.
if (sideUp == 0){
// Display tails up.
tailsPictureBox.Visible = true;
headsPictureBox.Visible = false;
}
else{
// Display heads up.
headsPictureBox.Visible = true;
tailsPictureBox.Visible = false;
}
}

Solution 34
Review Questions
Question 1

If you know a vehicle’s speed and the amount of time it has traveled, you can calculate the
distance it has traveled as follows:

For example, if a train travels 40 miles per hour for 3 hours, the distance traveled is 120 miles.
Create an application with a form similar to the one shown in the figure on the next slide.
The user enters a vehicle’s speed and the number of hours traveled into text boxes. When the
user clicks the Calculate button, the application should use a loop to display in a list box the
distance the vehicle has traveled for each hour of that time period.
Figure for Question 1 37
Question 2

Celsius to Fahrenheit Table


Assuming that C is a Celsius temperature, the following formula converts the
temperature to a Fahrenheit temperature (F):

Create an application that displays a table of the Celsius temperatures 0–20 and their
Fahrenheit equivalents. The application should use a loop to display the
temperatures in a list box.
38
Question 3

World Population
 The United States Census Bureau (USCB) had estimated the current world population to be
around 7 billion in the current year.
 The world population is, at present, growing at a rate of around 1.14 percent per year.
 Create an application that projects the estimated world population over the coming years.
The application allows the user to enter the number of years to be projected, and calculates
the total global population at that period of time.

39
Question 4

Ozone Layer Depletion


The ozone layer is currently depleting at about 4 percent per decade.
The average amount of ozone in the stratosphere across the globe is about 300 DU.
Create an application that displays the number of DUs it would deplete each decade
for the next 10 decades. Display the output in a ListBox control.

40
Question 5

Dice Simulator
 Create an application that simulates rolling a pair of dice. When the user clicks a button,
the application should generate two random numbers, each in the range of 1 through 6, to
represent the value of the dice.

 Use PictureBox controls to display the dice.

 Search for images that you can use in the PictureBoxes.)


41
Question 6

 Random Number Guessing Game


 Create an application that generates a random number in the range of 1 through
100 and asks the user to guess what the number is. If the user’s guess is higher
than the random number, the program should display “Too high, try again.”

 If the user’s guess is lower than the random number, the program should display
“Too low, try again.”
42
Question 6 (Cont’d)

 If the user guesses the number, the application should congratulate the user and
then generate a new random number so the game can start over.

 Optional Enhancement: Enhance the game so it keeps count of the number of


guesses that the user makes. When the user correctly guesses the random number,
the program should display the number of guesses.

43

You might also like