Presentation is loading. Please wait.

Presentation is loading. Please wait.

2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.

Similar presentations


Presentation on theme: "2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003."— Presentation transcript:

1 2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

2 Objectives Introduce the core C# language features class Main types
2: Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

3 Class Keyword class used to define new type specify name
2: Basics Class Keyword class used to define new type specify name enclose body in { } Most C# code placed inside a class no global variables allowed no global methods allowed class definition class MyApplication { ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

4 Main Main method is the application entry point
2: Basics Main Main method is the application entry point must be static method of some class any access level such as public or private is allowed Main can perform environment interaction can receive command line arguments as array of strings can return int to indicate success/failure class MyApplication { static void Main() ... } entry point Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

5 Simple types Comprehensive set of simple types available Type
2: Basics Simple types Comprehensive set of simple types available Type Description Special format for literals bool Boolean true false char 16 bit Unicode character 'A' '\x0041' '\u0041' sbyte 8 bit signed integer none byte 8 bit unsigned integer short 16 bit signed integer ushort 16 bit unsigned integer int 32 bit signed integer uint 32 bit unsigned integer U suffix long 64 bit signed integer L or l suffix ulong 64 bit unsigned integer U/u and L/l suffix float 32 bit floating point F or f suffix double 64 bit floating point no suffix decimal 128 bit high precision M or m suffix string character sequence "hello" Boolean character integer floating point string Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

6 Local variable declaration
2: Basics Local variable declaration Declare variables by specifying type and name names are case sensitive comma separated list for multiple variables end with semicolon class MyApplication { static void Main() double area; char grade; int x, y, z; string name; ... } variables Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

7 Local variable initialization
2: Basics Local variable initialization Can initialize local variables when declared use literal value or expression compiler error to use without initializing class MyApplication { static void Main() int width = 2; int height = 4; int area = width * height; int x; int y = x * 2; ... } literals expression error, x not set Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

8 Type conversion Some automatic type conversions available
2: Basics Type conversion Some automatic type conversions available from smaller to larger types Conversions which may lose information require cast syntax is type name inside parentheses int i = 5; double d = 3.2; d = i; i = (int)d; implicit conversion cast required Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

9 Input Read input using ReadLine from Console class in System namespace
2: Basics Input Read input using ReadLine from Console class in System namespace returns entire input line as a string Typically then need to convert string to actual type conversion methods provided in Convert class read entire line string s = System.Console.ReadLine(); int i = System.Convert.ToInt32 (s); double d = System.Convert.ToDouble(s); convert string to int convert string to double Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

10 Output Write output using Write and WriteLine
2: Basics Output Write output using Write and WriteLine from Console class in System namespace WriteLine adds line terminator in output overloaded versions allow printing of all types some versions take format string and data variable argument list version allows printing multiple values int i = 3; double d = 5.2; System.Console.WriteLine(i); System.Console.WriteLine(d); System.Console.WriteLine("first {0} second {1}", i, d); int double multiple format string placeholder value Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

11 Library namespace Core standard library is System namespace
2: Basics Library namespace Core standard library is System namespace a using directive provides shorthand access using System; class MyApplication { static void Main() string s = Console.ReadLine(); int i = Convert.ToInt32(s); ... } using directive short names Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

12 Comments Three comment styles available XML documentation comment ///
2: Basics Comments Three comment styles available XML documentation comment /// delimited code comment /* ... */ single line code comment // /// <summary> /// MyApplication is very simple.</summary> class MyApplication { static void Main() /* delimited comment can extend across multiple lines */ int x; // comment goes to end of line ... } documentation delimited single line Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

13 Operators Comprehensive set of operators available int x = 5;
2: Basics Operators Comprehensive set of operators available Operator Description + addition - subtraction * multiplication / division % remainder << left shift >> right shift & bitwise and | bitwise or ^ bitwise xor ~ bitwise complement int x = 5; int y = 3; int z = x + y; addition Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

14 Combination assignment
2: Basics Combination assignment Several combination assignment operators available perform both operation and assignment Operator Description += add / assign -= subtract / assign *= multiply / assign /= divide / assign %= remainder / assign <<= left shift / assign >>= right shift / assign &= bitwise and / assign |= bitwise or / assign ^= bitwise xor / assign int x = 5; x += 2; combination addition Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

15 Shorthand operators A few shorthand operators available int x = 5;
2: Basics Shorthand operators A few shorthand operators available Operator Description ++ pre/post increment -- pre/post decrement ?: conditional int x = 5; int y = x++; int z = ++x; int x = 5; int y = 3; int max; max = x > y ? x : y; post-increment y = 5, x = 6 max set to greater of x and y pre-increment x = 7, z = 7 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

16 Array Arrays provide efficient storage of multiple data elements
2: Basics Array Arrays provide efficient storage of multiple data elements create using new specify element type and array size access elements using operator [ ] total number of elements recorded in Length property valid indices are 0 to Length-1 IndexOutOfRangeException generated if index invalid create int[] a = new int[5]; a[0] = 17; a[1] = 32; int x = a[1]; int l = a.Length; element access number of elements Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

17 Array element values Array elements have default values
2: Basics Array element values Array elements have default values 0 for numeric types false for bool '\x0000' for char null for references Programmer can supply initial values default to false bool[] a = new bool[10]; int[] b = new int[5]; int[] c = new int[5] { 48, 2, 55, 17, 7 }; default to 0 set to given values Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

18 If statement if statement provides conditional execution
2: Basics If statement if statement provides conditional execution Boolean expression is evaluated associated statement executed only if expression is true expression must be inside parentheses keywords such as "if" are case sensitive int temperature = 127; bool boiling = false; if (temperature >= 100) boiling = true; if statement Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

19 If/else statement if statement may provide optional else part
2: Basics If/else statement if statement may provide optional else part executed if expression is false int x = 3; int y = 5; int min; if (x < y) min = x; else min = y; else part Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

20 Code block Block required for multiple statements in control construct
2: Basics Code block Block required for multiple statements in control construct use { ... } int x = 3; int y = 5; int min, max; if (x < y) { min = x; max = y; } else min = y; max = x; block block Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

21 Comparison and logical operators
2: Basics Comparison and logical operators Comparison operators compare two values yield Boolean result Combine Boolean values with conditional logical operators int x; char c; if (x > 0 && x < 10) ... if (c == 'y' || c == 'Y') if (!Char.IsLetter(c)) == equal != not equal <, <= less >, >= greater && and || or ! not both must be true either can be true c can't be a letter Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

22 2: Basics Switch statement switch statement performs selection from a set of options expression evaluated and matching case executed case labels must be constant values end each case with keyword break optional default case executed if no label matches double total = 0.0; char grade = 'C'; switch (grade) { case 'A': total += 4.0; break; case 'B': total += 3.0; break; case 'C': total += 2.0; break; case 'D': total += 1.0; break; case 'F': total += 0.0; break; default: Console.WriteLine("Error"); break; } switch cases default Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

23 Switch type Types allowed in switch are limited integral types string
2: Basics Switch type Types allowed in switch are limited integral types string string string color = "blue"; switch (color) { case "red" : Console.WriteLine("red"); break; case "blue" : Console.WriteLine("blue"); break; case "green": Console.WriteLine("green"); break; } strings Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

24 2: Basics Multiple labels Can associate several different labels with same action use separate case for each label place action in last case switch (grade) { case 'A': case 'B': case 'C': Console.WriteLine("pass"); break; case 'D': case 'F': Console.WriteLine("no pass"); } pass no pass Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

25 2: Basics Multiple actions Can perform multiple actions for match on single label must forward control to next desired case use goto case or goto default instead of break string level = "gold"; switch (level) { case "silver": priorityCheckIn = true; break; case "gold": priorityUpgrade = true; goto case "silver"; case "platinum": useOfLounge = true; goto case "gold"; } forward control to other case Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

26 while loop while loop runs as long as condition is true
2: Basics while loop while loop runs as long as condition is true statements repeatedly executed stops when condition becomes false int i = 0; while (i < 5) { ... i++; } loop while true Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

27 do-while loop do-while loop test condition located after body
2: Basics do-while loop do-while loop test condition located after body body executed at least once int x; do { string s = System.Console.ReadLine(); x = System.Convert.ToInt32(s); } while (x < 0); do test done after body Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

28 for loop for loop centralizes control information
2: Basics for loop for loop centralizes control information initialization, condition, update parts separated by semicolons done once at start loop runs while test is true done each time after body for (int k = 0; k < 5; k++) { ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

29 2: Basics foreach loop Specialized foreach loop provided for collections like array reduces risk of indexing error provides read only access int[] data = new int[5] { 48, 2, 55, 17, 7 }; int sum = 0; foreach (int x in data) { sum += x; } foreach type value collection Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

30 Break break statement exits enclosing statement
2: Basics Break break statement exits enclosing statement usable with switch, while, do, for, foreach int i = 0; bool error; while (i < 5) { ... if (error) break; } break Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

31 Continue continue statement skips to end of current loop iteration
2: Basics Continue continue statement skips to end of current loop iteration does not exit loop usable with while, do, for, foreach int i = 0; bool skip; while (i < 5) { ... if (skip) continue; } continue Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

32 Goto goto transfers control to the specified labeled statement
2: Basics Goto goto transfers control to the specified labeled statement label must be in current or outer scope label must be in same method int[,] data = new int[2,4]; for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) if (data[i,j] < 0) goto error; ... } error: Console.WriteLine("Error"); goto label Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

33 Summary Class is basic unit of C# coding
2: Basics Summary Class is basic unit of C# coding Main defines application entry point Comprehensive set of types available Standard operators provided Arrays provide efficient way to store large amount of data Control constructs offer balance of convenience and safety Programming C# © 2003 DevelopMentor, Inc. 12/1/2003


Download ppt "2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003."

Similar presentations


Ads by Google