Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Forming Counts and Totals - Introduction to Computer Programming | CSCI 105, Exams of Computer Science

Material Type: Exam; Class: Intro to Computer Programming; Subject: Computer Science; University: Lake Superior State University; Term: Unknown 1989;

Typology: Exams

Pre 2010

Uploaded on 08/07/2009

koofers-user-zja
koofers-user-zja 🇺🇸

10 documents

1 / 11

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
4-2 Introduction to Computer Programming Using C#
Forming Counts and Totals
Frequently, a programming application needs to count the number of times some event occurs, or
compute a running total from a series of values that arise in a program. In both cases, the key to
this type of processing is an instruction of the form:
variable = variable + amount;
This instruction tells the computer to take the current value of variable, add amount, and then
store the result back as variable. If amount is some variable or expression, this instruction can
be used to form a sum. If amount is always 1, however, the value of variable will serve as a
counter, increasing by 1 each time the instruction is executed. If we ensure that variable is 0 to
begin with, this instruction will correctly form the desired total or count.
Because this is such a commonly encountered task, C# provides a couple of “short cut”
arithmetic forms for generating sums and counts:
variable += amount; // add "amount" to variable
variable++; // add 1 to variable;
There is still one important detail that must be addressed before looking at a more explicit
example. In C#, a variable is "owned" by the program module in which it is initially declared.
When we define a variable within an event handler, it is owned by that event handler, and cannot
be referenced outside of the event handler. This isn't a problem if an event handler performs a
computation, and immediately displays the result. For summary data, however, things get
messier. This is because the variables used for summary purposes are typically initialized in one
place, modified in another, and then displayed in a third. Obviously, the variables must somehow
be shared.
The easiest solution to this problem is to declare the variables to be part of the form. Recall that
the first few lines of a C# application look like this:
namespace …whatever…
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
It’s permissible to slip variable declarations into the class declaration for Form1, like this:
public partial class Form1 : Form
{
// You can define variables here
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Forming Counts and Totals - Introduction to Computer Programming | CSCI 105 and more Exams Computer Science in PDF only on Docsity!

4-2 Introduction to Computer Programming Using C#

Forming Counts and Totals

Frequently, a programming application needs to count the number of times some event occurs, or compute a running total from a series of values that arise in a program. In both cases, the key to this type of processing is an instruction of the form:

variable = variable + amount;

This instruction tells the computer to take the current value of variable , add amount , and then store the result back as variable. If amount is some variable or expression, this instruction can be used to form a sum. If amount is always 1, however, the value of variable will serve as a counter, increasing by 1 each time the instruction is executed. If we ensure that variable is 0 to begin with, this instruction will correctly form the desired total or count.

Because this is such a commonly encountered task, C# provides a couple of “short cut” arithmetic forms for generating sums and counts:

variable += amount; // add "amount" to variable variable++; // add 1 to variable;

There is still one important detail that must be addressed before looking at a more explicit example. In C#, a variable is "owned" by the program module in which it is initially declared. When we define a variable within an event handler, it is owned by that event handler, and cannot be referenced outside of the event handler. This isn't a problem if an event handler performs a computation, and immediately displays the result. For summary data, however, things get messier. This is because the variables used for summary purposes are typically initialized in one place, modified in another, and then displayed in a third. Obviously, the variables must somehow be shared.

The easiest solution to this problem is to declare the variables to be part of the form. Recall that the first few lines of a C# application look like this:

namespace …whatever… { public partial class Form1 : Form { public Form1() { InitializeComponent(); }

It’s permissible to slip variable declarations into the class declaration for Form1 , like this:

public partial class Form1 : Form { // You can define variables here

Chapter 4: Counts and Totals; Numeric Formatting; Message Boxes 4-

public Form1() {

When one or more variables are declared in this way, they are referred to as “global” to the entire form; in other words, they can be referenced from any of the program instructions in any of the event handlers associated with the form.

To see how summary results might be generated in an actual application, suppose you need to find the total number of customers and total of all sales that occur at a store. The first step would be to declare variables to hold the summary values, and initialize them to zero:

public partial class Form1 : Form { int customerCount = 0; double salesTotal = 0;

public Form1() {

Subsequently, you will have to include instructions like the following in the "sales processing" portion of the program:

Customer_Count++; Sales_Total += Current_Sale;

Displaying Summary Data Using On-Form Fields

In some cases, the value of a summary variable is only used within the program. Usually, though, it is necessary to display summary values. One way to do this is to add fields to the main form to hold the summary results as they are computed.

For example, consider the following (partial) data entry form:

Chapter 4: Counts and Totals; Numeric Formatting; Message Boxes 4-

To illustrate, consider the following examples:

Format directive Result (^ denotes a space) String.Format ("{0, 4}", 27); ^^ String.Format ("{0, 7:f2}", 39.867); ^^39. String.Format ("{0, 7:f2}", -496); -496. String.Format ("{0, 7:e2}", 1352.7); 1.35e+ String.Format ("{0, 7:c2}", 1352.7); $1,325.

While these examples are far from exhaustive, they do illustrate a couple of basic points. In the first 2 examples, you can see how extra spacing is added on the left if the format specification allows for more total width than is needed. The second example shows how places after the decimal point are rounded if the requested precision is less than the precision of the value that is being formatted. In contrast, the third example shows how extra zeros are used on the right if the fractional value has less precision than is being requested. The fourth and fifth examples not only show what to expect when either exponential and currency formats are used, they also show that, if the minimum width specified is less than the provided width, the result will be expanded as necessary.

C# supports several other formatting options, but these should serve our needs for now.

Using Message Boxes to Display Summary Results

While it is sometimes reasonable to display summary results on an applications main form, as was done in the previous chapter, it is often preferable to display these summary values on a separate form. Typically, this summary form is displayed at the time the program terminates, although it's also possible that it might be shown in response to some type of user-generated input request, such as a button click.

The simplest was to display summary data on a secondary form is to use Windows’ built-in message box. To illustrate, the instruction:

MessageBox.Show("This is a test", "Testing...", MessageBoxButtons.OK, MessageBoxIcon.Warning);

will generate a simple popup, showing the message This is a test , as shown below:

4-6 Introduction to Computer Programming Using C#

As this example illustrates, when you “show” a message box, you’re expected to provide 4 pieces of information:

  • The text to be displayed in the message box
  • The “caption” to be displayed at the top of the message box
  • The type of button to include in the message box
  • An icon to be displayed beside the message

Some of the legal icon settings include:

  • MessageBoxIcon.Warning – an exclamation point in a triangle
  • MessageBoxIcon.Question – a question mark in a circle
  • MessageBoxIcon.Information – a script lowercase i in a circle
  • MessageBoxIcon.None – no icon is included

Most of the time, you’ll likely use the “OK” button, but a couple of the other options include:

  • MessageBoxButtons.YesNo – two buttons - captioned “Yes” and “No” – will be included in the message box
  • MessageBoxButtons.OKCancel – two buttons – captioned “OK” and “Cancel” – will be included in the message box
  • MessageBoxButtons.YesNoCancel – three buttons, captioned “Yes,” “No,” and “Cancel” – will be included in the message box

When you’re using one of the button options, you’d want to be able to test to see which of the buttons was actually clicked within the message box. To do this, you should create a variable of type DialogResult , and “assign” the MessageBox.Show instruction to this variable:

DialogResult Response;

... Response = MessageBox.Show ("Is this correct?", "Please verify the last response", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

We’ll see, when we learn about decision making in the next chapter, how you can test to see the value of the DialogResult variable to determine which button was clicked, and have your program respond appropriately.

To use a message box to display a sum or count, or a maximum or minimum, you might use a form similar to the following:

MessageBox.Show(String.Format ("{0, 7:c2}", totalPayroll), "Total Payroll", MessageBoxButtons.OK, MessageBoxIcon.Information);

4-8 Introduction to Computer Programming Using C#

Project Assignments

Project 4.1: Inventory Management

Your friend Larry, of Larry's Software Shoppe, has asked you to help him out by developing a program that he can use to determine the value of his store's inventory.

Step 1: Create the Data Entry Form

Inventory information should be entered into the program using a form similar to the following:

An Aside: Basic Processing Within the Application

As each inventory item is entered, the value of that item (found by multiplying its price by the quantity on hand) is to be computed; this will be added to a "total inventory value" variable. In addition, counters for the total number of inventory items (each item counts as one, no matter how many of them are on hand) and total inventory "piece count" (add the "on hand" value for each item) are to be maintained.

When all inventory processing is completed, these three values are to be displayed on a child form. When the keyboard user closes this child form, the entire program should close, as well.

Step 2: Perform the Necessary Initialization Actions

As noted above, this application will maintain three accumulator variables during processing. This means that you will need to allocate variables for this purpose, and initialize these variables to appropriate values - in this case, zero. The two count variables should have type int , while the summary variable should be of type double. Remember – these variables should be declared just before the public Form1() constructor declaration.

Chapter 4: Counts and Totals; Numeric Formatting; Message Boxes 4-

Step 3: Program the Item OK Button

When the Item OK button is clicked, the sum and counter variables need to be updated. Therefore, the event handler for this button should be programmed to:

a) Define variables to hold the numeric equivalents of the Price and On Hand values b) Convert the Text attribute of the Price and On Hand text boxes to numeric values c) Add the product of the Price and On Hand variables to the Total Value variable d) Add 1 to the Total Items variable e) Add the value of the On Hand variable to the Total Pieces variable f) Use a message box to display the value of the item ( Price times OnHand ) g) Clear all of the form's text box components h) Set the form's focus back to the Item # text box field

Step 4: Program the Done Button

When the Done button is pressed, your application should display the values of the three accumulator variables on a child form, and then terminate.

While this could be done using 3 individual message boxes, a nicer result will be generated if you instead construct a single string variable to hold identifying messages with the 3 values, and embedded “new line” characters to break up the message across three lines. You might choose to construct the result string like this:

String Results = "Number of Items: " + itemCount + "\n\n" + "Number of Pieces: " + pieceCount + "\n\n" + "Inventory Value: " + String.Format("{0,7:c2}", invValue);

Now you can use a single message box to display this result string. Following the instruction that displays the message box, you should go ahead and Close the program.

Chapter 4: Counts and Totals; Numeric Formatting; Message Boxes 4-

An Aside: Basic Processing Within the Application

The “Next” button is used to indicate that the details for the next step of the project have been entered. For each step, your program should use the information that has been entered for this step to compute the number of man hours (the product of the number of employees and the number of hours) that will be required to complete the step; this value should be displayed in a message box. When the message box closes, the Description , Crew Size , and Hours Needed text boxes should be cleared, focus returned to the Description text box, and the Project Step # should be increased by one.

The “New Project” button is clicked when all of the steps of a single bid have been entered. Presumably, this will occur immediately after the “Next” button is clicked. When this button is clicked, the program should display the total number of steps and total number of man hours that will be required to complete project. After this message box closes, the Project ID text box should be cleared, focus returned to that text box, and the Project Step # value should be returned to 1.

The “Exit” button, as you should expect, will make the program terminate.

Step 2: Perform the Necessary Initialization Actions

It was implied, although not specifically stated in the previous section, that this application will have to maintain a pair of accumulator variables during processing. The first will be a counter variable (of type int ) that will be used to keep track of the step number, while the second (of type double ) will be used to keep track of the total number of man hours needed for to complete a bid.

You should define appropriately named variables to use for this purpose; remember – these variables should be declared just before the public Form1() constructor declaration. The counter variable should be initialized to 1, while the variable to hold the sum should be initialized to 0.

Step 3: Implement the Next Button’s Click Handler

The processing associated with the “Next” button is described above; to implement this, you should program this event handler to:

a) Define variables to hold the numeric equivalents of the Crew Size and Hours Needed values; the Crew Size would be a whole number, while the Hours Needed may have a decimal point b) Convert the Text attribute of the Crew Size and Hours Needed text boxes to numeric values, storing them in the variables defined in the previous step c) Multiply these two values together to determine the number of man hours needed to complete this step of the bid d) Add this value to the total number of man hours needed to complete the bid e) Display this value in a message box, similar to the following:

4-12 Introduction to Computer Programming Using C#

f) Clear the Description , Crew Size , and Hours Needed text boxes g) Shift focus back to the Description text box h) Add 1 to the Project Step # variable, and transfer this updated value to the corresponding field on the form

Step 4: Program the New Project Button

When the “New Project” button is clicked, the summary for the current project should be displayed, using a message box similar to that shown below:

Recall that you can embed a “new line” into a text string by using the escape sequence, '\n'. Also, note that the Project Step # was increased, in Step 3, so it’s value will be one larger than the value that should be displayed in the message box.

After the message box has been displayed, you need to reset the Project Step # to 1, then clear the Project ID text box, and return focus to that text box.

Step 5: Implement the Exit Button

This shouldn’t cause you any difficulty.