









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Exam; Class: Intro to Computer Programming; Subject: Computer Science; University: Lake Superior State University; Term: Unknown 1989;
Typology: Exams
1 / 17
This page cannot be seen from the preview
Don't miss anything!
3-2 Introduction to Computer Programming Using C#
Since a computer program is a specification for transforming input data into output data, it's natural that we concern ourselves with both the types of data your programs can manipulate, and also the kinds of operations you may want to perform upon that data.
Most programming languages support two general classes of data items. The first of these classes includes the literal constants, which, as the name implies, are fixed quantities. The second class of data consists of variables, which are changeable during the life of a program.
In addition to these fundamental classes of data, C# supports several data types, and provides facilities that allow the programmer to define additional data types if those supplied with the language aren't adequate.
The first basic class of data we’ll use is the numeric type. As you would expect, numeric data items are primarily used for performing arithmetic operations. In actuality, most languages, including C#, recognize two kinds of numeric data – one for whole numbers, and the second for values that contain a fractional component. This is because the underlying computer hardware uses a different representation for these two numeric types. Whole numbers are stored as exact values, at least up to the internal limits of the hardware, while fractional values are stored as approximations, in a form that is similar to that used in scientific notation.
The second basic data class we’ll be working with is the character string. Usually, this data type is used when keeping track of names or words, but can, in fact, also be used for numeric quantities like zip codes or telephone numbers, which aren’t normally involved in arithmetic operations. As with the numeric types, there are usually representational reasons to distinguish between a single character and a multi-character string.
Another common data type is the enumerated item, which is a list of specific values that a variable can assume. The simplest example of this kind of item is the C# data type bool , which is used to represent a value of either true or false. It’s also possible to create your own enumerated data type with almost any set of allowable values. For example, a programmer might define an enumerated item representing somebody’s choice for a breakfast fruit, with some of the possible values including Grapefruit , Orange , and Banana.
In C#, a literal constant is defined by simply writing out the value explicitly. The following are some examples of numeric literals:
17 -12.6 3.14159265 0 0.
The rules for defining a numeric literal are fairly simple - just write down the value you want to express. You don’t use fractions, though; fractional literals are expressed in decimal form,
Chapter 3: Input, Output, and Arithmetic 3-
instead. While not mandatory, it’s good programming practice to place a digit both before and after any decimal points. Thus, ½ should be written as 0.5, rather than as .5. For the record, if you do write out the fraction ½ as 1 / 2, the computer actually treats this as an arithmetic operation – the division of the constant value 1 by the constant value 2. As we’ll discuss in more detail later, this expression will evaluate to 0 in C# - almost certainly NOT what you expected! This occurs because this is interpreted to mean the integer division of 1 by 2, and, with integer division, remainders are discarded.
For extremely large or small values, you can also express a literal value in an alternate format, typically called exponential form. This form is comparable to scientific notation. For example, in scientific notation, the number 3,142,000,000,000,000 is usually written as 3.142 x 10^15 , while the number 0.0000005 can be written as 5 x 10-7. In exponential form, these values can be written as:
3.142e+15 5e-
In C#, a single-character literal is defined by placing the desired character inside a pair of apostrophes, like this:
'A' '7' '?'
It’s also possible to create a literal value representing a special character, such as a tab or end-of- line symbol, using an escape sequence. Some of the more common escape sequence values are summarized below:
Escape Sequence Meaning \n (^) New line \t (^) Horizontal Tab \ (^) Backslash Character ' (^) Apostrophe (Single Quote) " (^) Quote Symbol (Double Quote) \0 (^) Null character
Inside the computer, characters are represented by a numerical code. In many programming languages, each character value is stored as a single byte, or 8-bit value. This, in turn, allows for a total of 256 possible characters – sufficient for many applications, but far from adequate if you want to represent non-English character sets. In C#, an alternate representational form, known as Unicode, is instead utilized. Simply stated, a Unicode value is actually a 16-bit quantity, which means that more than 65,000 distinct characters can be represented.
You can use escape sequences to specify Unicode values directly, although to do so, you need to know the correct numeric value, in base 16 (hexadecimal), for the character you want to represent. For example, the letter A is represented by the hexadecimal Unicode value 0041. The literal character constant representation of the letter A, as a Unicode value, would be:
Chapter 3: Input, Output, and Arithmetic 3-
In practice, most C# programmers use lower-case letters almost exclusively when defining variable names, except when a variable name consists of multiple words or word fragments. In these cases, the first letter of each word or word fragment after the first word in the variable name will be capitalized. Note that this is NOT a rule, but just a convention that has been adopted by many programmers.
A variable declaration in C# consists of a data type, following by the names of one or more variables that are to have that type, separated by commas. The declaration is then terminated by a semicolon. Normally, variables are defined at or near the beginning of instruction blocks within your program, although they technically can be placed almost anywhere within your program. The fundamental rule, which provides much of the motivation for placing variable declarations near the start of an instruction block, is that every variable must be defined before it can be referenced.
Some of the more commonly used data types in C# include:
int : a whole-number value in the range of ±2,147,483,
long : a whole-number value in the range of ±9,223,372,036,854,775,
float : a fractional value with 7 digits of accuracy and a range of approximately -45 to +38 for the exponent
double : a fractional value with 15 to 16 digits of accuracy and a range of approximately -324 to +308 for the exponent
char : a single character of data
string : a multi-character string
bool : a Boolean (true or false) value. The term “Boolean” is a reference to the mathematician George Boole, who defined a mathematical system called Boolean Algebra that is the foundation of modern digital circuitry.
A typical variable declaration block might look like this:
string name; int age, yearHired; double salary; bool married;
Values are placed in variables either by reading them from some external source, such as a
3-6 Introduction to Computer Programming Using C#
keyboard or disk file, or by explicitly storing them with an assignment statement of the form:
variable = value;
It’s also possible to initialize variables when they are defined by following the variable name with an equal sign and the initializing value:
int first = 1, second = 2;
By throwing the keyword const into the declaration, you can create a named constant whose value cannot be changed within the program:
const double PI = 3.14159265;
Many programmers like to use all upper-case letters for named constants to visually emphasize the fact that the data item is a named constant, rather than a variable.
In traditional environments, programming languages include some type of output directive that allows the programmer to display results. For example, if you were developing a C# application that operated in “console mode” – without the now-common graphical environment, you could display the message "This is a test of the C# output system" using the WriteLine directive:
System.Console.WriteLine ("This is a test of the C# output system");
In the graphical environment, it’s more common to use Label components to display messages. This is surprisingly easy – simply assign the desired character string to the Text attribute of the Label component. For example, to display the same message in a Label component that has been given the name messageLabel , you could say:
messageLabel.Text = "This is a test of the C# output system";
In most programming languages, you can’t use numeric values when a character value is expected, nor can you use character strings when numeric values are needed. Not only would the data items have different internal representations, but if a numeric value with a fractional component is used in a character string context, it wouldn’t be clear how many digits should appear following the decimal point.
C# provides a default conversion mechanism for converting numeric values to character strings. While you can’t assign a numeric value directly to an item of type String , you can implicitly convert a numeric value as a part of a concatenation operation. For example, if you’ve stored a
3-8 Introduction to Computer Programming Using C#
Enabled : In some cases, you want to prevent the keyboard user from entering a value into a text box until after some event has occurred. One way to block access to the control is to set the Enabled property to False. When the delayed event has occurred, you can then change the Enabled property back to its default value of True.
TabStop : Normally, you move from field to field on a Delphi form by either hitting the tab key or by clicking the destination field with the mouse. If you set a component's TabStop property to False , however, pressing tab will not lead you to the associated field; you can only move there by using the mouse. If you've pre-loaded a default value into an edit control, you may decide to disable TabStop and force the user to manually (with the mouse) move to and change that field.
Visible : Another way to block access to a control is to hide it from view. By setting the Visible property to False , you hide the corresponding control. Subsequently resetting the value to True will cause the field to re-appear. Not surprisingly, the keyboard user cannot move focus to an invisible component.
Font : If you want text typed into the edit to be in a different font, or a different size or color, than that of the parent form, you can change the font attributes using this attribute, just like you can adjust the initial font settings for the form itself.
Once the program's user indicates that they've completed entering data into a text box, the program can access that data by referencing the Text property of the component. If the data in the box is to be treated as a character string (for example, a name or address), you can use it directly. If the data is supposed to represent a numeric value, however, it's necessary to convert it from character to numeric form.
To carry out these conversions, C# uses a special class named Convert that provides functions for the various numeric types. The two functions that we’ll be relying on to handle the bulk of our needs are Convert.ToInt32() and Convert.ToDouble(). As you may have guessed from their names, ToInt32() is used when the value in the text box is expected to be a whole number, while ToDouble() is used when the value may contain a decimal point.
For example, if a form has a text box named creditsEarnedIn , into which a user is expected to enter a whole number value, then that value might be transferred into the variable creditsEarned , of type int , like this:
creditsEarned = Convert.ToInt32(creditsEarnedIn.Text);
Similarly, if that same form had another text box named gpaIn , and the value in that control is expected to have a decimal point, it could be transferred to the variable studentGPA like this:
studentGPA = Convert.ToDouble(gpaIn.Text);
Chapter 3: Input, Output, and Arithmetic 3-
Unfortunately, if the keyboard user has entered an invalid value (perhaps by including an improper character), or perhaps hasn't entered anything at all, the conversion will fail. C# does provide a mechanism for trapping this type of error, but it’s not easy for new programmers to deal with, so we'll just assume that the keyboard user would never do such a foolish thing.
Typically, an application that requires one or more data values from the keyboard user will use a data entry form, with a text box component, and an identifying label, for each data value that must be entered. The sample form shown below illustrates a typical C# input form:
It's important that the fields be arranged in a natural order, and that hitting the tab key moves the focus from one field to the next in the same order that they appear on the form. Normally, the easiest thing to do is to simply ensure that the text box controls are added to the form in order. Sometimes, though, you may find that the controls aren’t in their natural order, either because you got careless, or perhaps because you added additional controls after designing the initial form. When this happens, you can manually adjust the order in which the controls receive focus.
Any of the controls that can hold focus have two attributes – TabStop and TabIndex – that are used to specify whether or not the cursor should automatically stop at that control ( TabStop ), and the order in which that control should receive focus ( TabIndex ). On the input form shown above, the 3 text box components and the button component would, under normal circumstances, all have their TabStop attributes set to True. Furthermore, the TabIndex settings for the 3 text box controls would be 0, 1, and 2, while the TabIndex setting for the button would be 3. If you change the TabStop setting for a control to False , then the only way for the keyboard user to focus on that control would be to use the mouse to move directly there. By manually changing the sequence numbers that are assigned to the TabIndex settings, you can adjust the default order in which the tab key moves the focus from control to control.
Also, there has to be some mechanism for the user to indicate that all of the text box components have been filled in, so the program can go ahead and perform whatever actions are required. Typically, a button, placed at the bottom of the form, is used for this purpose. It's very important
Chapter 3: Input, Output, and Arithmetic 3-
Operator Example Comments
+ A + B Addition
**- A - B Subtraction
The first three operators behave exactly as you'd expect, and correspond directly to normal arithmetic usage. As noted in the discussion, though, division can yield some surprises if you aren’t careful. If you divide 1 by 3, your answer will be 0, but if you divide 1 by 3.0, or 1.0 by 3, or 1.0 by 3.0, then you’ll get a result of 0.33333333333, as you would expect. Obviously, this can lead to some unexpected surprises if you aren’t careful.
The % operator is an interesting, and surprisingly useful operator that can only be used in conjunction with integer values. As noted above, this operator can be used to find a remainder, which can, in turn, be used, for example, to test divisibility, among other things. For example, 27 % 5 is 2, since 27 divided by 5 yields a quotient of 5, and a remainder of 2. Since this result in non-zero, 27 is not divisible by 5.
In order to provide for more complex arithmetic needs, C# also incorporates a wide variety of basic arithmetic functions, including those listed in the following table:
Function Example Comment Abs Math.Abs(X) Absolute value; strip the sign Sqrt Math.Sqrt(X) Square root Sign Math.Sign(X) Returns the “sign” of X; +1 if X is positive, -1 if X is negative, or 0 if X is 0 Pow Math.Pow(X,Y) Compute the value of X raised to the Y power, or XY Sin Math.Sin(X) Trigonometric sine; X is in radians Cos Math.Cos(X) Trigonometric cosine; X is in radians Tan Math.Tan(X) Trigonometric tangent; X is in radians Asin Math.Asin(X) Trigonometric inverse sine; X must be between -1 and 1, and the result will be in radians Acos Math.Acos(X) Trigonometric inverse cosine; X must be between -1 and 1, and the result will be in radians
3-12 Introduction to Computer Programming Using C#
Atan Math.Atan(X) Trigonometric inverse tangent; the result will be in radians Atan2 Math.Atan2(X,Y) Trigonometric inverse tangent; the result will be angle, measured in radians, whose tangent is X / Y Exp Math.Exp(X) Exponential; raise e to the power X Log Math.Log(X) Natural, or base e, logarithm of X Log10 Math.Log10(X) Common, or base 10, logarithm of X Round Math.Round(X) Round X to the nearest integer PI Math.PI The value of p , or 3.14159… E Math.E The value of e, the base of the natural logarithms, or 2.71828…
The most common use of arithmetic operators is in assignment statements, such as the following:
result1 = a + b; result2 = 2a - b; result3 = Math.Sqrt(Math.Pow(a,2) + Math.Pow(b,2));*
You should be aware, however, that care must be used when writing an arithmetic expression. This is because the order in which the expression is evaluated isn't just based on the order, from left to right, in which the expression is written. The relative precedence of the operators also comes into play. Specifically, parentheses are, in all cases, used to force immediate attention to some portion of an arithmetic expression. It's only after all parenthesized portions of the expression, along with any arithmetic functions, have been evaluated that the remainder of the expression will be processed. At this point, the multiply and divide operators will be evaluated, on a left to right basis. Finally, add and subtract operators will be processed from left to right.
When we write an algebraic expression, we also rely on the relative precedence of the operators. In addition, though, we use visual cues that aren't directly supported in conventional programming languages, like C#. For example, to find the average of three numbers, we might write the algebraic expression:
Avg = a + b + c 3 If we're not careful, we might ignore the implied grouping in the numerator, and write this expression as: avg = a + b + c / 3;
Unfortunately, the precedence rule says to divide c by 3, and not the entire sum. The solution, of course, is simple - use parentheses to force the sum to be evaluated first: avg = (a + b + c) / 3;
3-14 Introduction to Computer Programming Using C#
a) Transfer the hourly rate and rate of pay from the text box controls to program variables b) Perform the necessary computations c) Transfer the results to the appropriate label control
To support these actions, the program will need 3 distinct variables - 2 to hold the values from the text box controls, and 1 more to hold the results of the computation. Since the data we're dealing with will likely include decimal points, all these values should be of type double.
To implement the actions associated with the Compute button, you should:
double hourlyRate, hoursWorked, grossPay;
hourlyRate = Convert.ToDouble(textBox2.Text); hoursWorked = Convert.ToDouble(textBox3.Text);
grossPay = hourlyRate * hoursWorked;
label5.Text = "" + grossPay;
label5.Visible = true;
button2.Focus();
Step 3: Test the Program
While there are still a few details to be completed, this is a good time to give your program a test run, and look for any obvious problems with the work completed so far.
You should be able to enter values into the text box fields, and perform the appropriate computation by clicking the Compute button. Notice what happens if you leave any of the text box controls blank, or place non-numeric values in the Hours Worked or Hourly Rate fields.
Chapter 3: Input, Output, and Arithmetic 3-
Step 4: Program the Next Employee Button
While testing the program, you probably noticed that it remembered the values you had entered after it had performed the necessary computations. Once you've finished with a particular employee, it would appropriate for the program to clear the form, and reset the program focus to the text box control for the employee's name. This is the purpose of the Next Employee button. When it is pressed, the form should be cleared in preparation for another employee's data. To accomplish this, the following instructions can be entered into the event handler for the Next Employee button:
textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); label5.Visible = false; textBox1.Focus();
Step 5: Test the Program
Again, it's a good idea to test these latest program changes to ensure that, as expected, the form clears whenever the Next Employee button is pressed. The computational instructions added earlier should also still work in the same way.
Step 6: Program the Done Button
When the Done button is clicked, your program should terminate. Therefore, adding the single instruction, Close() , to the “click” handler for the Done button is all that is required.
Chapter 3: Input, Output, and Arithmetic 3-
To support these actions, the program will need 3 distinct variables - 2 to hold the values from the text box controls, and 1 more to hold the results of the computation. Since the data we're dealing with will likely include decimal points, all these values should be of type double.
To implement the actions associated with the Compute button, you should:
int atBats, hits; double battingAvg;
atBats = Convert.ToInt32(textBox2.Text); hits = Convert.ToInt32(textBox3.Text);
battingAvg = hits / (1.0 * atBats);
label5.Text = "" + battingAvg;
label5.Visible = true;
button2.Focus();
Step 3: Test the Program
While there are still a few details to be completed, this is a good time to give your program a test run, and look for any obvious problems with the work completed so far.
You should be able to enter values into the text box fields, and perform the appropriate computation by clicking the Compute button. Notice what happens if you leave any of the text box controls blank, or place non-numeric values in the At Bats or Hits fields.
3-18 Introduction to Computer Programming Using C#
Step 4: Program the Next Player Button
While testing the program, you probably noticed that it remembered the values you had entered after it had performed the necessary computations. Once you've finished with a particular employee, it would appropriate for the program to clear the form, and reset the program focus to the text box control for the employee's name. This is the purpose of the Next Player button. When it is pressed, the form should be cleared in preparation for another employee's data. To accomplish this, the following instructions can be entered into the event handler for the Next Player button:
textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); label5.Visible = false; textBox1.Focus();
Step 5: Test the Program
Again, it's a good idea to test these latest program changes to ensure that, as expected, the form clears whenever the Next Player button is pressed. The computational instructions added earlier should also still work in the same way.
Step 6: Program the Done Button
When the Done button is clicked, your program should terminate. Therefore, adding the single instruction, Close() , to the “click” handler for the Done button is all that is required.