Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 30a C# as Conventional Prog Lan

Similar presentations


Presentation on theme: "Lecture 30a C# as Conventional Prog Lan"— Presentation transcript:

1 Lecture 30a C# as Conventional Prog Lan
COS240 O-O Languages AUBG, COS dept Lecture 30a Title: C# as Conventional Prog Lan (Tutorial Introduction) Reference: COS240 Syllabus 5/6/2018 Assoc. Prof. Stoyan Bonev

2 Lecture Contents (new):
Why C# (instead intro) Anatomy of a C# program Sample source text, Namespaces, comments, names – (identifiers, reserved words, modifiers), classes (methods (statements, blocks of statements)) Components of a C# program Data – by category Data – by type Expressions (incl. operands & operators) Statements Routines (member functions - methods) I/O facilities Data collections – arrays Demo programs - examples 5/6/2018 Assoc. Prof. Stoyan Bonev

3 Assoc. Prof. Stoyan Bonev
Why C#? Good C# tutorials: 5/6/2018 Assoc. Prof. Stoyan Bonev

4 Assoc. Prof. Stoyan Bonev
Why C# One of the newer programming languages Conforms closely to C and C++ Has the rapid graphical user interface (GUI) features of previous versions of Visual Basic Has the added power of C++ Has the object-oriented class libraries similar to Java 5/6/2018 Assoc. Prof. Stoyan Bonev 4 Source: Longman dictionary 1987 4

5 Assoc. Prof. Stoyan Bonev
Why C# (continued) Can be used to develop a number of applications Software components Mobile applications Dynamic Web pages Database access components Windows desktop applications Web services Console-based applications 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 5 Source: Longman dictionary 1987 5

6 Assoc. Prof. Stoyan Bonev
C# Language C# is the next phase in the evolution of C and C++ and was developed expressly for Microsoft’s .NET platform. C# provides the features that are most important to programmers, such as: object-oriented programming, strings, graphics, graphical-user-interface (GUI) components, exception handling, event handling, multimedia (audio, images, animation and video), file processing, database processing, 5/6/2018 Assoc. Prof. Stoyan Bonev

7 Assoc. Prof. Stoyan Bonev
C# Language C# is fully object-oriented C# is an event-driven, visual programming language in which programs are created, run, tested and debugged using an Integrated Development Environment (IDE). The process of creating an application using an IDE is referred to as Rapid Application Development (RAD). 5/6/2018 Assoc. Prof. Stoyan Bonev

8 Anatomy of a C# program: Sample source text
5/6/2018 Assoc. Prof. Stoyan Bonev

9 Assoc. Prof. Stoyan Bonev
Syntax for simple C# program // Program start class public class class_name { // Main begins program execution public static void Main(string[] args) // implementation of method } 5/6/2018 Assoc. Prof. Stoyan Bonev

10 Hello World! Console Application
5/6/2018 Assoc. Prof. Stoyan Bonev

11 Anatomy of a C# program: Namespaces
5/6/2018 Assoc. Prof. Stoyan Bonev

12 Assoc. Prof. Stoyan Bonev
Line 4: using directive using System; directive is generated by the Visual Studio IDE and declares that the program uses features in the System namespace. A namespace groups various C# features into related categories. One of the great strengths of C# is that C# programmers can use the rich set of namespaces provided by the .NET framework. These namespaces contain code that programmers can reuse, rather than “reinventing the wheel.” This makes programming easier and faster. The namespaces that are defined in the .NET Framework contain preexisting code known as the .NET Framework Class Library. An example of one of the features in namespace System is Console. The various features are organized into namespaces that enable programmers to locate them easily. 5/6/2018 Assoc. Prof. Stoyan Bonev

13 Assoc. Prof. Stoyan Bonev
using Directive Permits use of classes found in specific namespaces without having to qualify them Framework class library Over 2,000 classes included Syntax: using namespaceIdentifier; 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 13 Source: Longman dictionary 1987 13

14 Namespace (continued)
Predefined namespace (System) – part of .NET FCL From Example 1-1 line // This is traditionally the first program written. line using System; line namespace HelloWorldProgram line { line } User-defined namespace Body of user-defined namespace 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 14 Source: Longman dictionary 1987 14

15 Assoc. Prof. Stoyan Bonev
The System namespace The System namespace contains fundamental classes and base classes that define: commonly-used value data types and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. 5/6/2018 Assoc. Prof. Stoyan Bonev

16 Assoc. Prof. Stoyan Bonev
Namespaces Used to group classes together based on function and help you organize your code. Usually a hierarchical naming system is used. Used to avoid naming collisions. You can have nested namespaces. E.g. namespace X{...} namespace X.Y{...} 5/6/2018 Assoc. Prof. Stoyan Bonev

17 Assoc. Prof. Stoyan Bonev
To access classes and methods without using their fully qualified name, use the using directive before a namespace declaration. E.g. using System; using System.IO; 5/6/2018 Assoc. Prof. Stoyan Bonev

18 Assoc. Prof. Stoyan Bonev
Console.WriteLine In C# statements we normally precede each class name (like Console) with its namespace name (like System) and a period. For example: System.Console.WriteLine( "Welcome to C# Programming!" ); The using directive (like using System;) eliminates the need to specify explicitly the namespace System when using classes in the namespace. This can save time and confusion for programmers. Console.WriteLine( "Welcome to C# Programming!" ); 5/6/2018 Assoc. Prof. Stoyan Bonev

19 Assoc. Prof. Stoyan Bonev
Using namespaces // Namespace Declaration using System; // Program start class public class HelloWorld { // Main begins program execution public static void Main(string[] args) // This is a single line comment /* This is a multiple line comment */ Console.WriteLine("Hello World!"); } 5/6/2018 Assoc. Prof. Stoyan Bonev

20 Assoc. Prof. Stoyan Bonev
More Choices public static void Main() { ... } public static int Main() { return 0; public static int Main(string[] args) { 5/6/2018 Assoc. Prof. Stoyan Bonev

21 Anatomy of a C# program: Comments
5/6/2018 Assoc. Prof. Stoyan Bonev

22 Assoc. Prof. Stoyan Bonev
Comments Three types of commenting syntax Inline comments Multiline comments XML documentation comments C# uses the same syntax as the C programming language for multiple-line comments (/*…*/) and the same syntax as C++ for single-line comments (//). 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 22 Source: Longman dictionary 1987 22

23 XML Documentation Comments
Extensible Markup Language (XML) Markup language that provides a format for describing data using tags Similar to HTML tags Three forward slashes (///) mark beginning Advanced documentation technique used for XML-style comments Compiler generates XML documentation from them 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 23 Source: Longman dictionary 1987 23

24 Anatomy of a C# program: names - identifiers
5/6/2018 Assoc. Prof. Stoyan Bonev

25 Assoc. Prof. Stoyan Bonev
Identifiers The name of the class is known as an identifier, which is a series of characters consisting of letters, digits, underscores ( _ ) and “at” symbols Identifiers cannot begin with a digit and cannot contain spaces. Examples of valid identifiers are Welcome1, _value, m_inputField1 and button7. The name 7button is not a valid identifier because it begins with a digit The name input field is not a valid identifier because it contains a space. The “at” character can be used only as the first character in an identifier. C# is case sensitive — uppercase and lowercase letters are considered different letters. 5/6/2018 Assoc. Prof. Stoyan Bonev

26 Anatomy of a C# program: reserved words
5/6/2018 Assoc. Prof. Stoyan Bonev

27 Assoc. Prof. Stoyan Bonev
Reserved Words in C# 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 27 Source: Longman dictionary 1987 27

28 Reserved Words in C# (continued)
Contextual keywords As powerful as regular keywords Contextual keywords have special meaning only when used in a specific context; other times they can be used as identifiers 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 28 Source: Longman dictionary 1987 28

29 Assoc. Prof. Stoyan Bonev
Reserved words Keywords (or reserved words) are reserved for use by C# and always consist of lowercase letters. 5/6/2018 Assoc. Prof. Stoyan Bonev

30 Anatomy of a C# program: modifiers
5/6/2018 Assoc. Prof. Stoyan Bonev

31 Anatomy of a C# program: classes
5/6/2018 Assoc. Prof. Stoyan Bonev

32 Assoc. Prof. Stoyan Bonev
Line 6-12: Class Welcome1 Line 6-12 class (these lines collectively are called a class definition). C# programs consist of pieces called classes, which are logical groupings of members (e.g., methods) that simplify program organization. These methods (which are like functions in procedural programming languages) perform tasks and return information when the tasks are completed. A C# program consists of classes and methods created by the programmer and of preexisting classes found in the Framework Class Library. 5/6/2018 Assoc. Prof. Stoyan Bonev

33 Assoc. Prof. Stoyan Bonev
Class Welcome1 The class keyword begins a class definition in C# and is followed immediately by the class name (Welcome1, in this example). 5/6/2018 Assoc. Prof. Stoyan Bonev

34 Assoc. Prof. Stoyan Bonev
Class Body The left brace ({) at line 7 begins the body of the class definition. The corresponding right brace (}) at line 12 ends the class definition. Notice that lines 8–11 in the body of the class are indented. This is one of the spacing conventions. Indentation improves program readability. 5/6/2018 Assoc. Prof. Stoyan Bonev

35 Anatomy of a C# program: classes (methods)
C# class definitions normally contain one or more methods (member functions) and C# applications contain one or more classes. For a C# console or Windows application, exactly one of those methods must be called Main, and it must be defined as static void Main( string args[] ) 5/6/2018 Assoc. Prof. Stoyan Bonev

36 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

37 Assoc. Prof. Stoyan Bonev
The left brace ({) on line 9 begins the body of the method definition (the code which will be executed as a part of our program). A corresponding right brace (}) terminates the method definition’s body (line 11). Notice that the line in the body of the method is indented between these braces. 5/6/2018 Assoc. Prof. Stoyan Bonev

38 Anatomy of a C# program classes (methods (statements))
5/6/2018 Assoc. Prof. Stoyan Bonev

39 Assoc. Prof. Stoyan Bonev
Statement(s) Line 10 is considered a statement. It instructs the computer to perform an action, namely, to print a series of characters contained between the double quotation marks. Characters delimited in this manner are called strings, character strings or string literals. We refer to characters between double quotation marks generically as strings. Whitespace characters in strings are significant—the compiler does not ignore these characters when they appear in strings. 5/6/2018 Assoc. Prof. Stoyan Bonev

40 Assoc. Prof. Stoyan Bonev
Console.WriteLine The Console class enables programs to output information to the computer’s standard output. Class Console provides methods that allow C# programs to display strings and other types of information in the Windows command prompt. 5/6/2018 Assoc. Prof. Stoyan Bonev

41 Assoc. Prof. Stoyan Bonev
Console.WriteLine The entire line, including Console.WriteLine, its argument in the parentheses ("Welcome to C# Programming!") and the semicolon (;), is called a statement. Every statement must end with a semicolon (known as the statement terminator). When this statement executes, it displays the message Welcome to C# Programming! in the console window Execution of the Welcome Program: 5/6/2018 Assoc. Prof. Stoyan Bonev

42 Anatomy of a C# program blocks of statements
5/6/2018 Assoc. Prof. Stoyan Bonev

43 Components of a C# program Data – by category
Literals Constants Variables 5/6/2018 Assoc. Prof. Stoyan Bonev

44 Constant Definition Constant definitions have the following syntax:
const datatype name = value; To define a constant to hold the value of pi, for example, you could use a statement such as this: const double c_pi = ; 5/6/2018 Assoc. Prof. Stoyan Bonev

45 Declaring Variables datatype variablename = initialvalue;
To create a new string variable and initialize it with a value, for example, you could use two statements, such as the following: string strName; strName = “Matt Perry”; However, if you know the initial value of the variable at design time, you can include it on the declaration statement, like this: string strName = “Matt Perry”; Note: supplying an initial value doesn’t make this a constant; it’s still a variable, and the value of the variable can be changed at any time. 5/6/2018 Assoc. Prof. Stoyan Bonev

46 Components of a C# program: Data – by type
5/6/2018 Assoc. Prof. Stoyan Bonev

47 Assoc. Prof. Stoyan Bonev
Operators, Types, and Variables Variables C# is a strongly “typed" language (aka “type-safe”.) Thus all operations on variables are performed with consideration of what the variable's “type" is. Variables can hold either value types or reference types (or they can be pointers). 5/6/2018 Assoc. Prof. Stoyan Bonev

48 Assoc. Prof. Stoyan Bonev
Value type where a variable X contains a value type, it directly contains an entity with some value. No other variable Y can directly contain the object contained by X (although Y might contain an entity with the same value). Reference type where a variable X contains a reference type, what it directly contains is something that refers to an object. Another variable Y can contain a reference to the same object referred to by X. Reference types actually hold the value of a memory address occupied by the object they reference. 5/6/2018 Assoc. Prof. Stoyan Bonev

49 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

50 Assoc. Prof. Stoyan Bonev
Predefined (Data) Types C# predefined types The “root” object Logical bool Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Floating-point float, double, decimal Textual char, string Textual types use Unicode (16-bit characters) 5/6/2018 Assoc. Prof. Stoyan Bonev

51 Assoc. Prof. Stoyan Bonev
All types are compatible with object - can be assigned to variables of type object - all operations of type object are applicable to them 5/6/2018 Assoc. Prof. Stoyan Bonev

52 Assoc. Prof. Stoyan Bonev
Predefined Data Types Common Type System (CTS) Divided into two major categories Figure 2-3 .NET common types 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 52 Source: Longman dictionary 1987 52

53 Value and Reference Types
Figure 2-4 Memory representation for value and reference types 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 53 Source: Longman dictionary 1987 53

54 Assoc. Prof. Stoyan Bonev
Value Types Fundamental or primitive data types Figure 2-5 Value type hierarchy 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 54 Source: Longman dictionary 1987 54

55 Value Types (continued)
5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 55 Source: Longman dictionary 1987 55

56 Assoc. Prof. Stoyan Bonev
Types C# simple types consist of the Boolean type and three numeric types (integer, floating-point and decimal) and the String type. The pre-defined reference types are object and string, where object is the ultimate base class of all other types. Boolean type - Boolean types are declared using the keyword, bool. They have two values: true or false. These are keywords. E.g. bool gaga = true; 5/6/2018 Assoc. Prof. Stoyan Bonev

57 Assoc. Prof. Stoyan Bonev
Integer type In C#, an integer is a category of types. They are whole numbers, either signed or unsigned. 5/6/2018 Assoc. Prof. Stoyan Bonev

58 Assoc. Prof. Stoyan Bonev
Floating-Point and Decimal Types A C# floating-point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values. 5/6/2018 Assoc. Prof. Stoyan Bonev

59 Assoc. Prof. Stoyan Bonev
The String Type A string is a sequence of text characters. The keyword string is an alias for the class System.String. Either may be used to define a string variable. A string literal is just some text enclosed with double quotes. E.g. “This is a string” There is a char type used to represent one Unicode character. 5/6/2018 Assoc. Prof. Stoyan Bonev

60 Assoc. Prof. Stoyan Bonev
Class System.String Can be used as standard type string string s = “AUBG"; Note • Strings are immutable (use class StringBuilder if you want to extend a string) • Can be concatenated with +: " + s; • Can be indexed: s[i] • String length: s.Length • Strings are reference types  reference semantics in assignments. • But their values can be compared with == and !=: if (s == "AUBG") ... • Class String defines many useful operations: CompareTo, IndexOf, StartsWith, Substring, ... 5/6/2018 Assoc. Prof. Stoyan Bonev

61 Casting Data from One Data Type to Another
5/6/2018 Assoc. Prof. Stoyan Bonev

62 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

63 Assoc. Prof. Stoyan Bonev
Mixed Expressions Implicit type coercion Changes int data type into a double No implicit conversion from double to int Figure 2-14 Syntax error generated for assigning a double to an int 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 63 Source: Longman dictionary 1987 63

64 Mixed Expressions (continued)
Explicit type coercion Cast (type) expression examAverage = (exam1+exam2+exam3) / (double) count; Int value1 = 0, anotherNumber = 75; double value2 = , anotherDouble = 100; value1 = (int) value2; // value1 = 100 value2 = (double) anotherNumber; // value2 = 75.0 5/6/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 64 Source: Longman dictionary 1987 64

65 Components of a C# program: Expressions (incl. operands & operators)
5/6/2018 Assoc. Prof. Stoyan Bonev

66 Components of a C# program: Expressions (operands)
Literal Values Constants Variables – scalar or indexed Structure member Function call Sub expression like ( … ) 5/6/2018 Assoc. Prof. Stoyan Bonev

67 Components of a C# program: Expressions (operators)
5/6/2018 Assoc. Prof. Stoyan Bonev

68 Assoc. Prof. Stoyan Bonev
C# Operators The table on the following slide describes the allowable operators, their precedence, and associativity. Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left, such as assignment operators where everything to the right is evaluated before the result is placed into the variable on the left. 5/6/2018 Assoc. Prof. Stoyan Bonev

69 Assoc. Prof. Stoyan Bonev
Operators 5/6/2018 Assoc. Prof. Stoyan Bonev

70 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

71 Components of a C# program: Statements
5/6/2018 Assoc. Prof. Stoyan Bonev

72 Assoc. Prof. Stoyan Bonev
Statements in C# C# supports the standard assortment … assignment subroutine and function call conditional if, switch iteration for, while, do-while, foreach control Flow return, break, continue, goto 5/6/2018 Assoc. Prof. Stoyan Bonev

73 Passing Literal Values to a Variable
The syntax of assigning a literal value to a variable depends on the variable’s data type. For strings, you must pass the value in quotation marks, like this: strCollegeName = “Bellevue University”; There is one caveat when assigning literal values to strings: Visual C# interprets slashes (\) as being a special type of escape sequence. If you pass a literal string containing one or more slashes to a variable, you get an error. What you have to do in such instances is preface the literal with the like this: strFilePath When Visual C# encounters symbol after the equal sign as shown in the preceding example, it knows not to treat slashes in the string as escape sequences. 5/6/2018 Assoc. Prof. Stoyan Bonev

74 if (condition) statement;
Decision Structures - Selection Same syntax for C++, C#, and Java if (condition) statement; The basic selection statement is the if statement. Used to execute or skip a statement or block of statements depending on a Boolean expression 5/6/2018 Assoc. Prof. Stoyan Bonev

75 Assoc. Prof. Stoyan Bonev
Examples if (x == valueOne)  {   Console.Writeline("x is ");   Console.Writeline( x );  } if (x == valueOne)   Console.Writeline("x is 100"); else   Console.Writeline("x is not 100"); 5/6/2018 Assoc. Prof. Stoyan Bonev

76 Assoc. Prof. Stoyan Bonev
if('0' <= ch && ch <= '9') val = ch -'0'; else if('A' <= ch && ch <= 'Z') val = 10 + ch -'A'; else { val = 0; Console.WriteLine("invalid character",ch); } 5/6/2018 Assoc. Prof. Stoyan Bonev

77 Assoc. Prof. Stoyan Bonev
Switch construct Same syntax for C++, C#, and Java switch can only be used to compare an expression with different constants /numeric or symbolic/. The types of the values a switch statement operates on can be booleans, enums, integral types, and strings (null is acceptable as a case label). No fall-through! - Every statement sequence in a case must be terminated with break (or return, goto, throw). If no case label matches  default If no default specified  continuation after the switch statement 5/6/2018 Assoc. Prof. Stoyan Bonev

78 Assoc. Prof. Stoyan Bonev
switch (x) { case 5: Console.Writeline("x is 5"); break; case 99: Console.Writeline("x is 99"); default: Console.Writeline("value of x unknown"); } 5/6/2018 Assoc. Prof. Stoyan Bonev

79 Assoc. Prof. Stoyan Bonev
switch(country) { case "Germany": case "Austria": Case "Switzerland": language = "German"; break; case "England": case "USA": language = "English"; case null: Console.WriteLine("no country specified"); default: Console.WriteLine("don't know language of", country); } 5/6/2018 Assoc. Prof. Stoyan Bonev

80 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

81 while (Boolean expression)
Loops Same syntax for C++, C#, and Java while (Boolean expression) {statements} while ( x > 1 )  {   Console.Writeline("x is ");   Console.Writeline( x ); x--;  } 5/6/2018 Assoc. Prof. Stoyan Bonev

82 Assoc. Prof. Stoyan Bonev
do {statements} while (Boolean expression) do {   Console.Writeline("x is ");   Console.Writeline( x ); x--; } while (x !=1 ); 5/6/2018 Assoc. Prof. Stoyan Bonev

83 Assoc. Prof. Stoyan Bonev
Loops Same syntax for C++, C#, and JAVA for (initialization; condition; in(de)crement) {statement;} for (int n=10; n>0; n--) { Console.Write( n ); Console.Write(", "); } 5/6/2018 Assoc. Prof. Stoyan Bonev

84 Assoc. Prof. Stoyan Bonev
foreach statement For iterating over collections and arrays // array traverse using foreach int[] a = {3, 17, 4, 8, 2, 29}; foreach (int x in a) sum += x; string s = "Hello"; foreach (char ch in s) Console.WriteLine(ch); 5/6/2018 Assoc. Prof. Stoyan Bonev

85 Components of a C# program: Routines (methods)
Already shortly discussed in section classes(methods(statements)) Same as in C++, Java 5/6/2018 Assoc. Prof. Stoyan Bonev

86 Components of a C# program: I/O
5/6/2018 Assoc. Prof. Stoyan Bonev

87 Assoc. Prof. Stoyan Bonev
Console Output Output is managed by a class named Console. This Console class has a method WriteLine() which takes a string (a set of characters) and writes it to the standard output. Console.WriteLine("Text"); // prints “Text” to the screen Console.WriteLine(120); // prints value 120 on screen Console.WriteLine(x.ToString()); // prints the content of x on screen 5/6/2018 Assoc. Prof. Stoyan Bonev

88 Assoc. Prof. Stoyan Bonev
Console Input The Console class provides basic support for applications that input characters. Data is read from the standard input stream int x; string alpha; alpha = Console.ReadLine(); // read the input from the keyboard x = System.Convert.ToInt32(alpha); // and save it in variable x 5/6/2018 Assoc. Prof. Stoyan Bonev

89 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

90 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

91 Assoc. Prof. Stoyan Bonev
ReadLine Method ReadLine (firstNumber=Console.ReadLne();) causes the program to pause and wait for user input. The user inputs characters from the keyboard, then presses the Enter key to return the string to the program. the .NET Framework does not provide a simple input dialog. For this reason, the examples in these early chapters receive user input through the command prompt. 5/6/2018 Assoc. Prof. Stoyan Bonev

92 Assoc. Prof. Stoyan Bonev
assignment operator = When the user enters a number and presses Enter, the program assigns the string representation of this number to variable firstNumber (line 19) with the assignment operator =. The statement is read as, “firstNumber gets the value returned by method ReadLine.” The = operator is a binary operator, because it has two operands—first-Number, and the result of the expression Console.ReadLine. The entire statement is an assignment statement, because it assigns a value to a variable. In an assignment statement, first the right side of the assignment is evaluated, then the result is assigned to the variable on the left side of the assignment. So, line 19 executes method ReadLine, then assigns the string value to firstNumber. 5/6/2018 Assoc. Prof. Stoyan Bonev

93 Assoc. Prof. Stoyan Bonev
Input Data Lines 22–23 prompt the user to enter a second integer and read from the user a string representing the value. Lines 26–27 convert the two strings input by the user to int values that can be used in a calculation. Method Int32.Parse (a static method of class Int32) converts its string argument to an integer. Class Int32 is part of the System namespace. Line 26 assigns the integer that Int32.Parse returns to variable number1. Any subsequent references to number1 in the program use this integer value. Line 27 assigns the integer that Int32.Parse returns to variable number2. Any subsequent references to number2 in the program use this integer value. 5/6/2018 Assoc. Prof. Stoyan Bonev

94 Assoc. Prof. Stoyan Bonev
Input Data You can eliminate the need for string variables firstNumber and secondNumber by combining the input and conversion operations as follows: int number1; number1 = Int32.Parse( Console.ReadLine() ); 5/6/2018 Assoc. Prof. Stoyan Bonev

95 Assoc. Prof. Stoyan Bonev
Input Data In C#, users input data as strings. We convert these strings to perform integer arithmetic. Arithmetic operations do not work with strings the same way operations work with integers. To add numbers and get the proper sum, we must convert the strings to integers. The preceding statements do not make use of the string variable (firstNumber). This variable is required only to store the string temporarily until the program converts it. Reading the string and converting it on one line makes the variable unnecessary. 5/6/2018 Assoc. Prof. Stoyan Bonev

96 Assoc. Prof. Stoyan Bonev
WriteLine format After performing the calculation, Console.WriteLine(“\nThe sum is {0}.”, sum); displays the result of the addition. In this example, we want to output the value in a variable using method WriteLine. Let us discuss how this is done. The comma-separated arguments to Console.WriteLine "\nThe sum is {0}.", sum use {0} to indicate a placeholder for a variable’s value. If we assume that sum contains the value 117, the expression evaluates as follows: 5/6/2018 Assoc. Prof. Stoyan Bonev

97 Assoc. Prof. Stoyan Bonev
Console.WriteLine( "The numbers entered are {0} and {1}", number1, number2 ); Method WriteLine encounters a number in curly braces, {0}, known as a format. This indicates that the variable found after the string in the list of arguments (in this case, sum) will be evaluated and incorporated into our string, in place of the format. The resulting string will be “The sum is 117.” Similarly, in the statement the value of number1 would replace {0} (because it is the first variable) and the value of number2 would replace {1} (because it is the second variable). The resulting string would be "The numbers entered are 45 and 72". More formats can be used ({2}, {3} etc.) if there are more variables to display in the string. 5/6/2018 Assoc. Prof. Stoyan Bonev

98 Assoc. Prof. Stoyan Bonev
5/6/2018 Assoc. Prof. Stoyan Bonev

99 Components of a C# program: Data collections
Arrays Records (C-like structs) 5/6/2018 Assoc. Prof. Stoyan Bonev

100 Assoc. Prof. Stoyan Bonev
Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search and manipulate - Elements in an array are always numbered 0 through N-1, where N is the total number of elements, called the size or length of array - Position of an element in an array is called the element index or subscript - Array of values are arranged in consecutive memory locations 5/6/2018 Assoc. Prof. Stoyan Bonev

101 Assoc. Prof. Stoyan Bonev
One-Dimensional Array Declaration of array In C#, declaration of array is a reference declaration, no allocation of memory to hold array elements. No actual array created yet. dataType[] arrayName; int[] data; string[] sentence; 5/6/2018 Assoc. Prof. Stoyan Bonev

102 Assoc. Prof. Stoyan Bonev
Create array using new operator arrayName = new dataType[size]; Allocate memory; hence an array data = new int[10]; Put together declaration and creation: int[] data = new int[100]; To access each element, use subscript or index, e.g. data[i], where i should be in the range 0 through length-1 5/6/2018 Assoc. Prof. Stoyan Bonev

103 Assoc. Prof. Stoyan Bonev
Array of primitive number types automatically initialized as 0, while bool type is initialized as false. Other types are reference types and initialized to the special value null. Once an aray has been declared and created, can assign values to each element a[0] = 10; a[1] = 20; 5/6/2018 Assoc. Prof. Stoyan Bonev

104 Assoc. Prof. Stoyan Bonev
C# has an easy way to initialize element values while declaring and creating the array int[] a = new int[2] {10, 20}; Or int[] a = new int[] {10, 20}; Length, a public method of System.Array, can be used to get the total number of elements, i.e. size of an array. Lots of other methods in System.Array 5/6/2018 Assoc. Prof. Stoyan Bonev

105 Assoc. Prof. Stoyan Bonev
Example using System; class ArraySum { public static void Main() int[] data = new int[] {11,12,13,14,15,16,17}; int sum = 0; double ave; for (int i = 0; i < data.Length; ++i) sum = sum + data[i]; Console.Write(data[i] + ", "); } ave = sum / (double)(data.Length); Console.WriteLine(“Sum="+sum+" average="+ave); 5/6/2018 Assoc. Prof. Stoyan Bonev

106 Assoc. Prof. Stoyan Bonev
Passing Array to Method as Parameter C# passes array parameters by reference More efficient to pass reference, rather than large amount of actual data Called method can manipulate the contents of the array passed from a calling method, which causes side effect: possible “damage” to the original data May use built-in methods to copy arrays. 5/6/2018 Assoc. Prof. Stoyan Bonev

107 Assoc. Prof. Stoyan Bonev
using System; class MyCopy { public static void Main( ) int[] data1 = {1, 2, 3, 4, 5, 6, 7}; int[] data2 = {8, 9, 10, 11, 12, 13, 14}; CopyIt(data1, data2); Console.Write("data1:"); // Output data1 for (int i = 0; i < data1.Length; ++i) Console.Write(" " + data1[i]); Console.WriteLine(); Console.Write("data2:"); // Output data2 for (int i = 0; i < data2.Length; ++i) Console.Write(" " + data2[i]); Console.WriteLine(); // Output data2 } static void CopyIt(int[] from, int[] to) for (int i = 0; i < from.Length; ++i) to[i] = from[i]; 5/6/2018 Assoc. Prof. Stoyan Bonev

108 Assoc. Prof. Stoyan Bonev
The foreach Statement Alternative and simplified statement for the for statement for (index=0; index<arrayName.Length; ++index) { // process arrayName[index]; } foreach (Type variableName in arrayName) // statements; 5/6/2018 Assoc. Prof. Stoyan Bonev

109 Assoc. Prof. Stoyan Bonev
Example static void WriteArray(int[] a, string arayName) { Console.WriteLine(arrayName); foreach (int element in a) Console.Write(element + " "); Console.WriteLine(); } foreach can not be used to change the contents of the array 5/6/2018 Assoc. Prof. Stoyan Bonev

110 Assoc. Prof. Stoyan Bonev
// Use of Array methods using System; class ArrayMethods { public static void Main() string[] words = {"the", "quick", "brown", "fox", "jumped", "over", "the" , "fence"}; foreach (string s in words) Console.Write(s + ", "); Console.WriteLine("\nthe is at first " + Array.IndexOf(words, "the")); Console.WriteLine("the is at last " + Array.LastIndexOf(words, "the")); Array.Reverse(words); Console.Write(s+ ", "); Console.WriteLine("\n\nSorted"); Array.Sort(words); Console.WriteLine(s); } 5/6/2018 Assoc. Prof. Stoyan Bonev

111 Assoc. Prof. Stoyan Bonev
Recap: Arrays - One-dimensional int[] a = new int[3]; int[] b = new int[3] {3, 4, 5}; SomeClass[] d = new SomeClass[10]; // Array of references int len = a.Length; // number of elements in array 5/6/2018 Assoc. Prof. Stoyan Bonev

112 Assoc. Prof. Stoyan Bonev
Two-dimensional arrays Declaration of two-dimension arrays GetLength(0) and GetLength(1) respectively for the length of each dimension string[] line; // 1-D double [,] matrix; // 2-D int [,,] plane; // 3-D int[,] data = new int[3,5]; 5/6/2018 Assoc. Prof. Stoyan Bonev

113 Assoc. Prof. Stoyan Bonev
// Simple two dimensional array using System; class TwoD { public static void Main() int[,] data = new int[3,5]; // row x column Console.WriteLine("No. of elements = " + data.Length); for (int i = 0; i < data.GetLength(0); ++i) Console.WriteLine("Row " + i + ": "); for (int j = 0; j < data.GetLength(1); ++j) data[i,j] = i * j; Console.Write(data[i,j] + ", "); } Console.WriteLine(); 5/6/2018 Assoc. Prof. Stoyan Bonev

114 Assoc. Prof. Stoyan Bonev
Two-dimensional array initialization Different organizations int[,] a = {{1,2}, {3,4}, {5,6}}; int[,] b = {{1,2,3}, {4,5,6}}; int[,] c = {{1,2,3,4,5,6}}; a has three rows of two elements b has two rows of three elements c has one row of six elements – a degenerate two- dimensional array 5/6/2018 Assoc. Prof. Stoyan Bonev

115 Single-Dimensional Arrays (C#)
Source: You can declare an array of five integers as in the following example: int[] array = new int[5]; This array contains the elements from array[0] to array[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to zero. An array that stores string elements can be declared in the same way. For example: string[] stringArray = new string[6]; 5/6/2018 Assoc. Prof. Stoyan Bonev

116 Multi-Dimensional Arrays (C#)
Source: Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns: int[,] array = new int[4, 2]; Also, the following declaration creates an array of three dimensions, 4, 2, and 3: int[, ,] array1 = new int[4, 2, 3]; 5/6/2018 Assoc. Prof. Stoyan Bonev

117 Assoc. Prof. Stoyan Bonev
Jagged Arrays (C#) A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays.“ How to declare, initialize, and access jagged arrays. The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers: int[][] jaggedArray = new int[3][]; 5/6/2018 Assoc. Prof. Stoyan Bonev

118 Assoc. Prof. Stoyan Bonev
Jagged Arrays (C#) How to initialize a jagged array? Before you can use jaggedArray, its elements must be initialized like this: jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; Each of the elements is a single-dimensional array of integers. Initialized but not populated with values The first element is an array of 5 integers. The second is an array of 4 integers. The third is an array of 2 integers. 5/6/2018 Assoc. Prof. Stoyan Bonev

119 Assoc. Prof. Stoyan Bonev
Jagged Arrays (C#) You can use the following shorthand form. Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements: int[][] jaggedArray3 = { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} }; 5/6/2018 Assoc. Prof. Stoyan Bonev

120 Assoc. Prof. Stoyan Bonev
Jagged Arrays (C#) A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null. How to access individual array elements? You can access individual array elements like these examples: // Assign 77 to the second element ([1]) of the first array ([0]): jaggedArray3[0][1] = 77; // Assign 88 to the second element ([1]) of the third array ([2]): jaggedArray3[2][1] = 88; 5/6/2018 Assoc. Prof. Stoyan Bonev

121 Assoc. Prof. Stoyan Bonev
Associative Arrays C# using System.Collections; // associative array - special case - hashtable Hashtable ht = new Hashtable(); ht.Add("Sofia", "BG"); ht.Add("Berlin", "DE"); //MessageBox.Show(ht["Sofia"]); Console.WriteLine(ht["Sofia"]); 5/6/2018 Assoc. Prof. Stoyan Bonev

122 Assoc. Prof. Stoyan Bonev
Demo Programs Demonstrate end-of-file controlled loop using standard input from the keyboard and standard output to the screen Solution to implement in a version: as managed code console application Problem: To accumulate sum of stream of input integers terminated by end-of-data (CTRL/Z) indicator 5/6/2018 Assoc. Prof. Stoyan Bonev

123 Demo Program – Managed Code Only
// C# demo program, standard Input (keyboard) / Output (screen) // Int Console.Read(), // String Console.ReadLine() // ReadKey() // Methods Convert.ToInt32(string), etc … using System; namespace ConsoleApplication4 { class Program static void Main(string[] args) string pom; while ((pom = Console.ReadLine()) != null) sum += Convert.ToInt32(pom); } Console.WriteLine("Final sum = {0}",sum); 5/6/2018 Assoc. Prof. Stoyan Bonev

124 Thank You for Your attention!


Download ppt "Lecture 30a C# as Conventional Prog Lan"

Similar presentations


Ads by Google