Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
`Lesson 02: Control Statements (If, For, Do etc) The If Statement: o Edit your source code file as follows, build and execute. using System; class test { public static void Main() { int x = 2; if (x > 1) Console.WriteLine("yes"); Console.ReadLine(); } } ie if x is bigger than 1 which of course it is since it's 2, do the following. o Modify the code as follows: int x = 2 ; if ( x == 2) Console.WriteLine("yes"); Note that when we are assigning we use one equal sign but when we are testing (comparing) we use two equal signs. If we wish more than one thing to be performed after an if then we must enclose them in braces as follows (This is generally true for a group of C# statements – enclose them in braces.) int x = 2 ; if (x == 2) { Console.WriteLine("yes"); Console.WriteLine("of course"); Enclosing braces. These ensure that all of the code contained within these braces is executed if the condition (x = 2)is true – which it is. } The opening and closing braces delimit a" block". D:\478176622.doc Type if and then immediately TAB TAB to the snippet - with enclosing braces etc. 1 Else o Try this: using System; class test { public static void Main() { int x = 2 Shortcut: type if and then tab, tab else and then tab, tab. ; if (x == 2) Console.WriteLine("yes"); else Console.WriteLine("no") ; Console.ReadLine(); } } o Change if (x == 2) to if (x == 1) and the else should be executed. ; More than one if statement has the effect of AND { int x = 2 if (x == 2) if (x > 1) For AND, both these conditions must be satisfied. ; Using else if has the effect of (exclusive) OR: public static void Main() { int x = 2; if (x > 2) Console.WriteLine("x>2"); else if (x > 1) Console.WriteLine("x>1"); else if (x > 0) Console.WriteLine("x>0"); Console.ReadLine(); } else if is like an if. D:\478176622.doc Note also that if one else if (or an if)is encountered which is true, all other else if‘s are then not even considered. 2 Problems in class. 1. We have previously written a program to swap two numbers. int i = 3; int j = 2; o Modify that code to swap the numbers if the first number is bigger than the second number – which of course it is in the above case We want the smaller number printed first. ie if we originally had instead: int i = 2; int j = 3; then your code should not swap them. D:\478176622.doc 3 Logical Operators Page 99-100 C# 21 days. OR: public class test { static void Main() { int i = 2; if (i == 1 || i == 2) Console.WriteLine("yes"); Console.ReadLine(); or i can be either 1 or 2. } } AND: using System; public class test { static void Main() { int i = 1, j = 2; if (i == 1 && j == 2) Console.WriteLine("yes"); Console.ReadLine(); and i must be 1 and j must be 2. } } D:\478176622.doc 4 The Switch (Looks good but perhaps only good for “a menu system”.C# in 21 Days page 123 break; is compulsory …is an alternative to using else if. using System; class test { public static void Main() { int x = 5 ; Type switch and then immediately TAB TAB to get the snippet - with enclosing braces etc. switch (x) { case 4: Console.WriteLine("four") break; case 5: Console.WriteLine("five") break; case 6: Console.WriteLine("six") break; } Console.ReadLine(); ; at the end of every case block else it will “fall through”. Thus if one case is found to be true, any following case statements are not considered. (This behaviour is the same as else if.) ; ; } } o Try this with i = 4 and then i = 5. case 4: case 5: Console.WriteLine("four/five") break; case 4: case 5: break ; ; catch both 4 or 5. will If no case expression matches the switch value, then control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch. default: Console.WriteLine("x doesnt match any value"); break; Note when using a switch eg switch (x) we can only test one condition c.f. the if which can test more than one eg see page 7 : if (i == 1 && j == 2) This is something of a disadvantage when using switch. D:\478176622.doc 5 True and False Console.WriteLine(1==2) ; Casting of bool Casting to and from bool is not permitted 1. From int to bool: int i = 1 b = (bool) i; is not allowed. (It wont even compile) Nor is 2. From bool to int: bool b = true; int i = (int) b; true has value of 1 and false has value of 0. We can use however int i = Convert.ToInt32(b); Console.WriteLine(i); The for Loop C# in 21 Days page (bottom of) p134 using System; class test { public static void Main() { int i ; for (i=0; i<4; i++) Console.WriteLine(i) ; Console.ReadLine() } The int declaration could alternatively be placed here. for (int i=0;i<4;i++) Note that in this case, the i will only be “known” inside the loop. ; } We could also have: for (i=4; i>=0 ; i-- ) for (i=0; i<=4 ; i+=2) counts backwards increments by 2 Type for and then immediately TAB TAB to get the snippet with enclosing braces etc. To execute a series of statements in a for loop, use enclosing braces (as we did for the if). for (i=0;i<4;i++) { Console.WriteLine(i) ; Console.WriteLine("looping") } Console.ReadLine() D:\478176622.doc ; ; 6 Ex 2. Write separate programs that will produce output like this below – using a nested loop ie a loop inside a loop. Hint 1: To print 4 numbers across using a space in between use Console.Write("{0} ", i); space Hint 2: Use a loop inside a loop. and this.. Hint : The inside loop counter “upper limit” will depend on the outer loop. and this.. and this.. continue using System; class test { public static void Main() { int i ; for (i=0; i<4; i++) { if(i==2) continue ; Console.WriteLine(i) ; } Console.ReadLine() ; } } continue causes control to pass to the end of this loop ignoring statement/s in between - if there are any - there is only one here - and then back to the next i which will be 3. break (which we have previously met with switch) causes termination of the loop. public static void Main() { int i for (i=0; i<4; i++) { if(i==2) break Console.WriteLine(i) } Console.ReadLine() D:\478176622.doc ; ; ; ; 7 while C# in 21 Days page 128 static void Main() { int i = 0; while (i < 4) { Console.WriteLine(i); i++; } Console.ReadLine(); } i < 4 evaluates to either True or False. If False ie if i = 5, it will stop. A while loop can also be terminated with a break, goto or a return. Type while and then immediately TAB TAB to the snippet - with enclosing braces etc. do while Type do and then immediately TAB TAB to the snippet - with enclosing braces etc. static void Main() { int i = 0; do { Console.WriteLine(i); i++; } while (i < 4); Console.ReadLine(); } The while and the do….while are almost identical. The only difference is that the do while evaluates the condition at the end ie it always goes through at least once and doesn’t find out if it shouldn’t have too late. goto transfers control unconditionally. It is usually used with a label. public static void Main() { int i; for (i = 0; i < 4; i++) { if (i == 2) goto mylabel ; Console.WriteLine(i) mylabel: } Console.ReadLine() } ; A label is used ; with a colon. ; Further reference: The Microsoft Help online. http://msdn.microsoft.com/en-us/library/370s1zax.aspx (Consult this reference generally.) D:\478176622.doc 8 When do we use a for loop and when do we use a while? When we know in advance how many loops are required, use a for but when we are waiting for something to happen use a while. We have previously seen that a for loops for a pre-determined number of times whereas the while is used when we don’t know when the condition to stop will be encountered. Run-Time is when the program is actually running. eg Design-Time is when you are actually writing the code. using System; public class test { static void Main() { Empty string. string st = ""; while (st != "s") { st = Console.ReadLine(); Console.WriteLine(st); } } Not equal. The program loops and echoes the letter to the screen until an “s” is pressed. (And then Enter is pressed.) } The Conditional Operator (Looks good but not actually used much.) using System; public class test { static void Main() { int i = 1 int j If the condition is true, which it is in this case, the first alternative (the 3) is assigned to j. If false, the 4 would be assigned to j. ; ; j = (i < 2) ? 3 : 4 ; Console.WriteLine(j); Console.ReadLine() ; } } Read to the end of C# in 21 Days Sams Day 4. D:\478176622.doc 9 Debugging o o Continue to press F11. You will see the program looping around the for loop. Click Build, Start Debug, Step Into (or press F11). o If this window is not visible, choose Debug Windows, Locals o Note the values of the variables in the Locals window. o By holding the mouse steady on a variable, the value will appear. o To set a break point, click in the margin of the line. This is only possible whilst debugging! To remove it click it again to toggle it off. If the Run button is pressed, the program will run and stop at this line. D:\478176622.doc 10 Binary Numbers How many ice-creams can you order with one hand? 5 right ? wrong 32! Consider that a finger (and thumb) can be in 2 states raised or not-raised and that we start with the thumb as 1 and multiply by 2 for the other fingers as shown If the thumb and 1st finger were raised this could represent 3 (1+2) as shown below. If all fingers were raised, this would represent 31 (1+2+4+8+16). If no fingers were raised, this would of course represent 0- this would indeed have to be a valid ice-cream order!. Therefore the total no. of orders possible is 32. We could indicate 5 as follows We could further represent a finger raised by 1 and a finger not-raised by 0. 5 would then be represented by: 00101 - this is called binary (actually the leading zeros can be omitted.) The respective 1’s and 0‘s are called bits (8 bits makes one byte) Exercise 101 is the binary representation of ……… 1101 is the binary representation of ……… 1000 is the binary representation of ……… 7 12 23 is the decimal representation of …………… is the decimal representation of …………… is the decimal representation of …………… D:\478176622.doc 11 Hexadecimal Whereas decimal numbers are to base 10, hexadecimal numbers are to base 16. Numbers in hexadecimal from 1 to 9 are the same – 0 to 9. But numbers from 10 to 15 are given the letters A to F Decimal 1 2 . . 9 10 11 12 13 14 15 Hexadecimal 1 2 . . 9 A B C D E F Hex numbers in C# are preceded with 0x eg 0xAD23F3. o Try this using System; class test { public static void Main() { int h ; int h ; h = 12 ; Console.WriteLine ("{0:X}",h) ; h = 0xC; Console.WriteLine(h) ; Console.ReadLine() } ; } will convert decimal to hex. page 392 To evaluate to 2 digit hex number eg 2A Whereas of course decimals increase by a factor of 10 from right to left, hex placeholders increase by a factor of 16 from right to left. … 256 16 1 So hex 2A can be evaluated: … 256 16 2 1 A i.e. 2 times 16 plus 10 times 1 i.e. decimal 42. Exercise: what is the decimal equivalent of the hex number 22A ? What algorithm would you use to convert a number from decimal to hex e.g. convert decimal 42 to hex. D:\478176622.doc 12 Why use hex? Hexadecimal is a shorthand way of writing binary For example, decimal 42 is the equivalent of the hex 2A. o Write the 2 and the A separately in binary: 2 A 8 4 2 1 8 4 2 1 … … … … … … … … o Now write 42 as binary: 42 128 64 32 16 8 4 2 1 … … … … … … … … They are the same! This is always true – since all of the numbers of the higher hex digit are 16 times those of the lower. Exercise 2 1. Write the code for a switch statement that switches on the variable name. If the name is Robert, print a message that says Hi Bob. If the name is Richard, print a message that says Hi Rich. If the name is Barbara, print a message that says Hi Barb. If the name is Kalee, print a message that says Kalee!. On any other name, print a message that says Hi x, where x is the person's name. 2. Write a program to roll a six-sided die 100 times. Print the number of times each of the sides of the die was rolled. You may wish to use: Random rnd = new Random(); // This only needs to be done once. int n = rnd.Next(1, 7); to generate random numbers between 1 and 6. Page 144 C# in 21 Days D:\478176622.doc 13 3. Write a program that calculates how much money you’ll end up with if you invest an amount of money at a fixed interest rate, compounded yearly. Have the user furnish the initial amount, the number of years, and the yearly interest rate in percent. Some interaction with the program might look like this: Enter initial amount: 3000 Enter number of years: 10 Enter interest rate (percent per year): 5.5 At the end of 10 years, you will have 5124.43 dollars. At the end of the first year you have 3000 + (3000 * 0.055), which is 3165. At the end of the second year you have 3165 + (3165 * 0.055), which is 3339.08. Do this as many times as there are years. A for loop makes the calculation easy. You may alternatively want to use the compound interest formula. A(1+r)n. ie A * Math.Pow(1+r,n). Don’t forget that pow is expecting a Double. Hint: When developing your program which requires keyboard input eg double amt ; ConsoleReadLine(amt); then “hard code” the input temporarily eg amt= 10.00; temporarily until you program works . Then finally reinstate ConsoleReadLine(amt); (When sending course work to me pls also use the “hard-coded” version!) 4. using the formula for the normal curve from the previous chapter, plot the normal curve using values from -3 to 3 with an increment of say 0.5 D:\478176622.doc 14 5. “Plot” these values: Here is the solution for a sine curve! Don’t worry if you can’t understand all of it for the moment! Adapt it to produce your normal curve (see below). o This is a function (not covered yet.) The value val (eg val = 0) is passed to it using System; class SineWaveToConsole { private static string spaces(double val) { string SpaceString = new String(' ', ((int)(val * 10.0)) + 10); return SpaceString; } o This produces a string (not covered [STAThread] yet.) It produces a string of concatenated static void Main(string[] args) spaces eg 5 spaces -> “ “ { for (float i = 0; i < Math.PI * 2.0F; i += 0.3F) { Console.WriteLine("The sine of {0,10:F} = {1,-10:F6}" + spaces(Math.Sin(i)) + "*", i, Math.Sin(i)); } Console.ReadLine(); } The 10 says The - says “right } a “field width justified”. The 6 o This “calls” the spaces function above to produce a series of spaces proportional to the value of Math.Sin(i). D:\478176622.doc of 10. The F says decimal says 6 decimal places. 15 A More Difficult Compound Interest Problem (Optional for FM students) £100 is invested at 10% interest for 1 year. How much will we have at the end of the year? Of course £110. ie 100 * (1 + .10) Lets now say that we get 5% interest every half year. How much will we have at the end of the year? Ans: 100 * (1 + .05) after 6 months and then THIS amount will accrue interest, so in total: 100 * (1 + .05) * (1 + 05) which gives 110.25 which of course is more than the £110. This can be generalized to: 100 * (1 + .10/2) * (1 + .10/2) = 100 * (1 + .10/2) 2. Lets now say that we get 2.5% (1%/4) interest every quarter. How much will we have at the end of the year? Ans: 100 * (1 + .025) after 3 months and then this amount will accrue interest for the next 3 months and then THIS amount will ….. etc. So at the end of the year we will have: 100 * (1 + .025) * (1 +.025) * (1 +.025) * (1 +.025) which gives 110.38 which of course is even more than the £110. This can be generalized to: 100 * (1 + .10/4) * (1 + .10/4) * (1 + .10/4) * (1 + .10/4) = 100 * (1 + .10/4) 4 To further generalize: If we are paid the interest n times per year, the total amount that we will have at the end of the year will be: A = 100 * (1 + .10/n) n Even if you don’t quite understand how we got this formula just use it! Write a program that will give you the total amount at the end of the year for a variable number of intervals. eg for 1 to 10 intervals , the output should be: Here’s the $64,000 question: If we kept dividing up the interval FOREVER ie an infinite number of payoffs, how much will we have Is this possible? Continually compounding interest! For 10 intervals, the end of the year we will have £105.114. D:\478176622.doc 16