Upload
earl-marsh
View
213
Download
0
Embed Size (px)
Citation preview
Programming by ExampleVersion 1.0
Objectives
Take a small computing problem, and walk throughthe process of developing a solution.
Investigate the structure and syntax of a C# Program.
Use the Visual Studio code editor and compiler.
Problem
I have a robot that I want to move from position ato position b. I want to move it on the most directroute possible.
a
b
We could run ahead 5 spaces
Then turn 90 and move ahead 3 spaceso
But it would be faster to …
To make this move, we need to* Calculate how much to turn, and* Calculate how far to move
Looks like a right triangle
The path we want to ta
ke
1 2 3 4 5 6
1
2
3
4
The path we want to ta
ke
6
How do we find the angle that we must turn the robot?
4
?
6
4
We know the length of the side opposite the angleand the length of the side adjacent to the angle(rise over run).
θ
tan θ =opposite
adjacent
so … θ = tan 4
6
-1= 33.69
o (rise)
(run)
?
6
4
Now, how do we compute the distance to move?
θ = 33.69o
?
6
4
There are several ways we can do this. Let’s useThe Pythagorean theorem.
θ = 33.69o
c = a + b2 2
?
6
4
There are several ways we can do this. Let’s useThe Pythagorean theorem.
θ = 33.69o
c = a + b2 2 16 + 36=
52=
= 7.211
We have come up with the algorithm required!Let’s write it down step by step.
1. Compute the angle to turn
2. Compute the distance to move
In order to write our program, we need a little more detail.
1. Compute the angle to turn
a. Find the length of the opposite side (rise), ab. Find the length of the adjacent side (run), bc. Divide a by bd. Find the angle whose tangent = a/b
In most programming languages there are librariesof mathematical functions to do things like
… find the angle whose tangent is a/b.
Microsoft provides an extensive set of resourcesTo help us with C# development. On the web,Go to www.msdn.com
2. Compute the distance to move
a. Square the length of side ab. Square the length of side bc. Add them togetherd. Take the square root of the result
When solving a programming problem like this,we often draw an “Activity” diagram, to show
the steps of the program pictorially.
get lengthsof a and b
get lengthsof a and b
divide a by b
get lengthsof a and b
divide a by b
find atan (a/b)
get lengthsof a and b
divide a by b
find atan (a/b)
square a
get lengthsof a and b
divide a by b
find atan (a/b)
square a
square b
get lengthsof a and b
divide a by b
find atan (a/b)
square a
square b add the squares
get lengthsof a and b
divide a by b
find atan (a/b)
square a
square b add the squares
take the square root
get lengthsof a and b
divide a by b
find atan (a/b)
square a
square b add the squares
take the square root
printresults
Now, we are ready to write the program.
Don’t worry about the details of each C# statementin the following slides. The objective of the next few slides it to give you an overview of what a C# programlooks like. Pay attention to the overall organization and structure of the code.
// This program takes two values, and x and a y as real numbers// The program computes the hypotenuse of a right triangle whose// base is x and whose height is y. It also returns the angle between the base// and the hypotenuse.// Author: Joe Coder// Course: CS 1400 section 002// Date Last Modified: July 2, 2009// Version 1.0
We begin all programs with a file prologue.The file prologue explains what is in the file.
The forward slash marks “//” mark this line as a comment. The compiler will ignore this line when compiling the program.
using System;
Next, we have to tell the compiler about any namespaces that we will use. For allPrograms that we will write this semesterWe will use the System namespace.
All of the code that we write in a C# programwill be enclosed in one or more classes. Initiallywe will just use one class. Although we can name this class anything that we want to, we will callit Program. The code within a class is enclosedin curly braces like this
class Program . . .
Every C# program must include a method whosename is “Main”. When your program runs, the computer looks for the method named Main, and begins execution at that point. Everything in theMain method will be between a pair of curly braces.
static void Main( ) …
// declare variables we will use in our programdouble width = 0.0;double height = 0.0;double hypotenuse = 0.0;double theta = 0.0;
We now declare any variables that we will use in this program. We need A place in memory to hold the length of each side of the triangle and a place tohold the size of the angle.
data type
intialization valuesvariable names
The Atan function returns the size of an anglein radians. We will need a constant to changeradians into degrees. We need to declare thisconstant and set its value. The Math classcontains a constant for PI that we will use.
// declare a constant to do conversion// from radians to degreesconst double CONVERSION_FACTOR = 180 /Math.PI;
C# statements all end in a semicolon.
Console.WriteLine("This program computes the hypotenuse of a right triangle. ");Console.Write("Please enter in the base of the triangle: ");
get lengthsof a and b
These statements provide a user prompt. That is, theyhelp the user of the program know what to do next.
The Console class represents the display on the computer.The WriteLine method writes the text in quotation marks to thedisplay and moves to the next line.
width = double.Parse(Console.ReadLine( ) );
get lengthsof a and b
This statement gets the user’s input and saves it in thevariable named base.
The ReadLine method reads a string from the keyboard and returns in-place of itself a temporary string variable. The double.Parse method converts the string into a double which we save in the variable base.
Console.Write("Please enter in the height of the triangle: ");height = double.Parse(Console.ReadLine( ) );
Now, prompt the user to type in the height of thetriangle and store it in the variable height.
get lengthsof a and b
double square = (width * width) + (height * height);hypotenuse = Math.Sqrt(square);theta = Math.Atan ( height / width) * CONVERSION_FACTOR;
Do the calculations necessary to compute thelength of the hypotenuse and the angle.
multiply
divide
add
Console.WriteLine("The hypotenuse of the triangle is 0", hypotenuse);Console.WriteLine"The angle between the hypotenuse and the base is 0:f2", theta);
Print out the results
The 0:f2 is a placeholder.The actual value of theta getsput into this place when the data is written to the console.f2 outputs value as floating pointWith 2 digits after the decimal point.
Console.ReadLine( );
This statements completes the program.
This statement keeps the DOS console window open, untilthe user presses the Enter key, so that the user can see the program’s output.
Here is the complete program …
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009// Version 1.0using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width=0.0, height=0.0, hypotenuse=0.0, theta=0.0;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine(); //End Main()//End class Program
Desk Check the Code
Play the role of the computer. Go throughthe code step by step and see if the resultsat each step are correct and make sense.
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width=0.0, height=0.0, hypotenuse=0.0, theta=0.0;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine(); //End Main()//End class Program
width height
Write down the variable names
hypotenuse theta
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width=0.0, height=0.0, hypotenuse=0.0, theta=0.0;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine();
Use a calculatorTo check this
conversionFactor
57.2957
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width, height, hypotenuse, theta; //init??
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine();
width height ?
Write down the valueLet’s assume the usertypes 3
hypotenuse ?
theta ?
conversionFactor
?
57.2957
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width, height, hypotenuse, theta;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine();
width height ?
Write down the valueLet’s assume the usertypes 3
hypotenuse ?
theta ?
conversionFactor
3
57.2957
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width, height, hypotenuse, theta;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine();
width height
Write down the valueLet’s assume the usertypes 4
hypotenuse theta
conversionFactor
3 4
57.2957
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width, height, hypotenuse, theta;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine();
width height
Check this with acalculator
hypotenuse theta
conversionFactor
3 4
57.2957 Square25
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width, height, hypotenuse, theta;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine();
base height
Check this with acalculator
hypotenuse theta
conversionFactor
3 4
57.2957 square25
5
// Robot Mover Example// Author: Joe Coder// Course: CS 1400-003// Date last modified: April 8, 2009using System;
class Program const double CONVERSION_FACTOR = 180 / Math.PI; static void Main() double width, height, hypotenuse, theta;
Console.WriteLine("This program moves a robot from the origin to"); Console.WriteLine("a point that you specify."); Console.Write("Please enter the x-coordinate of that point: "); width = double.Parse(Console.ReadLine());
Console.Write("Please enter the y-coordinate of that point: "); height = double.Parse(Console.ReadLine());
hypotenuse = Math.Sqrt(width * width + height * height); theta = Math.Atan(height / width) * CONVERSION_FACTOR;
Console.WriteLine("Turn the robot 0:f2 degrees", theta); Console.WriteLine("and move the robot 0:f2 units.", hypotenuse); Console.ReadLine();
base height
Check this with acalculator
hypotenuse theta
conversionFactor
3 4
57.2957 square25
5 36.869
Compiler Demonstration
Using Visual C# Express, type in the code for the program that we just developed. Compile and run it.
Test the program with the values usedin the desk check. Does it produce thesame answers?
Summary of what we did
1. We analyzed the problem to be solveda. Gather information – write down what you knowb. Write down what you need to find outc. Write down the steps to get from a to b, in detail
2. Draw an activity diagram3. Write the code
4. Desk check your code – fix it if necessary (refactor)5. Compile your code – fix compiler errors (refactor)6. Test your code – fix it if necessary (refactor)
Another Example
An Electrical Engineering Problem
Ohm’s law states that the voltage acrossa resistor is equal to the current throughthe resistor times the value of the resistance,or …
v = i * R
Furthermore, if two or more resistors areconnected in series, the equivalent resistanceis equal to the sum of the individual resistances.
Req = R1 + R2 + … Rn
Consider the following circuit:
2Ω 8Ω
12A
Develop a program that will compute the voltage drop across the two resistors.
1. Analyze the problem –a. Write down what you knowb. Write down what you want to find out
2. Write down the steps involved in the program
2. Draw an activity diagram
3. Based on the previous example, see if you can write the code that will solve this problem.
Remember the basic structure of a C# Program
// file prologue
using System;
class Program // declare constants
static void Main( ) // declare local variables
// prompt the user for input // get input
// calculate the answer
// output the answer //End Main()//End class Program
Another Example
telephone #1 telephone #2
telephone #3 telephone #4
A directly connected telephone service is one inwhich each telephone is directly connected to every other telephone in the system. There is nocentral switching station.
The number of lines required to connect n telephones = n (n-1)/2.
Write a program that computes the number oflines required to connect n telephones, where the user supplies the value of n.
1. Analyze the problem –a. Write down what you knowb. Write down what you want to find out
2. Write down the steps involved in the program
2. Draw an activity diagram
3. Based on the previous example, see if you can write the code that will solve this problem.
Remember the basic structure of a C# Program
// file prologue
using System;
class Program // declare constants
static void Main( ) // declare local variables
// prompt the user for input // get input
// calculate the answer
// output the answer //End Main()//End class Program