Programming In C With Visual Stdio 2010 Lab Manual instant download
Programming In C With Visual Stdio 2010 Lab Manual instant download
Manual download
https://ebookbell.com/product/programming-in-c-with-visual-
stdio-2010-lab-manual-1547090
https://ebookbell.com/product/ms-10266a-programming-in-c-with-visual-
studio-2010-vol-1-student-manual-2581036
https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-1-microsoft-2113632
https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-2-microsoft-2113634
https://ebookbell.com/product/programming-in-c-with-microsoft-visual-
studio-2010-student-manual-2581034
Network Programming In Net With C And Visual Basic Net Fiach Reid
https://ebookbell.com/product/network-programming-in-net-with-c-and-
visual-basic-net-fiach-reid-4110194
https://ebookbell.com/product/parallel-programming-in-c-with-mpi-and-
openmp-michael-jay-quinn-2438258
https://ebookbell.com/product/functional-programming-in-c-with-
categories-221-dimitris-papadimitriou-46704096
https://ebookbell.com/product/an-introduction-to-objectoriented-
programming-in-c-with-applications-in-computer-graphics-2nd-edition-
graham-m-seed-beng-4198618
https://ebookbell.com/product/handson-network-programming-with-c-
learn-socket-programming-in-c-and-write-secure-and-optimized-network-
code-1st-edition-lewis-van-winkle-55536756
OFFICIAL MICROSOFT LEARNING PRODUCT
10266A
Programming in C# with
Microsoft® Visual Studio® 2010
ii Programming in C# with Microsoft® Visual Studio® 2010
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for
any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
of Microsoft of the site or the products contained therein.
© 2010 Microsoft Corporation. All rights reserved.
Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in
the United States and/or other countries.
All other trademarks are property of their respective owners.
Module 1
Lab Instructions: Introducing C# and the .NET
Framework
Contents:
Exercise 1: Building a Simple Console Application 5
Exercise 2: Building a WPF Application 10
Exercise 3: Verifying the Application 14
Exercise 4: Generating Documentation for an Application 17
2 Lab Instructions: Introducing C# and the .NET Framework
Objectives
After completing this lab, you will be able to:
• Create, build, and run a simple console application by using Visual Studio
2010 and C# 4.0.
• Create, build, and run a basic WPF application by using Visual Studio 2010.
• Use the Visual Studio 2010 debugger to set breakpoints, step through code,
and examine the values of variables.
• Generate documentation for an application.
Introduction
In this lab, you will create simple console and WPF solutions to get started with
using Visual Studio 2010 and C#. You will also configure projects, use code-editing
features, and create comments. You will become familiar with the debugger
Lab Instructions: Introducing C# and the .NET Framework 3
interface. You will compile, run, and use the debugger to step through a program.
Finally, you will generate documentation for an application.
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10266A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
Note: Step-by-step instructions for completing the labs in this course are available in the
lab answer keys provided. Completed, working code is available in the Solution folders
under the Labfiles folder for each lab exercise on the virtual machine.
4 Lab Instructions: Introducing C# and the .NET Framework
Lab Scenario
Fabrikam, Inc. produces a range of highly sensitive measuring devices that can
repeatedly measure objects and capture data. You have been asked to write a C#
application to read a small set of input data that a measuring device has generated,
format this data to make it more readable, and then display the formatted results.
The data consists of text data that contains pairs of numbers representing x-
coordinates and y-coordinates of the location of an object. Each line of text
contains one set of coordinates. The following code example resembles a typical
dataset.
23.8976,12.3218
25.7639,11.9463
24.8293,12.2134
You have been asked to format the data like the following code example.
x:23.8976 y:12.3218
x:25.7639 y:11.9463
x:24.8293 y:12.2134
Lab Instructions: Introducing C# and the .NET Framework 5
Scenario
As a prototype, you have decided to implement a console application to read input
from the keyboard and format it. When you are happy that your code is working,
you will then run the code and redirect input to come from a file that contains the
data that you want to format.
The main tasks for this exercise are as follows:
1. Create a new Console Application project.
2. Add code to read user input and write output to the console.
3. Modify the program to read and echo text until end-of-file is detected.
4. Add code to format the data and display it.
5. Test the application by using a data file.
X Task 2: Add code to read user input and write output to the console
1. In the Main method, add the statements shown in bold in the following code
example, which read a line of text from the keyboard and store it in a string
variable called line.
{
// Buffer to hold a line as it is read in
6 Lab Instructions: Introducing C# and the .NET Framework
string line;
// Read a line of text from the keyboard
line = Console.ReadLine();
}
This code uses the Console.ReadLine method to read the input, and includes
comments with each line of code that indicates its purpose.
2. Add the statement and comment shown in bold in the following code
example, which echo the text back to the console by using the
Console.WriteLine method.
X Task 3: Modify the program to read and echo text until end-of-file is
detected
1. In the Main method, modify the statement and comment shown in bold in the
following code example, which read a line of text from the keyboard.
}
// Write the results out to the console window
Console.WriteLine(line);
}
This code incorporates the statement into a while loop that repeatedly reads
text from the keyboard until the Console.ReadLine method returns a null
value (this happens when the Console.ReadLine method detects the end of a
file, or the user types CTRL+Z).
2. Move the Console.WriteLine statement into the body of the while loop as
shown in bold in the following code example. This statement echoes each line
of text that the user has entered.
This code replaces each occurrence of the comma character, "," in the input
read from the keyboard and replaces it with the text " y:". It uses the Replace
method of the line string variable. The code then assigns the result back to the
line variable.
2. Add the statement shown in bold in the following code example to the code in
the body of the while loop.
This code adds the prefix "x:" to the line variable by using the string
concatenation operator, +, before the Console.WriteLine statement. The code
then assigns the result back to the line variable.
3. Build the application.
4. Run the application and verify that it works as expected.
The application expects input that looks like the following code example.
23.54367,25.6789
Your code should format the output to look like the following code example.
Lab Instructions: Introducing C# and the .NET Framework 9
x:23.54367 y:25.6789
x:23.8976 y:12.3218
x:25.7639 y:11.9463
x:24.8293 y:12.2134
In the Command Prompt window, type the command in the following code
example.
5. Close the Command Prompt window, and then return to Visual Studio.
6. Modify the project properties to redirect input from the DataFile.txt file when
the project is run by using Visual Studio.
7. Run the application in Debug mode from Visual Studio.
10 Lab Instructions: Introducing C# and the .NET Framework
The application will run, but the console window will close immediately after
the output is generated. This is because Visual Studio only prompts the user to
close the console window when a program is run without debugging. When a
program is run in Debug mode, Visual Studio automatically closes the console
window as soon as the program finishes.
8. Set a breakpoint on the closing brace at the end of the Main method.
9. Run the application again in Debug mode. Verify that the output that is
generated is the same as the output that is generated when the program runs
from the command line.
Scenario
You have been asked to change the application to generate the data in a more
helpful manner. The application should perform the same task as the console
application except that the output is displayed in a WPF window.
The main tasks for this exercise are as follows:
1. Create a new WPF Application project.
2. Create the user interface.
3. Add code to format the data that the user enters.
4. Modify the application to read data from a file.
2. Using the Properties window, set the properties of each control by using the
values in the following table. Leave any other properties at their default values.
Height 28
HorizontalAlignment Left
Margin 12,12,0,0
VerticalAlignment Top
Width 302
Height 23
HorizontalAlignment Left
Margin 320,17,0,0
VerticalAlignment Top
Width 80
Height 238
HorizontalAlignment Left
Margin 14,50,0,0
Text blank
VerticalAlignment Top
Width 384
12 Lab Instructions: Introducing C# and the .NET Framework
The MainWindow window should look like the following screen shot.
X Task 3: Add code to format the data that the user enters
1. Create an event handler for the Click event of the button.
2. Add the code shown in bold in the following code example to the event-
handler method.
This code reads the contents of the TextBox control into a string variable
called line, formats this string in the same way as the console application in
Exercise 1, and then displays the formatted result in the TextBlock control.
Notice that you can access the contents of a TextBox control and a TextBlock
control by using the Text property.
3. Build the solution, and then correct any errors.
4. Run the application and verify that it works in a similar manner to the original
console application in Exercise 1.
5. Close the MainWindow window, and then return to Visual Studio.
This code reads text from the standard input, formats it in the same manner as
Exercise 1, and then appends the results to the end of the TextBlock control.
It continues to read all text from the standard input until end-of-file is
detected.
Notice that you can use the += operator to append data to the Text property of
a TextBlock control, and you can add the newline character ("\n") between
14 Lab Instructions: Introducing C# and the .NET Framework
lines for formatted output to ensure that each item appears on a new line in
the TextBlock control.
3. Perform the following steps to modify the project settings to redirect standard
input to come from the DataFile.txt file. A copy of this file is available in the
E:\Labfiles\Lab 1\Ex2\Starter folder:
a. In Solution Explorer, right-click the WpfApplication project, point to
Add, and then click Existing Item.
b. In the Add Existing Item – WpfApplication dialog box, move to the
E:\Labfiles\Lab 1\Ex2\Starter folder, select All Files (*.*) in the drop-
down list box adjacent to the File name text box, click DataFile.txt, and
then click Add.
c. In Solution Explorer, select DataFile.txt. In the Properties window,
change the Build Action property to None, and then change the Copy to
Output property to Copy Always.
d. In Solution Explorer, right-click the WpfApplication project, and then
click Properties.
e. On the Debug tab, in the Command line arguments: text box, type
< DataFile.txt
f. On the File menu, click Save All.
g. Close the WpfApplication properties window.
4. Build and run the application in Debug mode. Verify that, when the
application starts, it reads the data from DataFile.txt and displays in the
TextBlock control the results in the following code example.
x:23.8976 y:12.3218
x:25.7639 y:11.9463
x:24.8293 y:12.2134
Scenario
You want to verify that the code for your WPF application is operating exactly as
you require. You decide to create some additional test data and use the Visual
Studio 2010 debugger to step through the application.
The main tasks for this exercise are as follows:
1. Modify the data in the DataFile.txt file.
2. Step through the application by using the Visual Studio 2010 debugger.
1.2543,0.342
32525.7639,99811.9463
24.8293,12.2135
23.8976,12.3218
25.7639,11.9463
24.8293,12.2135
X Task 2: Step through the application by using the Visual Studio 2010
debugger
1. Set a breakpoint at the start of the Window_Loaded event handler.
2. Start the application running in Debug mode.
When the application runs the Window_Loaded event handler, it reaches the
breakpoint and drops into Visual Studio. The opening brace of the method is
highlighted.
3. Step into the first statement in the Window_Loaded method that contains
executable code.
The while statement should be highlighted. This is because the statement that
declares the line variable does not contain any executable code.
16 Lab Instructions: Introducing C# and the .NET Framework
4. Examine the value of the line variable. It should be null because it has not yet
been assigned a value.
5. Step into the next statement.
The cursor moves to the opening brace at the start of the body of the while
loop.
6. Examine the value of the line variable. It should be 1.2543,0.342. This is the
text from the first line of the DataFile.txt file. The Console.ReadLine statement
in the while statement reads this text from the file.
7. Step into the next statement.
The cursor moves to the line in the following code example.
Scenario
You must ensure that your application is fully documented so that it can be
maintained easily. You decide to add XML comments to the methods that you have
added to the WPF application, and generate a help file.
The main tasks for this exercise are as follows:
1. Open the starter project.
2. Add XML comments to the application.
3. Generate an XML comments file.
4. Generate a .chm file.
2. Add the XML comment in the following code example before the
MainWindow class declaration.
/// <summary>
/// WPF application to read and format data
/// </summary>
3. Add the XML comment in the following code example before the
MainWindow constructor.
/// <summary>
/// Constructor for MainWindow
/// </summary>
4. Add the XML comment in the following code example before the
testButton_Click method.
/// <summary>
/// Read a line of data entered by the user.
/// Format the data and display the results in the
/// formattedText TextBlock control.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
5. Add the XML comment in the following code example before the
Windows_Loaded method.
/// <summary>
/// After the Window has loaded, read data from the standard input.
/// Format each line and display the results in the
/// formattedText TextBlock control.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
6. Save MainWindow.xaml.cs.
3. Verify that an XML comments file called comments.xml has been generated in
the E:\Labfiles\Lab 1\Ex4\Starter\WpfApplication\bin\Debug folder, and
then examine it.
4. Copy the comments.xml file to the E:\Labfiles\Lab 1\Ex4\Helpfile folder.
Module 2
Lab Instructions: Using C# Programming
Constructs
Contents:
Exercise 1: Calculating Square Roots with Improved Accuracy 4
Exercise 2: Converting Integer Numeric Data to Binary 12
Exercise 3: Multiplying Matrices 16
2 Lab Instructions: Using C# Programming Constructs
Objectives
After completing this lab, you will be able to:
• Use C# data types and expressions to help implement a numeric algorithm.
• Use C# programming constructs to perform common programming tasks.
• Use arrays to store and process data.
Introduction
In this lab, you will create several applications that implement some common
algorithms. This will help you to become familiar with using the C# syntax and
learn many of the core C# programming constructs.
Important: The purpose of these exercises, and the remaining exercises throughout this
course, is not to make you familiar with mathematical algorithms or engineering
Lab Instructions: Using C# Programming Constructs 3
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10266A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
4 Lab Instructions: Using C# Programming Constructs
Lab Scenario
Fabrikam, Inc. produces a range of highly sensitive measuring devices that can
repeatedly measure objects and capture data. You have been asked to implement
some embedded functionality that several scientific instruments require. You will
write C# applications to build and test your implementations.
Scenario
Some of the software that is being developed to support devices that perform
scientific analysis requires applications to perform calculations with a high degree
of accuracy. The .NET Framework uses the double type to perform many of its
calculations. The double type has a very large range, but the accuracy is not always
sufficient. The decimal type provides a higher degree of accuracy at the cost of a
Lab Instructions: Using C# Programming Constructs 5
Height 28
HorizontalAlignment Left
Margin 12,12,0,0
Text 0.00
VerticalAlignment Top
Width 398
Content Calculate
Height 23
HorizontalAlignment Right
Margin 0,11,12,0
Lab Instructions: Using C# Programming Constructs 7
VerticalAlignment Top
Width 75
Height 28
HorizontalAlignment Left
Margin 12,41,0,0
VerticalAlignment Top
Width 479
Height 28
HorizontalAlignment Left
Margin 12,75,0,0
VerticalAlignment Top
Width 479
8 Lab Instructions: Using C# Programming Constructs
The MainWindow window should look like the following screen shot.
Note: You can display a message in a message box by using the MessageBox.Show
method.
Lab Instructions: Using C# Programming Constructs 9
3. Check that the value that the user enters is a positive number. If it is not,
display a message box with the text "Please enter a positive number," and then
return from the method.
4. Calculate the square root of the value in the numberDouble variable by using
the Math.Sqrt method. Store the result in a double variable called squareRoot.
5. Format the value in the squareRoot variable by using the layout shown in the
following code example, and then display it in the frameWorkLabel Label
control.
Use the string.Format method to format the result. Set the Content property
of a Label control to display the formatted result.
6. Build and run the application to test your code. Use the test values that are
shown in the following table, and then verify that the correct square roots are
calculated and displayed (ignore the "Using Newton" label for the purposes of
this test).
25 5
625 25
0.00000001 0.0001
10 3.16227766016838
8.8 2.96647939483827
2.0 1.4142135623731
2 1.4142135623731
Note: This step is necessary because the decimal and double types have different
ranges. A number that the user enters that is a valid double might be out of range for
the decimal type.
2. Declare a decimal variable called delta, and initialize it to the value of the
expression Math.Pow(10, –28). This is the smallest value that the decimal
type supports, and you will use this value to determine when the answer that
is generated by using Newton's method is sufficiently accurate. When the
difference between two successive estimates is less than this value, you will
stop.
Note: The Math.Pow method returns a double. You will need to use the
Convert.ToDecimal method to convert this value to a decimal before you assign it to
the delta variable.
3. Declare another decimal variable called guess, and initialize it with the initial
guess at the square root. This initial guess should be the result of dividing the
value in numberDecimal by 2.
4. Declare another decimal variable called result. You will use this variable to
generate values for each iteration of the algorithm, based on the value from the
previous iteration. Initialize the result variable to the value for the first iteration
by using the expression ((numberDecimal / guess) + guess) / 2.
5. Add a while loop to generate further refined guesses. The body of the while
loop should assign result to guess, and generate a new value for result by
using the expression ((numberDecimal / guess) + guess) / 2. The while loop
should terminate when the difference between result and guess is less than or
equal to delta.
Lab Instructions: Using C# Programming Constructs 11
Note: Use the Math.Abs method to calculate the absolute value of the difference
between result and guess. Using Newton's algorithm, it is possible for the difference
between the two variables to alternate between positive and negative values as it
diminishes. Consequently, if you do not use the Math.Abs method, the algorithm might
terminate early with an inaccurate result.
6. When the while loop has terminated, format and display the value in the
result variable in the newtonLabel Label control. Format the data in a similar
manner to the previous task.
625 25 25.000000000000000000000000000
10 3.16227766016838 3.1622776601683793319988935444
2 1.4142135623731 1.4142135623730950488016887242
Scenario
Another device has the requirement to display decimal numeric data in a binary
format. You have been asked to develop some code that can convert a non-negative
decimal integer value into a string that contains the binary representation of this
value.
The process for converting the decimal value 6 into its binary representation is as
follows:
1. Divide the integer by 2, save the integer result, and use the remainder as the
first binary digit.
In this example, 6 / 2 is 3 remainder 0. Save the character "0" as the first
character of the binary representation.
2. Divide the result of the previous division by 2, save the result, and use the
remainder as the next binary digit.
In this example, 3 / 2 is 1 remainder 1. Save the character "1" as the next
character of the binary representation.
3. Repeat the process until the result of the division is zero.
In this example, 1 / 2 is zero remainder 1. Save the character "1" as the final
character of the binary representation.
4. Display the characters saved in reverse order.
In this example, the characters were generated in the sequence "0", "1", 1", so
display them in the order "1", "1", "0". The value 110 is the binary
representation of the decimal value 6.
Height 28
HorizontalAlignment Left
Margin 12,12,0,0
Text 0
VerticalAlignment Top
Width 120
Content Convert
Height 23
HorizontalAlignment Left
Margin 138,12,0,0
VerticalAlignment Top
Width 75
14 Lab Instructions: Using C# Programming Constructs
Content 0
Height 28
HorizontalAlignment Left
Margin 12,41,0,0
VerticalAlignment Top
Width 120
The MainWindow window should look like the following screen shot.
Lab Instructions: Using C# Programming Constructs 15
Note: To prefix data into a StringBuilder object, use the Insert method of the
StringBuilder class, and then insert the value of the data at position 0.
7. Display the value in the binary variable in the binaryLabel Label control.
Note: Use the ToString method to retrieve the string that a StringBuilder object
constructs. Set the Content property of the Label control to display this string.
16 Lab Instructions: Using C# Programming Constructs
0 0
1 1
10.5 Message box appears with the message "TextBox does not
contain an integer"
Fred Message box appears with the message "TextBox does not
contain an integer"
4 100
999 1111100111
65535 1111111111111111
65536 10000000000000000
Scenario
Some of the devices that Fabrikam, Inc. has developed perform calculations that
involve sets of data that are held as matrices. You have been asked to implement
code that performs matrix multiplication. You decide to test your code by building
Lab Instructions: Using C# Programming Constructs 17
a WPF application that enables a user to specify the data for two matrices, calculate
the product of these matrices, and then view the result.
Multiplying matrices is an iterative process that involves calculating the sum of the
products of the values in each row in one matrix with the values in each column in
the other, as the following screen shot shows.
This screen shot shows a 3×4 matrix multiplying a 4×5 matrix. This will result in a
3×5 matrix.
Note: The number of columns in the first matrix must match the number of rows in the
second matrix. The starter code that is provided for you in this lab ensures that this is
always the case.
To calculate each element xa,b in the result matrix, you must calculate the sum of
the products of every value in row a in the first matrix with every value in column
b in the second matrix. For example, to calculate the value placed at x3,2 in the
result matrix, you calculate the sum of the products of every value in row 3 in the
first matrix with every value in column 2 in the second matrix:
(5×3)+(4×2)+(2×6)+(3×1) = 38
You perform this calculation for every element in the result matrix.
The main tasks for this exercise are as follows:
1. Open the MatrixMultiplication project and examine the starter code.
2. Define the matrix arrays and populate them with the data in the Grid controls.
3. Multiply the two input matrices and calculate the result.
4. Display the results and test the application.
f Task 2: Define the matrix arrays and populate them with the data in
the Grid controls
1. In Visual Studio, review the task list.
2. Open the MainWindow.xaml.cs file.
3. At the top of the MainWindow class, remove the comment TODO Task 2
declare variables, and then add statements that declare three two-dimensional
arrays called matrix1, matrix2, and result. The type of the elements in these
arrays should be double, but the size of each dimension should be omitted
because the arrays will be dynamically sized based on the input that the user
provides. The first dimension will be set to the number of columns, and the
second dimension will be set to the number of rows.
4. In the task list, double-click the task TODO Task 2 Copy data from input
Grids. This task is located in the buttonCalculate_Click method.
5. In the buttonCalculate_Click method, remove the comment TODO Task 2
Copy data from input Grids. Add two statements that call the
getValuesFromGrid method. This method (provided in the starter code)
expects the name of a Grid control and the name of an array to populate with
data from that Grid control. In the first statement, specify that the method
should use the data in grid1 to populate matrix1. In the second statement,
specify that the method should use the data from grid2 to populate matrix2.
6. Remove the comment TODO Task 2 Get the matrix dimensions. Declare
three integer variables called m1columns_m2rows, m1rows, and m2columns.
Initialize m1columns_m2rows with the number of columns in the matrix1
array (this is also the same as the number of rows in the matrix2 array) by
using the GetLength method of the first dimension of the array. Initialize
m1rows with the number of rows in the matrix1 array by using the GetLength
method of the second dimension of the array. Initialize m2columns with the
number of columns in the matrix2 array.
f Task 3: Multiply the two input matrices and calculate the result
1. In the buttonCalculate_Click method, delete the comment TODO Task 3
Calculate the result. Define a for loop that iterates through all of the rows in
the matrix1 array. The dimensions of an array are integers, so use an integer
variable called row as the control variable in this for loop. Leave the body of
the for loop blank; you will add code to this loop in the next step.
20 Lab Instructions: Using C# Programming Constructs
2. In the body of the for loop, add a nested for loop that iterates through all of
the columns in the matrix2 array. Use an integer variable called column as the
control variable in this for loop. Leave the body of this for loop blank.
3. The contents of each cell in the result array are calculated by adding the
product of each item in the row identified by the row variable in matrix1 with
each item in the column identified by the column variable in matrix2. You will
require another loop to perform this calculation, and a variable to store the
result as this loop calculates it.
In the inner for loop, declare a double variable called accumulator, and then
initialize it to zero.
4. Add another nested for loop after the declaration of the accumulator variable.
This loop should iterate through all of the columns in the current row in the
matrix1 array. Use an integer variable called cell as the control variable in this
for loop. Leave the body of this for loop blank.
5. In the body of this for loop, multiply the value in matrix1[cell, row] with the
value in matrix2[column, cell], and then add the result to accumulator.
6. After the closing brace of the innermost for loop, store the value in
accumulator in the result array. The value should be stored in the cell that the
column and row variables have identified.
Note: The number of rows in the Matrix 2 matrix is determined by the number of
columns in the Matrix 1 matrix.
5. Specify the values for the cells in the matrices as shown in the following tables.
Lab Instructions: Using C# Programming Constructs 21
Matrix 1
1 5 –9
3 –7 11
Matrix 2
2 –8 14
4 –10 16
6 –12 18
6. Click Calculate. Verify that the Result matrix displays the values in the
following table.
Result
–32 50 –68
44 –86 128
Matrix 2
1 0 0
0 1 0
0 0 1
8. Click Calculate. Verify that the Result matrix displays the values in the
following table.
Result
1 5 –9
3 –7 11
22 Lab Instructions: Using C# Programming Constructs
Matrix 2
–1 0 0
0 –1 0
0 0 –1
10. Click Calculate. Verify that the Result matrix displays the values in the
following table.
Result
–1 –5 9
–3 7 –11
This time, the values in Result are the same as those in Matrix 1 except that
the sign of each element is inverted (Matrix 2 is the matrix equivalent of –1 in
regular arithmetic).
11. Close the MainWindow window.
12. Close Visual Studio.
Lab Instructions: Declaring and Calling Methods 1
Module 3
Lab Instructions: Declaring and Calling Methods
Contents:
Exercise 1: Calculating the Greatest Common Divisor of Two Integers by Using
Euclid’s Algorithm 4
Exercise 2: Calculating the GCD of Three, Four, or Five Integers 8
Exercise 3: Comparing the Efficiency of Two Algorithms 12
Exercise 4: Displaying Results Graphically 18
Exercise 5: Solving Simultaneous Equations (optional) 21
2 Lab Instructions: Declaring and Calling Methods
Objectives
After completing this lab, you will be able to:
• Create and call methods.
• Define overloaded methods.
• Define methods that take output parameters.
• Define methods that take optional parameters and call them by using named
arguments.
Introduction
In this lab, you will create methods to calculate the greatest common divisor
(GCD) of a pair of positive integers. You will create an overloaded version of one of
these methods that can take up to five integer parameters. You will modify the
methods to take an output parameter that returns the time taken to perform the
Lab Instructions: Declaring and Calling Methods 3
calculations. Finally, you will use a method that uses optional parameters to
display the relative performance of the methods by displaying a simple graph.
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10266A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
4 Lab Instructions: Declaring and Calling Methods
Lab Scenario
Fabrikam, Inc. produces a range of highly sensitive measuring devices that can
repeatedly measure objects and capture data.
Some of the calculations that various scientific instruments perform depend on
statistical information that is generated by using prime numbers. One of your
colleagues has implemented a method for generating prime numbers, but it does
not have sufficient performance to meet the requirements of the devices that it will
be used with. The software analysts have examined the code and have determined
that it can be improved by using a faster algorithm for calculating the GCDs. You
have been asked to implement a test application that can calculate the GCD of a set
of numbers by using different well-known algorithms, and compare their relative
performance.
prompts the user for the parameter values, and displays the result. You will also
generate a unit test project to enable you to automate testing this method.
Scenario
Some of the data that is collected by devices built by Fabrikam, Inc. must be
encrypted for security purposes. Encryption algorithms often make use of prime
numbers. A part of the algorithm that generates prime numbers needs to calculate
the GCD of two numbers.
The GCD of two numbers is the largest number that can exactly divide into the two
numbers. For example, the GCD of 15 and 12 is 3. Three is the largest whole
number that divides exactly into 15 and 12.
The process for finding the GCD of 2806 and 345 by using Euclid's algorithm is as
follows.
1. Keep taking 345 away from 2806 until less than 345 is left and store the
remainder.
In this case, 2806 = (8 × 345) + 46, so the remainder is 46.
2. Keep taking the remainder (46) away from 345 until less than 46 is left, and
store the remainder.
345 = (7 × 46) + 23, so the remainder is 23.
3. Keep taking 23 away from 46 until less than 23 is left, and store the remainder.
46 = (2 × 23) + 0
4. The remainder is 0, so the GCD of 2806 and 345 was the value of the
previously stored remainder, which was 23 in this case.
Euclid: result
Hint: Set the Content property of a label control to display data in a label. Use the
String.Format method to create a formatted string.
7. Use the window to calculate the GCD for the values that are specified in the
following table, and verify that the results that are displayed match those in the
table.
Random documents with unrelated
content Scribd suggests to you:
caractère[78]. Aussi prétendit-on que le désir de la revoir n'était pas
le moindre motif qui le ramenât à Versailles en 1783. Quatre ans
avaient suffi pour transformer la jeune princesse, dont le front,
rayonnant de tout l'éclat des grâces printanières, semblait destiné
par l'opinion publique à recevoir le bandeau impérial. Le parti
antiautrichien qui dominait à la cour, et qui déjà avait semé à
l'entour de la Reine des défiances et des haines, s'inquiéta d'une
alliance qui devait être contraire à son ascendant et mit tout en
œuvre pour l'empêcher. L'intrigue réussit. On a dit sans raison que
Madame Élisabeth en conçut quelque regret; l'Empereur n'avait point
encore laissé apercevoir dans la politique les excentricités de son
esprit, et il venait de perdre une femme dont la jeunesse, les vertus
et la piété avaient emporté l'amour et la bénédiction de tout un
peuple. Madame Élisabeth, bien qu'elle possédât assurément tout ce
qu'il fallait pour recueillir un tel héritage, ne parut pas attacher plus
de prix à cette union qu'aux autres alliances que la convenance avait
indiquées, mais auxquelles la politique avait trouvé des obstacles.
Ou peut-être Celui qui règne dans les cieux et de qui relèvent tous
les empires, comme dit Bossuet, Celui dont l'œil voyait déjà s'ouvrir
dans l'avenir la prison du Temple et se dresser l'échafaud du 21
janvier, n'avait-il pas voulu enlever toute consolation à la maison
royale.
Les jeux et les plaisirs dont se montre avide la jeune cour laissent
cependant place à des intrigues qui doivent parfois diviser les
membres de la famille royale. Le Roi et ses frères ont chacun un
caractère différent. Louis XVI, qui possède les vertus d'un homme de
bien, est loin d'avoir toutes celles qui conviennent à un roi. Sa
défiance de lui-même est extrême. À l'époque où il n'était encore
que Dauphin, on agitait une question difficile à résoudre: «Il faut,
dit-il, demander cela à mon frère de Provence.» Confiant envers les
autres, il se livre aisément; mais il entre dans des emportements
fâcheux quand il s'aperçoit qu'on le trompe. Il n'a ni fermeté dans le
caractère ni grâces dans les manières. Comme certains fruits
excellents dont l'écorce est amère, il a l'extérieur rude et le cœur
parfait. Sévère pour lui seul, il observe rigoureusement les lois de
l'Église, jeûne et fait maigre pendant les quarante jours de carême,
et trouve bon que la Reine ne l'imite point. Sincèrement pieux, mais
formé à la tolérance par l'influence du siècle qu'il subit sans s'en
rendre compte, il est disposé, trop disposé peut-être à sacrifier les
prérogatives du trône toutes les fois qu'on allègue les intérêts de son
peuple; car un des premiers intérêts d'une nation est le maintien
d'un pouvoir fort et incontesté. Une royauté affaiblie est impuissante
à la fois pour le bien et contre le mal.
On a aussi retenu de cette époque un mot qui fit quelque peu rire
par sa naïveté. La ville de Paris, à l'occasion de ce mariage, dota des
filles. Une d'elles (mademoiselle Lise) se présenta pour se faire
inscrire. On lui demanda le nom de son amoureux, et où il était. «Je
n'en ai point, dit-elle; je croyais que la ville fournissait de tout.» Les
officiers municipaux allèrent lui choisir un mari.
Nous avons dit quel était l'intérieur du palais de Versailles dans les
années qui précédèrent la révolution. Les princes et les princesses
du sang n'y faisaient que de rares apparitions; ils avaient des goûts
différents, des habitudes différentes.
S'il est beau de voir les grandes âmes toujours bien jugées par les
grands hommes, il est touchant aussi de voir les vertus des mères
passer comme un héritage aux enfants et devenir leur entretien le
plus aimé. Marie-Antoinette se plaisait à parler de la bonté de sa
mère (la bonté, dont Bossuet a dit que c'était le trait qui rapprochait
le plus les souverains de Dieu), à citer des actes de charité dont elle
avait été elle-même témoin. «Combien ma mère valait mieux que
nous! dit-elle un jour; ma mère, qui trouvait que le spectacle d'un
seul pauvre suffisait pour déshonorer son règne!» Une autre fois,
s'étant attardée au lit plus longtemps que de coutume, elle s'écria:
«Et ma mère qui se reprochait le temps qu'elle donnait au sommeil,
disant que c'était autant de dérobé à ses peuples!»
. . . . . . . . . . .
. . .
. . . . . . . . . . .
. . .
. . . . . . . . . . .
. . .
À
«À Versailles, ce 27 juin 1781.
. . . . . . . . . . .
. . .
. . . . . . . . . . .
. . .
. . . . . . . . . . .
. . .
Puis voici le nom des Polignac, qui paraît dans ces lettres
comme un point noir à l'horizon. Les calomnies commencent.
Quand on veut détruire l'effet qu'elles peuvent produire sur
l'esprit de Madame Élisabeth, c'est à madame de Bombelles
qu'on s'adresse, comme pour obtenir une grâce de la
princesse.
. . . . . . . . . . .
. . .
. . . . . . . . . . .
. . .
»Je te dirai que j'ai été hier à Passy voir la comtesse Diane;
la conversation s'est tournée sur la santé. Elle m'a dit que
malgré l'extrême besoin qu'elle auroit eu d'aller aux eaux, les
propos infâmes qu'on avoit tenus sur son compte l'en avoient
empêchée, et qu'elle auroit mieux aimé mourir que de faire
aucune démarche qui eût donné la moindre vraisemblance
aux torts qu'on lui prêtoit; que tous ces propos lui avoient
causé la peine la plus sensible. Je lui ai répondu qu'ils étoient
si dénués de bon sens que je trouvois qu'elle avoit tort d'y
attacher un si grand prix, que toutes les personnes honnêtes
n'avoient pas douté un instant de leur fausseté. «Je me flatte,
a-t-elle ajouté, que Madame Élisabeth ne les aura pas sus.»
Je crois qu'elle les ignore, ai-je répondu (elle les savoit déjà à
mon arrivée à Versailles); d'ailleurs elle a une si belle âme et
vous rend trop de justice pour jamais les croire si on les lui
apprenoit.
. . . . . . . . . . .
. . .
. . . . . . . . . . .
. . .
»J'ai quitté hier mon petit Bombon à une heure de l'après-
dînée; il dormoit paisiblement. Je n'ai pu m'empêcher de
verser quelques larmes au moment de notre séparation. C'est
bête, mais je ne puis te rendre ce qui s'est passé en moi:
j'étois oppressée, et, malgré tous les efforts que je faisois
pour être gaie, je ne pouvois en venir à bout. Madame
Élisabeth m'avoit fait chercher pour pêcher, de sorte que j'ai
été obligée de le quitter une heure plus tôt que je ne devois.
J'avoue que cela m'a contrariée à mort; il faisoit à cette triste
pêche un vent et un soleil terribles; nous y sommes restées
jusqu'à deux heures trois quarts, et j'étois transie jusqu'aux
os. Nous ne sommes sorties de table qu'à quatre heures. J'ai
vitement été chez moi, espérant revoir encore un petit
moment mon pauvre enfant; point du tout: il étoit déjà parti
pour Montreuil. Tu avoueras que j'ai dû être bien contrariée
toute la journée. Je suis revenue chez Madame Élisabeth, où
je n'ai pas voulu être maussade, de façon que je m'efforçois
de rire de tout ce qu'on disoit, ce qui me donnoit sûrement un
air fort spirituel. Nous sommes parties à cinq heures, arrivées
ici à six heures et demie, avons fait nos toilettes pour être
rendues au salon à huit heures et demie. Là, j'ai été fort bien
traitée par tout le monde. Le Roi m'a parlé, Monsieur m'a
prise à côté de lui à souper, et a beaucoup causé avec moi
pendant ce temps-là, m'a questionnée sur Ratisbonne, sur toi,
etc. J'ai fait après souper une partie de truc avec Madame
Élisabeth, le chevalier de Crussol et M. de Chabrillant. Le
baron de Breteuil étoit dans le salon; il m'a demandé de tes
nouvelles. Le comte d'Esterhazy n'est pas ici, ce qui me
désespère; mais je pense qu'il y viendra ces jours-ci, car la
seule chose qui m'ait consolée de ce voyage est l'espoir de l'y
voir à mon aise; je serois bien piquée que cela ne fût pas,
mais je ne doute pas qu'il n'y vienne. La Reine est fort
occupée de la duchesse de Polignac. On attend d'un moment
à l'autre qu'elle accouche. Sa Majesté ira y dîner tous les
jours et y passera la journée; elle ne sera ici que pour l'heure
du salon. Madame Élisabeth monte à cheval, j'y monterai
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookbell.com