Presentation is loading. Please wait.

Presentation is loading. Please wait.

BIM313 – Advanced Programming Techniques C# Basics 1.

Similar presentations


Presentation on theme: "BIM313 – Advanced Programming Techniques C# Basics 1."— Presentation transcript:

1 BIM313 – Advanced Programming Techniques C# Basics 1

2 Contents Variables and Expressions – Comments – Variables – Expressions – Operators – Namespaces Flow Control – if, switch – while, do-while, for, foreach – Binary operators 2

3 Basic C# Syntax White spaces (space, carriage return, tab) are ignored by the C# compiler Statements are terminated with a semicolon (;) C# code is case-sensitive C# is a block-structured language and blocks are delimited with curly brackets (‘{’ and ‘}’) Please indent your code so that your code becomes more readable Write comments while writing the codes 3

4 Comments Type I /* Single line comment */ /* Multi- Line Comment */ Type II // Another single line comment a = 0; // Initialize the count Type III /// Special comments used for documentation 4

5 Variables Think variables as boxes to store data in them Variables have types, names, and values int num = 5; Here, int is the type, num is the name, and 5 is the value of the variable All variables should be declared before using them 5

6 Simple Types Simple types include types such as numbers and Boolean (true or false) values There are several types to represent numbers, because different amount of bytes are required for each type 6

7 Integer Types TypeAlias forAllowed Values# of bytes sbyteSystem.SByteInteger between –128 and 1271 byteSystem.ByteInteger between 0 and 2551 shortSystem.Int16Integer between –32768 to 327672 ushortSystem.UInt16Integer between 0 and 655352 intSystem.Int32 Integer between –2,147,483,648 and 2,147,483,647 4 uintSystem.UInt32Integer between 0 and 4,294,967,2954 longSystem.Int64 Integer between –9223372036854775808 and 9223372036854775807 8 ulongSystem.UInt64 Integer between 0 and 18446744073709551615 8 7 u: unsigneds: signed

8 Floating-Point Value Types TypeAlias forRange# of bytes floatSystem.Single4 doubleSystem.Double8 decimalSystem.Decimal16 8

9 Precisions TypePrecision float7-8 digits double15-16 digits decimal28 digits 9 The decimal value type is generally used in currencies which require more precision!

10 Other Simple Types TypeAlias forAllowed Values charSystem.Char Single Unicode character, stored as an integer between 0 and 65535 boolSystem.Booleantrue or false stringSystem.StringA sequence of characters 10 Note that char type is stored in 2 bytes and it is Unicode!

11 Variable Declaration, Assignment, and Printing Example static void Main(string[] args) { int myInteger; string myString; myInteger = 17; myString = "\"myInteger\" is"; Console.WriteLine("{0} {1}.", myString, myInteger); } 11 Two variables are declared here Values are assigned to the variables Variables are displayed on the screen. "myInteger" is 17.

12 Printing Variable Values Use Console.Write() or Console.WriteLine() methods to display variable values on the screen Console.WriteLine() method adds a new line at the end of the line The methods have several faces to print several types; use the most suitable one 12

13 Some Console.WriteLine() Faces 13

14 Printing an int on the screen int x = 17, y = 25; Console.WriteLine(x); Console.WriteLine(x.ToString()); Console.Write(“x = ”); Console.WriteLine(x); Console.WriteLine(“x = ” + x); Console.WriteLine(“x = ” + x.ToString()); Console.WriteLine(“x = {0}, y = {1}.”, x, y); 14 17 x = 17 x = 17, y = 25.

15 Variable Naming The first character must be either a letter, or an underscore character (_) Subsequent characters may be letters, underscore character, or numbers. Reserved words can’t be used as variable names – If you want a reserved word as variable name, you can put an at character (@) at the beginning 15

16 Example: Valid Variable Names myBigVar VAR1 _test i myVariable MyVariable MYVARIABLE 16

17 Example: Invalid Variable Names a+b 99bottles namespace double my-result 17

18 Keywords abstractconstexternintoutshorttypeof ascontinuefalseinterfaceoverridesizeofuint basedecimalfinallyinternalparamsstackalloculong booldefaultfixedisprivatestaticunchecked breakdelegatefloatlockprotectedstringunsafe bytedoforlongpublicstructushort casedoubleforeachnamespacereadonlyswitchusing catchelsegotonewrefthisvirtual charenumifnullreturnthrowvoid checkedeventimplicitobjectsbytetruevolatile classexplicitinoperatorsealedtrywhile 18

19 C# Contextual Keywords addascendingasyncawaitbydescendingdynamic equalsfromgetglobalgroupininto joinletonorderbypartialremoveselect setvaluevarwhereyield 19 Contextual keyword are used in certain language constructs. They can’t be used as identifier in those constructs. Otherwise, they can be used as identifiers.

20 Variable Naming Conventions Hungarian Notation Camel Case Pascal Case 20

21 Hungarian Notation Place a lowercase prefix which shows the type of the variable – nAge – iAge – fDelimeter – btnClick – txtName 21

22 Camel Case Begin first word with lowercase, others with uppercase – age – firstName – lastName – birthDay 22

23 Pascal Case Start all words with uppercase letters – Age – FirstName – LastName – WinterOfDiscontent 23

24 Escape Sequences Escape SequenceCharacter ProducedUnicode Value \’Single quotation mark0x0027 \”Double quotation mark0x0022 \\Backslash0x005C \0Null0x0000 \aAlert (causes a beep)0x0007 \bBackspace0x0008 \fForm feed0x000C \nNew line0x000A \rCarriage return0x000D \tHorizontal tab0x0009 \vVertical tab0x000B 24

25 More About Strings… You can use Unicode values after \u – “Karli\’s string” – “Karli\u0027s string” If you place the @ character before a string, all escape sequences are ignored. – “C:\\inetpub\\wwwroot\\” – @“C:\inetpub\wwwroot\” – “A short list:\nitem 1\nitem 2” – @“A short list: item 1 item 2” 25

26 Variable Declaration and Assignment int age; age = 25; int age = 25; int xSize, ySize; int xSize = 4, ySize = 5; int xSize, ySize = 5; 26

27 Operators Addition, subtraction, etc. are made using operators Three types of operators: – Unary – Act on single operand – Binary – Act on two operands – Tertiary – Act on three operands 27

28 Mathematical Operators OperatorCategoryExample +Binaryvar1 = var2 + var3; –Binaryvar1 = var2 – var3; *Binaryvar1 = var2 * var3; /Binaryvar1 = var2 / var3; %Binaryvar1 = var2 % var3; +Unaryvar1 = +var2; –Unaryvar1 = –var2; 28 % : Remainder operator Example: 8 % 3 gives 2.

29 Increment and Decrement Operators OperatorCategoryExample ++ Unary var1 = ++var2; -- Unary var1 = --var2; ++ Unary var1 = var2++; -- Unary var1 = var2--; 29 Increment first, assign next Assign first, increment next

30 Exercise int var1, var2 = 5, var3 = 6; var1 = var2++ * --var3; Console.WriteLine("var1={0}, var2={1}, var3={2}", var1, var2, var3); 30 How?

31 Printing Variable Values int var1 = 3, var2 = 5; Console.WriteLine("var1 = {0}, var2 = {1}", var1, var2); 31 var1 = 3, var2 = 5

32 Printing Variable Values int var1 = 3, var2 = 5; Console.WriteLine("{0}{1}{0}{1}{1}", var1, var2); 32 35355

33 Reading Strings string userName; Console.Write("Your name: "); userName = Console.ReadLine(); Console.WriteLine("Welcome {0}!", userName); 33 Your name: Muzaffer Welcome Muzaffer!

34 Reading Integers int age; Console.WriteLine("Your age: "); age = int.Parse(Console.ReadLine()); Console.WriteLine("Your age is {0}.", age); 34 Equivalent code: Convert.ToInt32(Console.ReadLine());

35 Reading Doubles double w; Console.WriteLine("Your weight (in kg.): "); w = double.Parse(Console.ReadLine()); Console.WriteLine("You weigh {0} kg.", w); 35 Equivalent code: Convert.ToDouble(Console.ReadLine());

36 Assignment Operators OperatorExampleEquivalent =var1 = var2; +=var1 += var2;var1 = var1 + var2; -=var1 -= var2;var1 = var1 – var2; *=var1 *= var2;var1 = var1 * var2; /=var1 /= var2;var1 = var1 / var2; %=var1 %= var2;var1 = var1 % var2; 36

37 Operator Precedence PrecedenceOperators Highest++, -- (used as prefixes), +, - (unary) *, /, % +, - =, *=, /=, %=, +=, -= Lowest++, -- (used as suffixes) 37

38 Namespaces.NET way of providing containers – Header files in C and C++ – Packages in Java.NET classes are grouped in namespaces – Sin, Cos, Atan, Acos, Pi, Sqrt, etc. in Math namespace – Int32, Double, etc. in System namespace – Windows Forms classes in System.Windows.Forms – Registry operations in Microsoft namespace You also can write your programs or DLLs in a separate namespace, e.g. using your company name 38

39 Flow Control Branching (if, switch, ternary operator) Looping (for, while, do-while, foreach) 39

40 Comparison Operators OperatorMeaning ==equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal to 40

41 Boolean Variables A Boolean variable may take values true or false – bool isWhite = true; – isWhite = false; Comparison results can be stored in Boolean variables – bool isLong = (height > 195); – bool isWhite = (color == Color.White); 41

42 Fundamental Logical Operators OperatorNameExample &&AND(a > 0) && (a < 10) ||OR(a = 10) !NOT!(a < 100) 42

43 The ‘if’ Statement int height; Console.Write("Enter your height (in cm.) "); height = int.Parse(Console.ReadLine()); if (height > 190) Console.WriteLine("You are a tall person!"); else Console.WriteLine("Your height is normal!"); 43

44 if Statement if (expression) ; if (expression) { ; } 44

45 if..else if (expression) ; else ; If there are more statements, use curly brackets. 45

46 Some Notes on ‘if’ Parentheses are required, they can’t be omitted Curly braces (‘{’ and ‘}’)should be used if there are more than one statements: if (test) { statement1; statement2; } else part can be omitted if statements can be nested 46

47 Example: Finding the smallest of 3 integers int a, b, c, min; Console.WriteLine("Enter 3 integers:"); Console.Write("a = "); a = int.Parse(Console.ReadLine()); Console.Write("b = "); b = int.Parse(Console.ReadLine()); Console.Write("c = "); c = int.Parse(Console.ReadLine()); if (a < b) { if (a < c) min = a; else min = c; } else { if (b < c) min = b; else min = c; } Console.WriteLine("The smallest one is {0}.", min); 47

48 Checking Conditions if (var1 == 1) { // Do something. } else { if (var1 == 2) { // Do something else. } else { if (var1 == 3 || var1 == 4) { // Do something else. } else { // Do something else. } if (var1 == 1) { // Do something. } else if (var1 == 2) { // Do something else. } else if (var1 == 3 || var1 == 4) { // Do something else. } else { // Do something else. } 48

49 Common Mistakes if (var1 = 1) {…} if (var1 == 1 || 2) {…} 49

50 The ‘switch’ Statement switch ( ) { case : == > break; case : == > break;... case : == > break; default: != comparisonVals> break; } 50

51 Example 1 switch (var1) { case 1: // Do something. break; case 2: // Do something else. break; case 3: case 4: // Do something else. break; default: // Do something else. break; } 51

52 Example 2 switch (option) { case 1: Console.WriteLine(“You select 1”); break; case 2: Console.WriteLine(“You select 2”); break; case 3: Console.WriteLine(“You select 3”); break; default: Console.WriteLine(“Please select an integer between 1 and 3.”); break; } 52

53 switch Example switch (strProfession) { case "teacher": MessageBox.Show("You educate our young"); break; case "programmer": MessageBox.Show("You are most likely a geek"); break; case "accountant": MessageBox.Show("You are a bean counter"); break; default: MessageBox.Show("Profession not found in switch statement"); break; } 53 In C, only integer values can be used as the expression but in C#, strings can be used too. Don’t forget to use breaks!

54 Example 3 switch (strAnimal) { case “bird”: Console.WriteLine(“It has 2 legs.”); break; case “horse”: case “dog”: case “cat”: Console.WriteLine(“It has 4 legs.”); break; case “centipede”: Console.WriteLine(“It has 40 legs.”); break; case “snake”: Console.WriteLine(“It has no legs.”); break; default: Console.WriteLine(“I don’t know that animal!”); break; } 54

55 The Ternary Operator ? : Tertiary operator because it acts on 3 operands (remember unary and binary operators acting on 1 and 2 operands resp.) Example: – if (a < b) min = a; else min = b; – min = (a < b) ? a : b; 55

56 Looping 56

57 for Loop for (initializers; check_condition; modifying_expressions) { } Example: for (i = 0; i < 10; i++) { Console.WriteLine("i = " + i.ToString()); } 57

58 while Loop while (expression) { } 58

59 do-while Loop do { } while (expression); 59

60 foreach Loop foreach ( in ) { } 60

61 Displaying Months using for Loop string[] months = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for (int i = 0; i < months.Length; i++) { MessageBox.Show(months[i]); } 61

62 Displaying Months using foreach string[] months = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; foreach (string month in months) { MessageBox.Show(month); } 62

63 Exercise Display first ten prime numbers. 63

64 Interrupting Loops break – ends the loop immediately continue – ends the current loop cycle return – jumps out of the function goto – jumps to the specified location (don’t use) 64

65 Infinite Loops while (true) { … } 65

66 Example int num; while (true) { Console.Write(“Enter a number between 1 and 100: ”); num = Convert.ToInt32(Console.ReadLine()); if (num >= 1 && num <= 100) break; else { Console.WriteLine(“It should be between 1 and 100.”); Console.WriteLine(“Please try again!\n”); } 66

67 Bitwise Operators & (Bitwise AND) | (Bitwise OR) ~ (Bitwise NOT) ^ (Bitwise XOR) 67

68 Examples 0110 & 0101 = 0100 (1&1=1, otherwise 0) 0110 | 0101 = 0111 (0|0=0, otherwise 1) 0110 ^ 0101 = 0011 (same  0, different  1) ~0110 = 1001 (0  1, 1  0) 68

69 Examples option = Location.Left | Location.Bottom; if (option & Location.Left != 0) MessageBox.Show(“Indented to left.”); if (option & Location.Bottom != 0) MessageBox.Show(“Indented to right.”); 69

70 Shift Operators >> (Shift right) << (Shift left) >>= <<= 70

71 Examples int a = 16; int b = a >> 2; // b becomes 4 int c = a << 4; // c becomes 256 a >>= 2; // a becomes 4 a <<= 4; // a becomes 64 71


Download ppt "BIM313 – Advanced Programming Techniques C# Basics 1."

Similar presentations


Ads by Google