Академический Документы
Профессиональный Документы
Культура Документы
5
ht t p: / / www. m at hcom poser . com
Dear Reader,
This booklet on Microsoft C# 6.0 is only 101 pages, but it's richly illustrated for
improved, and more immediate comprehension. It's one thing to read a book on
coding, but it's quite another to truly understand what the code is doing, or why
it's doing it. Therefore, this first book in the series has a heavy focus on creating
flow diagrams in order to build deeper and more immediate understanding.
There are 34 check point exercises with solutions included. This material is best
read with Visual Studio Community 2015 open and ready to go. It's important
you practice as soon and frequently as possible. Because this book focuses on
doing things that produce results quickly, this book follows the question and
answer format. The answers are stand alone code examples you should type into
Visual Studio. There are also brief discussions where needed, and the code is
heavily annotated with comments, and many flow diagrams. The driving
philosophy of this first book in the series is simple:
Mastery results from a deep understanding of how many small pieces interact
to produce something more complex. There are no long paragraphs in this book.
Partial List Of Topics Covered:
The most important sequence of steps in this book is shown below. Use these
with every example, and your comprehension will become very deep and
complete. Ultimately, my friends, this is the only kind of comprehesion that is
worth our time and effort.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
I am the author of one of the best selling C# courses on udemy. Please visit
udemy.com for more.
www.udemy.com/u/tomaszowsiak
1
Question 1: How do I download and install Visual Studio 2015 Community?
Answer 1: Do an Internet search for "visual studio 2015 community".
Doing so should bring you to a page similar to the one below. There should
be a big download button. Click it, and follow the directions as they appear.
Downloading and installing Visual Studio 2015 Community can be a process
that takes time, so patience is in order.
2
Question 3: How is "C#" pronounced, and what is it exactly?
Answer 3: In English, we pronounce this as "c sharp". It's a powerful
programming language from Microsoft.
Question 4: How can a simple, understandable program be made in C#?
Answer 4: Launch Visual Studio, and follow the numbered steps below to create
a console application.
1
2 3
3
The simple console application program code is shown below. This code has
features that are not needed at first.
Simplify your code by erasing the elements highlighted in the red boxes below.
1. Erase
2. Erase
3. Erase
4. Erase
Only the code shown below should be left at this point.
3. Click here
4. Get console application
Line numbers
Comments
5
Question 8: How can a line of text be shown in a console application?
Answer 8: Add line 7, as in the code below. Notice that now "using System;" is
no longer faded. This confirms that Console.WriteLine(..) is accessed by writing
"using System;". WriteLine(..) is a method. This version of it prints a sequence
of characters within double quotes. This is called a "string". End your
statements always with semicolons, or ";". Press Ctrl+F5 to run this new code.
1. Load main
2. Hit first curly brace to enter main
3. Print string to screen
5. Exit
6
Check point 1 solution: (Change to code is shown in red box.)
Question 10: It seems that "Console" is something that could occur frequently. Is
a way available of not having to write "Console" many times?
Answer 10: C# has a feature that allows using the "static" keyword together
with a using statement.
1.Put "static System.Console;"
Question 11: Things change. How are changing quantities written in C#?
Answer 11: C# has variables. Variables are named memory locations where the
value stored usually changes over time. The program below shows how to create
a variable and set its value. Name for memory location Memory location
value
salary 45000
stored
7
Question 12: Once a variable value is set, how can the variable value be displayed
in a console window?
Answer 12: C# has string interpolation. Put a dollar symbol before the string,
and then place the variable between curly braces inside the string. Here forward,
"curly braces" will be called "curlies".
8
Check point 2 sample solution: (Code changes in red box.)
Question 14: What is the list of suggested features called that shows as code is
typed?
Answer 14: This list is called "IntelliSense". Learn to use it well. It can save a lot
of time, and wasted effort.
"IntelliSense"
Type System and then hit "." on your keyboard. This will show you what is
accessible in the System name space. If you choose Console, and then type a
period, you'll see what is available as a feature inside the Console class.
1. 2. 3.
1. 2.
Question 15: How can more useful information be found about code features ?
Answer 15: Hover your mouse over a bit of code. An editor tool tip should show.
These are useful because they provide a lot of detail.
9
Question 16: The world is made of many different objects. How can these be
represented in C#?
Answer 16: C# has different data types. Imagine we want to describe a cup. We
look at the cup, and then translate its properties, like whether it has a lid or not,
into data types in C#.
Use decimal for money because
it's accurate. "M" is needed when
putting numbers after the decimal
point in a decimal data type. Use doubles to
represent measured
values, like a height
Use booleans to represent
you can measure
one of only two possible values.
with a ruler.
Either the cup is covered, or it's
not. Only two options are possible.
When deciding on a data type, ask the kinds of questions outlined above.
10
Check point 3 sample solution:
multiplication
symbol
Question 19: Why must we be careful with division when working in C#?
Answer 19: The results of division depend on whether we're dividing a type that
can store decimals, or a type that stores only whole numbers. The integer type,
written as "int" in C#, stores numbers like -5,0 and 10. The double type, on the
other hand, stores values like -45.909, 0.02, and 4.556.
Result is another
whole number like 1
Result is another
double like 1.04
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
12
Question 20: What's the difference in using "/" to divide, and "%" to divide?
Answer 20: Imagine you want to find how many whole weeks in a year, and
how many days are left after all the whole weeks are taken out.
The two symbols "/" and "%" do not produce the same results from division.
Question 21: How are complex mathematical expressions evaluated?
Answer 21: The biggest rule is this: enclose anything you want to happen first
inside parenthesis, and then the order of execution is from the inside to the
outside. There are many other smaller rules, of course. Apply the rules of basic
algebra in most cases, and, if needed, rewrite a complex expression as a
sequence of more basic ones, until you feel you truly understand.
1) 2*(4+3*(4/2))
do 4/2
Check point 5: Write code to find the average of 2) 2*(4+3*2)
the three values shown below. Use variables. do 3*2
x=1, y=5, z=6. 3) 2*(4+6)
sum of values do 4+6
The average is defined as 4) 2*10
number of values
do 2*10
5) 20
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
13
Check point 5 sample solution:
Question 22: Many times expressions that change a variable and store back
to the same location need to be used. What are some examples of this?
Answer 22. Compound operators like "+=" can be used to write x+=1 instead of
x=x+1. The two produce equivalent results, but do not look the same.
x=x+1 is the same as x+=1
Both add 1 to x and store back
to x. Follow the arrows below
to see how x changes.
5+1
6-10
-4*3
-12/2
Question 23: What is the difference between writing x++ and ++x?
Answer 23: x++ first uses x, and then adds 1. ++x first adds 1, and then uses x.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
14
Question 24 : The amount of money in a bank account changes over time. The
number of months in a year never changes. It's constant. How are constant
quantities represented and used in C#?
Answer 24: Look at the triangles shown. The side length changes from triangle
to triangle, but the number of sides NEVER changes. Declare number of sides to
be constant. The ushort data type is used because it's small and never negative.
side length=1
sides=3 side length=2
sides=3 side length=3
sides=3
3.45
3*3.45=10.35
15
Check point 6 sample solution: Every square has four sides
3.45
3.45 3.45
3.45
no y
y
exists
here
y ceases
to exist
new y
exists
here
new y
is dead
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
16
Question 26: To make a useful program, input needs to be accepted, and turned
into output. How can this be done in C#?
Answer 26: C# has a method called ReadLine(). Use it to read string input
from users. A way to make a method act on a variable is to use the following
syntax: "name of variable.name of method()". Example: input.ToUpper()
same
Question 27: How can numerical input be collected, processed, and output?
Answer 27: Collecting numerical input requires a data conversion. Another
way to make a method act on a variable is to pass the variable to the method
using this syntax: MethodName(variable name).
Example: double.Parse(input) means attempt to convert "input" to numerical
form. First, input is "10", and then double.Parse(input) gives 10.
Check point 7: Create a program that finds and shows the sum of two numbers.
This means collect and convert input twice, and then show the sum.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
1. ReadLine() runs first. This means it returns a string from the user.
2. The string returned by ReadLine() is then passed into Parse(..).
3. Parse then returns a numerical value, which is stored to input.
1. ReadLine() is the nested method.
2. Parse(..) is the nesting method.
Line above is equivalent to the two below.
Check point 8: Write code to divide two doubles. Be sure to use method nesting
to both collect and convert input.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
18
Check point 8 sample solution:
19
Check point 9 sample solution:
There are other format specifiers, but the logic is the same.
20
Question 31: Sometimes it's not so easy to decide what data type might result
from a calculation. Is there a way to approach this?
Answer 31: The "var" keyword can be used. The compiler, which is responsible
for making executable programs, can recognize the actual data type based on
what's written on the right side.
Recognized as a string.
Hover your mouse over
var.
Recognized as a integer.
Recognized as a double.
21
Question 33: How can the simplest decisions be made in C#?
Answer 33: C# has the "if/else" construct available for making decisions. As a
simple example, consider comparing two numbers. Follow the numbered arrows
to see the order of execution. "x>=y" is the logical condition to be checked.
1. Check condition, which is true, since 6>=5
2. Run the code
3. Exit
1. 6>=5 is true
2. Run code
3. Exit code
1. 4>=5 is false
2. Run code
3. Exit
Read as "less than Read as "equal to" Read as "not equal to"
or equal to"
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
22
Question 34: How can if/else blocks be made to work with input and strings?
Answer 34: As an example, you can collect a string, and check whether it has
a certain letter. The Contains method can check for something like a character
inside a string.
Hover your mouse over Contains. It has a return type of bool. This is a true or
false value, so Contains can be used as a logical condition to work with if.
Check point 10: Write a program that performs each step below.
1) Accepts a string
2) Since users can type, for example, "hello", or "HELlo", write code
to convert the input to a consistent case, either upper or lower
3) For example, if string is "HEllo", Contains("e") returns false because "e"
and "E" are not considered the same. Your code has to fix this.
23
Check Point 10 sample solution:
1.
2.
3.
4.
5.
6.
In the code above, each if block is checked. These if blocks are independent, so
whether one runs or not has no impact on any of the other ones.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Question 36: Can if/else constructs be nested to produce very fine logic? 24
Answer 36: Yes. Nesting of constructs is always allowed, but the code can be
difficult to read. Follow the numbered arrows to see the execution order.
1.
2.
3.
4. exit
On the next page is a very careful analysis of the operation of this construct.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
25
The steps below outline how a while loop runs. Start at the top, and move down.
Because the counter begins at 1, and goes to 3, the loop runs three times. It then
exits in the fourth picture. Follow the numbers down the pictures carefully. Start
at 1, go to 2, 3, 4, and so on to 11, where the loop exits.
3. Return to top
1. counter=1
1<=3, so true
9. Return to top
7. counter=3
3<=3, so true
10. counter=4
4<=3, so false
11. Exit
If you close your eyes, and are able to run this loop in your imagination, you have
fully grasped it. Be sure to imagine it as a very structured sequence of steps. 4
steps are used to illustrate the essential character of this loop. Now imagine you
have to run 100,000 lines of code. Clearly, writing 100,000 lines of code by hand
would be a great waste of time and energy. Hence, the need for such things as
while loops.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
26
Question 38: I don't understand the while loop, or what it's doing. What
can be done to understand it better?
Answer 38: Use the "step into" feature of the debugger to go through the loop
with complete control, one step at a time. Press Debug->Step Into-> And
then press the little blue arrow that points down. Look for it carefully across
the top of the program.
Do these steps only once. Keep pressing this little arrow to keep looping.
1. 2. 3.
1.Start here
2.
3. counter is now 2
4.
5. counter is now 3
6.
7. counter is now 4,
so condition is false
8. exit
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
27
Question 39: How can if/else constructs be combined meaningfully with while
loops?
Answer 39: A common task might be to get a string, grab each character, and
then to examine that character to see whether it satisfies some condition. Type
and run this code with the debugger if you wish to truly understand.
28
Question 40: Writing many if/else if../else blocks can be tedious and prone to
errors. Is there a better way?
Answer 40: The "switch" block can be used to examine a variable with multiple
possible values. You will benefit immeasurebly from running this code with your
debugger.
1.
2.
3.
4.
Follow the numbered arrows to see how such a block executes. Can you
reproduce the flow in your mind with your eyes closed? That is when you can say
you have truly understood.
Check point 11: Can you improve the program above so it can accept a string
input in varying cases, like "APPLE", or "AppLE", and still show the price?
1) Be sure you read the input from the command window
2) Be sure that the input is changed to a consistent case
3) Once you have your code built, run it with the debugger, step by step
4) Either on paper, or in your mind's eye, draw a numbered arrow diagram to
be sure you truly understand.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
29
Check point 11 sample solution:(Code changes in red boxes)
1.
2.
3.
4.
Question 41: What is a for loop, and what can be done with it?
Answer 41: For loops allow repeating blocks of code. They use an index variable.
Since strings are indexed, for loops can be used to step through the characters of
a string.
On the next page is a very careful analysis of the operation of this construct.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
30
Below is a very careful analysis of how a for loop actually runs.
The first time the loop runs, i=0. Follow the numbered arrows to complete the
first cycle.
1. Set i=0
1. 2. 4. 2. Check condition
3. Print
3. 4. Go to i++
On all other cycles, the loop is reduced to the three steps below.
1. Check condition
1. 3. 2. Print
3. Go back to i++
2.
On all other cycles, the loop is reduced to the three steps below.
1. 3. 1. Check condition
2. Print
2. 3. Go back to i++
2.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
31
Question 42: How can a for loop be run with the debugger?
Answer 42: The steps are outlined below.
Do these steps only once. Keep pressing this little arrow to keep looping.
1. 2. 3.
1. Set i to 1
2. Check condition
3. Run code
4. Increment i by 1
5. Check condition
6. Run code
7. Increment i by 1
9. Exit
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
32
Question 43: Sometimes it's difficult to know when and why to introduce a
variable. Is there some reliable preliminary process that can be applied to help
decide when a variable is right?
Answer 43: Look for a numerical pattern. Then convert the numerical pattern
to symbolic form. Follow the arrows very carefully.
1. Look for a numerical pattern, like the changing values below.
2. Notice the starting value, and ending value.
Question 44: How can if's be combined meanginfully with for loops?
Answer 44: Think of a quantity that can be listed in some fashion, and then
think of some condition that can be applied to each item in the list
Notice that since only one line, WriteLine(...), runs after the if, no curly braces
are needed to enclose WriteLine(..). Remember that i is a variable, so as the loop
runs, it represents the values 1,2,3,4, and thus each of these can be checked to
decide whether it's even.
Check point 12: Can you produce an arrow diagram of the code in question 43?
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
33
Check point 12 sample solution:
Assume i is even, so it's Assume i is odd, so it's
divisible by 2. not divisible by 2
2. 6. 5. 2. 5. 4.
1. 1.
3. 3.
4.
Question 45: It seems like keeping track of an index variable can be challenging.
Is there some other mechanism for stepping through collections of various kinds?
Answer 45: The "for each" loop can be used to examine values in a collection of
items of a great variety of types. Wrting "(int)letter" changes the letter from
something familiar like "p" to its underlying numerical code. This is called
explicit casting. The string "s" is the collection of items to examine. Notice that
no index variable is required to step through the string.
The order of execution of this loop is outlined with numbered arrows below.
Follow them very carefully.
2. 1. 1., 3.
3. 2.
Assume this is the first cycle. These are the remaining cycles.
1. Grab s 1. Grab letter
2. Grab first letter 2. Convert to code and print
3. Convert to code and print 3. Grab next letter and so on...
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
34
Question 46: How can foreach loops be combined with if/else blocks?
Answer 46: Imagine a collection of items to examine. The foreach loops allows
grabbing each character, while the if/else block examine each character.
1. 2. 3. 5. 6.
7. 8. 9.
4.
The foreach loop grabs each letter, and the if/else construct prints it. The blank
' ' character is turned into a new line. Follow the output pictures on the right
from 1 to 9. Notice step 4. appears out of order, but it's not. It shows the cursor
moves down to the next line, proving a blank is turned into a new line. If you
run this code, you see the output below.
Check point 13: Notice that "Press any key..." is on the same line as "There".
Can you add one line of code to make "Press any key..." appear on its own line?
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Question 47: How can values be accumulated in a variable before the variable is
printed?
Answer 47: The symbol "+=" can be used to accumulate values,like numbers, or
even to build up a long string from short pieces.
As you can see above, the sum is first 11, and then grows to 18. The values are
are accumulated using the "+=". In the case of a string, this symbol might build
a long string from short strings.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
36
Question 48: To make a realistic application, it's necessary to be able to collect
input until a user wants to exit. How can this be done?
Answer 48: Use a while(true) loop to achieve this effect. The loop can be
controlled using the break and continue statements.
37
Question 49: If/else constructs seem to occur frequently. Is there some more
efficient way of writing them?
Answer 49: C# has the ternary operator. This operator can be used to
streamline the writing of if/else blocks. The logic it expresses is the same.
38
Check point 14 sample solution:
You should draw a flow diagram to be sure you truly understand.
Question 50: Sometimes two things must be true in order for something to
happen. For example, to qualify for a discount, a customer has to pay with cash,
and buy premium gas at a gas station. How can this be expressed in C#?
Answer 50: C# has the logical "and" operator. This operator returns a value of
true only when both sides of it evaluate to true.
Notice that both variables are of type boolean. Either gas is premium, or not.
Either cash is being used, or not. Each has only two possible values in this simple
example. On the next page is a very careful analysis of this operator.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
39
When both variables are true,
the code executes as shown.
1) Check usingCash 1. 2.
2) Check buyingPremiumGas
3) The "&&" returns true 3.
4) Print discount
5 )Exit
4.
3.
4.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
40
Question 51: Is it possible to use the ternary and logical "and" operators together?
Answer 51: Combining the ternary and "and" operators produces streamlined code.
Imagine a person wants to ride a roller coaster. To qualify, this person must be
45 inches or more, and be with parents. We can express this as shown below.
4. 1. 2. 3.
5.
You can run this code with the debugger using the steps below.
Do these steps only once. Press this little arrow to step through the code.
1. 2. 3.
Hovering your mouse over "&&" shows a tip. This tip shows whether the operator
is currently returning true, or false.
Hover mouse over
Check point 15: Rewrite the code so that the height is accepted from the user.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Question 52: Objects in the world have features. For example, a console window
has features like its width. How can we access such features through C#?
Answer 52: C# has "properties". Properties in C# represent things like the height
or width of a window. Properties are like variables, but they can be coded to be
much smarter than variables. We will learn about coding properties later. For
now, let's use one that already exists.
WindowWidth property
Please be sure to count the x's and the last y above to confirm there are 20.
Hover your mouse of WindowWidth. This shows a tip. This tip contains much
useful information.
Property icon
Property data type
Location of property
Name of property
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
no letter H e y no letter
index=-1 index=0 index=1 index=2 index=3
not allowed allowed allowed allowed not allowed
same as length
Or
no letter no letter H e y no letter no letter
index=-2 index=-1 index=0 index=1 index=2 index=3 index=4
not allowed not allowed allowed allowed not allowed not allowed not allowed
same as length greater than length
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
43
The code executes as shown when
leftSide and rightSide have the
values shown on the right. 1.
1. Check left side is true
2. Since left side is true, 2.
call WriteLine(..)
3. Exit
Not checking the right side is called
short-circuiting.
3.
The code executes as shown when
leftSide and rightSide have the
values shown on the right. 1. 2.
1. Check left side, which is false now
2. Since left side is false, check right side
which is true 3
3. Call WriteLine(..)
4. Exit
4. Exit
4.
Imagine leftSide is given the value "true". When leftSide is then compared against
"true" using "==", the result is another "true". 1. Compare
2. Gives back true
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
44
Check point 16: Can you rewrite the code to Question 53 so that it uses the
logical "and" operator? Below are some questions to guide you.
1) Draw a picture of a string, like "Hey"
2) The logical "and" must check that an index lies within the string
3) If the index is within the string, print the character at that index
4) If the index is not within the string, print an appropriate message
Length=3
Question 54: Indexes occur in strings. But I can imagine storing a block of numbers.
How can that be done in C#?
Answer 54: C# has arrays. An array is a block of values. The values stored are
usually of the same data type, and each value can be set and read using an index.
index=0 -5 data type[ ] name of array = new data type[ size of array ]
index=1 3
index=2 10
Question 55: Strings work well with for loops because strings are indexed. Since
arrays are indexed, can they work with for loops also?
Answer 55: The first entry in an array is at index 0. The last index is at the length
of the array, decreased by 1. Use these two ideas with for loops.
10 5 -6 8 Length is 4, but indexes go from 0 to 3, NOT 1 to 4.
index=0 index=1 index=2 index=3 General rule:Length=n, so indexes go from 0 to n-1
Array initializer
10 is at index 0, 5 at index 1, and so on
1. pretend i=0
1. pretend i=0
2. do array[0]*array[0]
2. then array[0]=10
3. print 100
3. print (10)^2
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
46
To make an array work with a for loop, be sure to iterate over the index values.
To set the value of i correctly, look at the picture. C# is smart enough to allow
writing double[] array={1,2,4,5.6}, without the "new double[]" on the right side.
i i i i
n n n n
d d d d
e e e e
x x x x
0 1 2 3
In other words, writing "int i=1" has two consequences, and both must be handled
for the code to work properly.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Question 56: How can we collect several values at run time from a single line, and 48
then display some output after operating on each value?
Answer 56: We can read input with ReadLine(). This gives a string. We then have
to split the string by a separator like a comma, save the entries into an array of
strings, and then convert each entry to numerical form so it can be operated on.
On the left of the code are pictures of what's actually stored in memory. Notation
like [0] means the entry at index 0. When the array of doubles is first made, it
stores all zeros. This is true in general for doubles. To be more exact, the value is
0.0D.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
49
Question 57: There is a class of students. Each student has his or her grades. How
can this be expressed in C#?
Answer 57: We can convert a situation like this one into an array of arrays.
index=0 index=1
Corresponds to first student Corresponds to second student
index=0 index=1 index=0 index=1 index=2
test 1 test 2 test 1 test 2 test 3
89 98 76 89 91
Notation for nested, or jagged, arrays Grades for first student
You can run this code with the debugger using the steps below. To truly know
what this code is doing at this point, please run it with the debugger now. It's
crucial as a step towards building real comprehension.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
There is more a more detailed discussion on the next page.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
3. Grab new int[]{89,98} first using the outer foreach loop from studentGrades
6. Now grab new int[]{76,89,91} from studentGrades using the outer foreach loop.
Question 58: Imagine an array that stores salaries for 3 people. How can the average
salary be found?
Answer 58: To find an average, apply the defintion of an average as the sum of the
values divided by the number of values.
sum of values add up all the values inside the array with foreach loop
average = =
number of values length of array
Check point 18: Rewrite the code so that it uses a for loop.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
51
Check point 18 sample solution: (Change to code in red boxes)
When i=0, salaries[0] gives 25000 and sum+=salaries[0] adds it to sum, so sum=25000.
When i=1, salaries[1] gives 34000 and sum+=salaries[1] adds it to sum, so sum=59000
When i=2, salaries[2] gives 45000 and sum+=salaries[2] adds it to sum, so sum=104,000
Check point 19: Can you extend the code so that the sum
is printed as it grows. Think of terms of
printing it at EACH execution of either a
for loop, or a foreach loop.
Question 59: It's easy to copy the number "5" from one place to another. How does
C# handle copying simple data types like doubles, decimals, and related types?
Answer 59: Simple data types like doubles are copied by value. This means that a
copy of the data is made, but no other relationship exists between the variables.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
52
Check point 19 sample solution: (Code changes in red boxes.)
Question 60: An array could store 1,000,000 values. Copying entries one by one
could take a long time. How does C# handle this?
Answer 60: Arrays are copied by reference. This means multiple names are made
that point to the same location in memory.
In other words, x and are two different names that reference the same memory.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
53
Question 61: How do I think more like a programmer?
Answer 61: Imagine you have a class of students. Each student has his or her own
grades. Find the average grade of each student.
1. Draw a picture, and label it clearly. Many times, the picture can be
a simplified version of the real situation.
Mary Louisa 2. Try an approach to the code based on simplicity and
Grades Grades directness. For example, turn Mary's grades into an
98 99
89 91
array, add the grades, divide by the total number of grades
85 86 and print as the average.
3. If you have many grades for each student, finding the sum by adding entries
together is not practical. Imagine, for example, adding 50 grades for one person.
Such a long addition is better done with a foreach loop. So add foreach loops.
Mary Louisa
Additional grades for each student shown as Grades Grades
98 99
ellipses 89 91
85 86
... ...
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
54
4. If there are many students, it's not practical to go through the process of
finding each average, for each student, manually. But we can think of a class
of students programatically as an "array of arrays".
....
Mary Louisa
Grades Grades ....
98 99
89 91
85 86 ....
Additional grades for each student shown as ... ...
ellipses
Additional students with their
grades are indicated by these
ellipses
55
Question 62: Placing too many lines of code inside Main() leads to code that can
be difficult to read. How can this be addressed?
Answer 62: C# allows creating methods. Methods are usually created to perform
a specific task, and allow breaking a huge amount of code into small, understanble
pieces.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
4. "double" is the
1. "static" means method 2. "void" means this method
data type of the
can be called directly does not send a value back 3. PrintIncreasedValue
is the name parameter
by typing its name. to the calling code
5. x is the parameter
4.
x exists in this method
as a local variable.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Check point 20: Create a program with a method. The purpose of the method is 56
to accept a decimal data type, and print it increased by 10%. Apply currency
formatting. You can make a few modificantions to the code in question 62.
Question 63: How can a method return a value to the calling code?
Answer 63: The return keyword can be used to send a value back to the calling
code.
Send in x. This means send 45 along the numbered arrows 1.,2. , 3. The return
keyword sends back 49.5.
1.
2.
3.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
57
Check point 20 sample solution: (Code changes in red boxes)
58
After rate and principle are declared and set, they are passed into the body of
GetInterest as shown. Follow the arrows.
The names "rate" and "principle" are the variables. They are passed into the method
as the arguments. They go into the body of the method through the parameters.
variable variable
argument
argument
parameter
parameter
Check point 21: Create a program with a method that accepts two values, and
returns the larger of the two.
1. Call the method Compare.
2. Make the parameters of type double.
3. Use the ternary operator to compare the values inside the body of method.
4. Return the larger of the two values.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Question 65: Values of type double, integer, decimal and so on can be passed into
a method. Are the values passed as references to the same memory location, or as
copies of the data?
Answer 65: Simple types like the decimal type are passed by value. This means a
copy of the data is sent into the body of a method. The original variable is not
affected after the method call completes.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
60
Notice that it's okay to place method calls directly in strings.
Question 66: How can a method we've written be used with a program construct
like an if/else?
Answer 66: To create a method that works with program flow structures, the
method could return a "bool". We can check whether a number is even, or not.
Below are numbered arrow diagrams to show how this code runs. Please follow
the arrows very carefully.
3.
1.
3.
1.
4.
4.
2.
2.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
61
Question 67: Sending an array to a method could take a lon gtime if the array
were big. How are arrays passed to methods?
Answer 67: Arrays are reference type variable, so a reference to the array is passed
and no copy of the data is sent. This means changes to an array inside a method
are visible in the calling code.
Before ChangeArray
is called
1.
Changes made through arr are visible 3.
here through array.
2.
Inside the method, arr points to the same memory as
array.
array 1
2
arr
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
62
Question 68: How can a method operate on a variable number of values?
Answer 68: The params keyword can be used to create methods that operate
equally well whether 5 inputs or 25 inputs go on.
The number of arguments varies. The method "Add" is more flexible because of
this feature.
Check point 22: Can you create a program with a method that can multiply a
variable number of values? In other words:
1) Create a method called Mutiply
2) Make it return a double
3) Make it work so that it works whether you write Multiply(1,2) or
Multiply(1,2,4,5).
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
63
Check point 22 sample solution: (Important bits of code in red boxes)
1. Set product=1, not 0 at first. If you want the product of 2,4,5, you can't multiply
by 0 because the product would then always be zero.
To keep multiplying and storing back to the product, use "*=". This is the operator
used in this solution.
In other words, at each stage product stores the new, updated value.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
64
Question 69: How can a method set or return multiple values, and why is this
useful?
Answer 69: Methods can use the "out" keyword to and the return keyword. The
out keyword allows setting a value that then is accessible inside the calling code.
Before sorting
After sorting
Check point 23: Extend the code in question 69 to also return the minimum value
of an array.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
65
Check point 23 sample solution:(Important bits of code in red boxes.)
Before sorting
After sorting
Question 70: What is a useful method that uses the "out" keyword already defined
in C#?
Answer 70: The double.TryParse(..) method is one that takes a string, and returns
a "bool", as well as a value that is the result of a successful conversion to numerical
form.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
66
y=10
x=5
temp=x y=temp means
means y is now 5
temp=5
x=y means
x is now 10
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
67
Question 72: The world is made of many different kinds of objects. How can a
simple template for making objects be made in C#?
Answer 72: C# is objected oriented. In C#, a "class" is a template that allows
constructing objects. A particular object is called an "instance". Variables that
describe instances are called "instance variables".
height=65 height=60 height=55
name="Mary" name="Jenny" name="Suza"
2,5,8
1,3
4, 6
7,9
data type 68
"private" means name of instance variable
of variable
this variable is instance variables are also called "fields"
accessible only in
this class.
data type
same as
class name
1.
3.
4.
Mary after:
69
Check point 24:
Below are pictures of rectangles. Turn the pictures you see into C# code, just as
in the previous example.
1. Decide on the name of the class
2. Decide on the instance variables
3. Create a parametrized constructor
4. Inside Main, create instances of the class you've created
method call
name of instance
The method "Speak" is public. This means this method can be called in code in
other classes. The instance variables are private, so they can be accessed only in
Person. Fields are usually private so that other code can't just change them.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
70
Check point 24 sample solution:
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
4. When you step through the program, you should see the Locals window. This
window shows you the variables, and their values.
name of class
also think of it
as the "type"
name of instance
code window
locals window
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
71
Question 74: What is member access, and how does IntelliSense work with
programmer defined classes?
Answer 74: Create a simple class. As you type, features of the class should become
visible in IntelliSense.
1. 2. 1. 2.
Available, programmer
defined members
72
Check point 25 sample solution:
1, 3
4,6
7,9
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
73
Question 75: How can we create member methods that operate on input ?
Answer 75: Add parameters to the methods. Then pass values in to be processed
inside the methods.
Notice this code has no visible constructor. One, however, does exist, but the call
to it is not explicit here.
Either run the code above with the
debugger so you can be 100% clear on 3 Runs 20
the way it executes, or on the right is times
an approximate flow analysis. Follow
the numbers adjacent to the boxes 4
Check point 26: Add a method to this class that can print a vertical line of a
specified length. The code you have to write is very similar to the code that
defines DrawSeparator(..).
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
74
Check point 26 sample solution: (Code addition in red boxes.)
Below is the order of execution of this code. Follow the numbers carefully.
3 Runs 10
times
4
7 Runs 10
times
1
2, 5
6, 8
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
75
Question 76: Does Visual Studio have a feature for summarizing the features of
a class?
Answer 75: Visual Studio 2015 has a class desinger, which can be accessed as
shown below. This feature provides a lot of summary information on a class.
3 2
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
76
Check point 27 sample solution:
Compare the header of the loop to the window right above it. The condition that
controls the execution of the loop is in the red box.
Question 77: Imagine we make a Canvas class, and give it a name. Then later we
decide we want to change and display the title. How can we do this?
Answer 77: Properties are features that objects possess. They are not behaviors.
For example, "Height" is a property. You don't do "Height". It's not an action.
Properties allow controlled access to backing fields.
This is a field. We have a property below.
So now you can think of this as the
"backing field"
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
1,3
4,6
7,9
10,12
Check point 28: Create a class called "Person". Add a backing field called "name".
Add a property called "Name". Be sure you then read the name inside Main().
Do not code a "set" block.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Question 78: If we have an "Age" property, a user could attempt to set its value
to something like -10. How can we prevent such errors?
Answer 78: We can add logic to properties to ensure that the backing field is
given only sensible values.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
79
This is how the age field is read. Notice it's accessible all the way down in the call
to WriteLine(..) because it's all within the same class.
Check point 29: Modify the example in question 78 to answer each question:
1) What is the default value of age?
2) What's the value set to "age" when a user tries to set it to 454?
Question 79: How can a program with two classes be written?
Answer 79: We can add two classes to one file. We can expose the members of a
class by making them public.
81
Question 80: Can properties be coded in some other way?
Answer 80: C# has auto-implemented properties. Use these when the get and set
blocks do not require additional logic.
Automatically implemented
property is set directly inside the
constructor.
Question 81: Remembering the order of parameters when there are several could 82
be a little hard. Is there an easier way?
Answer 81: C# has named arguments. Named arguments allow sending values
in any order.
The named argument is in 2nd position, but it's still sent to the correct parameter.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
83
Question 82: How can we keep track of the number of instances of a class?
Answer 82: C# has static fields. These are fields that operate on the class level,
so they can be used to store information about the number of instances of a class.
static property
1,3
4,6
7,9
name of class name of property 10,12
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
84
Check point 30: What happens when an attempt is made to access a static field
through an object? Make a modification to the code in question 82 to find out.
Question 83: Since there are static fields and static properties, are there also
static methods, and even static classes?
Answer 83: C# has both static methods and static classes. One useful example of
this is the Math class.
Math class is stored in System.
"Math" is much more conceptual than something like a "table". You can easily
imagine a table, but "Math" cannot be imagined so easily as a physical object. In
other words, "Math" does not need to have fields that have to be set. A table on
the other hand needs fields like color, number of legs and so on.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
85
Check point 30 sample solution:
"per1" is the name of a person object. Notice that IntelliSense does not show the
"Counter" property as an option to call on this object.
86
The code in the previous question is a little more advanced. Please be sure to
type and run it with the debugger.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
Question 85: How can a programmer defined data type be used as a parameter
in a method call?
Answer 85: We can imagine a book class. Books are stored in book shops.
It is crucial to building real comprehension that you type this code, and run it with
the debugger, step by step. As code grows, understanding can grow also, but only
if correct learning methods are embraced. Rushing does not work.
Do these steps only once. Press this arrow repeatedly to step through the code.
1. 2. 3.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
87
Below is an approximate flow analysis of this code. Be sure to follow the
numbers next to the boxes very carefully. Notation like 1,3 means that line is
hit twice.
2,5
15
runs
2 times
1,3
4,6
7
8,10
11,13
14,16
Question 85: Behind the scenes, computers love only numbers. People love names.
How can the two be reconciled?
Answer 85: C# has enumerations, which are lists of named constants. There are
prebuilt enumerations like ConsoleColor.
named constant
name constant
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
88
To make an enumeration, think of a list of numbers that can also be named
meaningfully. A common example is the days of the week.
Scrollbar is resizable
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
(question 86 continued)
To turn the objects described earlier into code, create a base, or parent, class
called InterfaceObject, and then proceed as outlined below. It makes sense for
Scrollbar and TextBox to inherit from InterfaceObject because each "IS-A" kind
of interface object. For example, you see them both and you can interact with
both of them.
This code cannot run. There is no entry point in the form of "Main()". We
continue on the next page.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
90
Now Main() is present, so the program can be run.
The locals window confirms that the box and bar objects have inherited the
resizable field.
If not for inheritance, there would be more code because we'd have to declare
the same field in multiple places. Now imagine a real application with dozens of
fields, methods and properties. Clearly, any ability to centralize code immediately
leads to less code. Next is a careful analysis of the execution of this code.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
91
On the right is an analysis
the order of execution of
this code. It's important to
observe that the code begins
3,8
inside Main(), and climbs all
the way up to the constructor for
InterfaceObject.
7,9
2,4
1,5
6,10
1
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
92
Click the steps on the right to view the
class designer.
1
3 2
Arrow indicates
inheritance
93
Question 87: Fields are inherited. What happens to properties?
Answer 87: Properties are also inherited. Class diagram shows
how TextBox inherits
from InterfaceObject
Now the box object consists of a field, and a property. This property is public,
so it can be called inside Main.
Check point 32: Take the example from question 87 above, and add one class.
Make the class inherit from InterfaceObject. Be sure inside Main() you can
call the public property from the base class. Confirm inside the locals window
that this new object has both the private "resizable" field, and public property.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
94
Check point 32 sample solution: (Code additions in red boxes.)
The locals window confirms that now both box, and bar have inherited the
resizable field, and the Resizable property.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
Question 88: We can centralize fields and properties. Can we extend this same 95
logic to methods?
Answer 88: C# has virtual methods. The purpose of these methods is to centralize
logic that is common to multiple classes. It is absolutely necessary to type this
code, and run it with the debugger. This will illustrate the order of execution with
complete precision.
The most important observation here is that the GetDesc() is virtual. This means
it stores code that will be used by child classes. If this were not so, this code would
have to be recreated in multiple classes. If you had several hundred products it
would be a huge waste of energy to type "Price:{price:C}" 500 times, when it can
be done once inside the base class. Imagine further that the base class stored 10
common fields, and they had to be formatted. Then clearly it's easier to type
base.GetDesc() then to write code for 10 different fields inside each of 500 classes.
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
96
On the right is an
approximate flow
analysis starting from
the call to GetDesc().
Please follow the numbers
very carefully.
3
"virtual" keyword. Place
default code inside this
method. Default means it's
code that can be used by
many child classes equally
well.
2
4
"override" keyword means
this method refines or adds
unique code. Here, uniqe
means the addition of code
to display the page count.
1,5
1 2
Check point 33: You're going to extend the code in question 88 above.
1) Add a country of origin field
2) Decide where to place this field
3) Add code to display the value of this field
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
97
Check point 33 sample solution: (Code changes in red boxes.)
Inherited field
Specific to book class
Inherited field
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
99
When "prod" is a book, GetDesc() from the book class is called. This is called
"run time polymorphism". In other words, "prod" has now the form of a "book",
and therefore, the correct method from the Book class is called.
When "prod" is a bag, GetDesc() from the bag class is called. This is called
"run time polymorphism". In other words, "prod" has now the form of a "bag",
and therefore, the correct method from the Bag class is called.
1
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
100
When prod is a book, the code
executes as shown. Please follow
the numbers next to the boxes
very carefully.
3 5
2,6
now "prod" stands for a book,
so the correct, derived version
of GetDesc() is called. This is
the second example of polymorphism.
Check point 34: Can you draw an execution diagram to illustrate the order of
execution when prod becomes a "bag" inside the foreach loop?
M at h Com poser 1. 1. 5
ht t p: / / www. m at hcom poser . com
101
Check point 34 sample solution:
2,6
https://www.udemy.com/beginnerscsharp2015/?couponCode=amz
Please visit the link below to see the full, 19 hour curriculum.
https://www.udemy.com/beginnerscsharp2015/?couponCode=amz