Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5...

13
9/25/2017 EEE-425 Programming Languages (2013) 1 2 Namespaces Classes Fields Properties Methods Attributes Events Interfaces (contracts) Methods Properties Events Control Statements if, else, while, for, switch foreach Additional Features Operation Overloading Structs Enums Delegates OO Features Type Unification Inheritance Polymorphism 3 Namespaces Contain types and other namespaces Type declarations Classes, struct’s, interfaces, enum’s, and delegates Contain members Members Constants, fields, methods, operators, constructors, destructors Properties, indexers, events Organization No header files, types imported using assemblies (dll’s). Type reflection 4 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 A data item is classified as either constant or variable Constant data items cannot vary Variable data items can hold different values at different points of time All data items in a C# program have a data type Data type describes the format and size of a piece of data

Transcript of Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5...

Page 1: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 1

2

Namespaces Classes◦ Fields◦ Properties◦ Methods◦ Attributes◦ Events

Interfaces (contracts)◦ Methods◦ Properties◦ Events

Control Statements◦ if, else, while, for,

switch◦ foreach

Additional Features◦ Operation

Overloading◦ Structs◦ Enums◦ Delegates

OO Features◦ Type Unification◦ Inheritance◦ Polymorphism

3

Namespaces◦ Contain types and other namespaces

Type declarations◦ Classes, struct’s, interfaces, enum’s, and delegates◦ Contain members

Members◦ Constants, fields, methods, operators, constructors,

destructors◦ Properties, indexers, events

Organization◦ No header files, types imported using assemblies (dll’s).◦ Type reflection

4

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

A data item is classified as either constant or variable

Constant data items cannot vary

Variable data items can hold different values at different points of time

All data items in a C# program have a data type

Data type describes the format and size of a piece of data

Page 2: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 2

7

C# provides 14 basic or intrinsic types

The most commonly used data types are:◦ int,

◦ double,

◦ char,

◦ string, and bool

Each C# intrinsic type is an alias, or other name for, a class in the System namespace

8

A variable declaration includes:◦ The data type that the variable will store

◦ An identifier that is the variable’s name

◦ An optional assignment operator and assigned value when you want a variable to contain an initial value

◦ An ending semicolon

9

Examples of variable declarations:

int myAge = 25;

The equal sign (=) is an assignment operator

The assignment operator works from right to left

An assignment made when a variable is declared is an initialization

It is not necessary to initialize a variable during a declaration. For example int myAge; is a valid declaration

10

You can display variable values by using the variable name within a WriteLine() method call

11

Program that displays a string and a variable value

12

A format string is a string of characters that contains one or more placeholders. For example:◦ Console.WriteLine(“The money is {0} exactly”, someMoney);

Page 3: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 3

13

The number within the curly braces in the format string must be less than the number of values you list after the format string

You do not have to use the positions in order:◦ Console.WriteLine

(“The money is {0} . ${0} is a lot for my age which is {1}”, someMoney, myAge);

14

C# provides you with several shortcut ways to count and accumulate◦ Examples of Shortcuts:

+=, -+, *=, /=

The prefix and postfix operators can also provide a shorthand way of writing operators◦ Examples of the unary operators:

++val, val++

Besides the prefix and postfix increment operators, you can also use a decrement operator (--)

15

Boolean logic is based on true or false comparisons

Boolean variables can hold only one of two values: true or false

You can assign values based on the result of comparisons to Boolean variables

16

A floating-point number is one that contains decimal positions

C# supports three floating-point data types: float, double, and decimal

A double can hold 15 to 16 significant digits of accuracy

Floating-point numbers are double by default

17

Standard numeric format strings are strings of characters expressed within double quotation marks that indicate a format for output. For example, “F3” , where F is the format specifier and 3 is the precision specifier, indicates a fixed point with three significant digits.

The format specifier can be one of nine built-in format characters

The precision specifier controls the number of significant digits or zeros to the right of the decimal point

18

Format Specifiers

Page 4: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 4

19

In arithmetic operations with variables or constants of the same type, the result of the operation usually retains the same type

- For example, an integer type added to another integer type will result in an integer type

When an arithmetic operation is performed with dissimilar types, C# chooses a unifying type for the result and implicitly converts the nonconforming operands to the unifying type

There are rules followed by C# for implicit numeric conversions

20

When you perform a cast, you explicitly override the unifying type imposed by C#

For example:

double balance = 189.66;

int dollars = (int)balance;

A cast involves placing the desired resulting type in parentheses followed by the variable or constant to be cast

21

The char data type is used to hold a single character (‘A’,’b’,’9’)

A number can be a character only if it is enclosed in a single quotation mark (char aChar = 9; is illegal)

You can store any character in a char variable, including escape sequences

Characters in C# are represented in Unicode

22

In C# the string data type holds a series of characters

Although you can use the == comparison operator with strings that are assigned literal values, you CANNOT use it with strings created through other methods

C# recommends that you use the Equals() and Compare() methods to compare strings

A string is considered greater than another string when it is greater lexically

23

Program that compares two strings using ==

24

Program that compares two strings using Equals() and Compares()

Page 5: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 5

25

SalesTax program

26

A program that allows user input is an interactive program

The Console.ReadLine() method accepts user input from the keyboard

This method accepts a user’s input as a string

You must use a Convert() method to convert the input string to the type required

27

InteractiveSalesTax program

Strings are first-class immutable objects in C#

Behave like a value type

Can be indexed like a char array.

Has many methods (see System.String)

The @ command allows specifying a string literal spanning lines.

string s = “Hello”;

char third = s[2];

string[] split = s.Split(third);

28

Classes, including user-defined classes◦ Inherited from System.Object

◦ Transparently refers to a memory location

◦ Similar to pointers in other languages

Other view is that: Everything is a pointer.

◦ Can be set to null

memory

} fields in class A for instance a

{

A a = new A();

A b = a;

}

a

b29

Contain the actual value, not the location

Inherited from System.ValueType◦ Which is (logically) derived from System.Object.

Treated specially by the runtime

Need to be boxed in order to get a reference

memory

{

int a = 137;

int b = a;

}

a

b

137

137

30

Page 6: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 6

Value types are not indirectly referenced ◦ More efficient.

◦ Less memory.

In order to treat all types uniformly, a value type needs is converted to a reference type.◦ called boxing. Reverse is unboxing

{

int a = 137;

object o1 = a;

object o2 = o1; // Boxing

int b = (int)o2; //Unboxing

}

memorya

b

o1

o2

137

137int

137

31

using System;

namespace InvestigateOfBoxingUnBoxing{

class TestBoxing{

static void Main(){

int i = 123;object o = i; //Boxing

i = 456;// i = (int)o; //Unboxing ????Console.WriteLine("Value-type value = {0}", i);Console.WriteLine("Object type data value = {0}", o);

}}

} 32

Copy semantics:Polynomial a = new Polynomial();

Polynomial b = a;

b.Coefficient[0] = 10;

Console.WriteLine(a.Coefficient[0]);

int a = 1;

int b = a;

b = 10;

Console.WriteLine(a);

Copies of value types make a real copy◦ Important for parameter passing◦ Boxing still copies

33

In C++ you could pass a variable by:◦ Value (creating a new copy and passing it)

◦ Pointer (passing in the address)◦ Reference (same as pointer, less cluttered syntax).

In C# there seems to be some confusion and misinformation on this.◦ The MSDN documentation for ref has this correct.

If you were raised on pointers and understand this (which you are not), then it is quite simple.◦ The ref and out keywords indicate that you should pass:

Value types – address of value type is passed.

Reference types – address of pointer is passed.

34

ref parameters◦ Use the value that is passed in

◦ Change the value of a value type passed in

◦ Change the instance that a reference type points to.

◦ A valid (or initialized) instance or value type must be passed in.

Null is a valid value.

35

out parameters◦ Set the value of a value type passed in.

◦ Set the instance that a reference type points to.

◦ Does not need to be initialized before calling.

◦ Compiler forces you to set a value for all possible code paths.

36

Page 7: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 7

For variable number of parameterspublic void f(int x, params char[] ar);

call f(1), f(1, ‘s’), f(1, ‘s’, ‘f’), f(1, “sf”.ToCharArray());

Must be the last argument in the list

37

If, else

while

for

foreach

38

39

The typical for loop syntax is:

Consists of◦ Initialization statement

◦ Boolean test expression

◦ Update statement

◦ Loop body block

for (initialization; test; update){

statements;}

40

Iteration over a Collection

41

The typical foreach loop syntax is:

Iterates over all elements of a collection◦ The element is the loop variable that takes

sequentially all collection values

◦ The collection can be list, array or other group of elements of the same type

foreach (Type element in collection){

statements;}

42

Page 8: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 8

Example of foreach loop:

string[] days = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday", "Sunday" };

foreach (String day in days){Console.WriteLine(day);

}

The above loop iterates of the array of days

The variable day takes all its values

43

Print all elements of a string[] array:

string[] capitals ={

"Ankara","Washington","London","Paris"

};foreach (string capital in capitals){

Console.WriteLine(capital);}

44

Live Demo examples

45

switch statements must be expressions that can be statically evaluated.

Restricted to primitive types, strings and enums.

There is no fall through on switch cases unless the case is an empty case:

46

switch (myEmployee.Name)

{case “Boss”:

Console.Writeline(“Your fired!”);

break;case “Henry”:case “Jane”:

Console.Writeline(“I need a pay raise.”);

break;default:

Console.Writeline(“Busy working.”);

break;

}

47

Several C# statements provide a break in the execution:◦ break – jumps out of a while or for loop or a switch

statement.

◦ continue – starts the next iteration of a loop.

◦ goto – do not use.

◦ return – returns out of the current method.

◦ throw – Causes an exception and ends the current try block or method recursively.

48

Page 9: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 9

49

An array is a sequence of elements◦ All elements are of the same type

◦ The order of the elements is fixed

◦ Has fixed size (Array.Length)

0 1 2 3 4Array of 5 elements

Element index

Element of an array

… … … … …

50

Declaration defines the type of the elements

Square brackets [] mean "array"

Examples:◦ Declaring array of integers:

◦ Declaring array of strings:

int[] myIntArray;

string[] myStringArray;

51

An array is an object (not just a stream of objects). See System.Array.

Bounds checking is performed for all access attempts.

Declaration similar to Java, but more strict.◦ Type definition: a is a “1D array of int’s”◦ Instance specifics: a is equal to a 1D array of int’s

of size 10.int[] a = new int[10];

int[] b = a;

int[] c = new int[3] {1,2,3};

int[] d = {1,2,3,4};

52

Use the operator new◦ Specify array length

Example creating (allocating) array of 5 integers:

myIntArray = new int[5];

myIntArray

managed heap(dynamic memory)

0 1 2 3 4

… … … … …

53

Creating and initializing can be done together:

The new operator is not required when using curly brackets initialization

myIntArray = {1, 2, 3, 4, 5};

myIntArray

managed heap(dynamic memory)

0 1 2 3 4

… … … … …

54

Page 10: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 10

Creating an array that contains the names of the days of the week

string[] daysOfWeek ={

"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"

};

55

Live Demo

56

Accessing Array ElementsRead and Modify Elements by Index

57

Array elements are accessed using the square brackets operator [] (indexer)◦ Array indexer takes element’s index as parameter

◦ The first element has index 0

◦ The last element has index Length-1

Array elements can be retrieved and changed by the [] operator

58

int[] array = new int[] {1, 2, 3, 4, 5};

// Get array sizeint length = array.Length;

// Declare and create the reversed arrayint[] reversed = new int[length];

// Initialize the reversed arrayfor (int index = 0; index < length; index++){

reversed[length-index-1] = array[index];}

59

Reading and Printing Arrays on the Console

60

Page 11: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 11

First, read from the console the length of the array

Next, create the array of given size and read its elements in a for loop

int n = int.Parse(Console.ReadLine());

int[] arr = new int[n];for (int i=0; i<n; i++){

arr[i] = int.Parse(Console.ReadLine());}

61

Read int array from the console and check if it is symmetric:

bool isSymmetric = true;for (int i=0; i<(array.Length+1)/2; i++){

if (array[i] != array[n-i-1]){

isSymmetric = false;}

}

1 2 3 2 11 2 2 1 1 2 3 3 2 1

62

Process all elements of the array

Print each element to the console

Separate elements with white space or a new line

string[] array = {"one", "two", "three"};// Process all elements of the arrayfor (int index = 0; index < array.Length; index++){// Print each element on a separate lineConsole.WriteLine("element[{0}] = {1}“, index,

array[index]);}

63

class MyArray

{

static void Main(string[] args)

{

int [] n = new int[10]; /* n is an array of 10 integers*/

int i, j;

for (i = 0; i<10; i++) /*initialize elements of array n*/

{ n[ i ] = i + 100; }

for (j = 0; j <10; j++)/*output each array element's value*/

{ Console.WriteLine("Element[{0}] = {1}", j, n[j]); }

Console.ReadKey();

}

}

64

Accessing N-dimensional array element:

Getting element value example:

Setting element value example:

nDimensionalArray[index1, … , indexn]

int[,] array = {{1, 2}, {3, 4}}int element11 = array[1, 1]; //element11 = 4

int[,] array = new int[3, 4];for (int row=0; row<array.GetLength(0); row++)for (int col=0; col<array.GetLength(1); col++)array[row, col] = row + col;

Number of rows

Number of col

65

int rows = int.Parse(Console.ReadLine());int columns = int.Parse(Console.ReadLine());int[,] matrix = new int[rows, columns];String inputNumber;for (int row=0; row<rows; row++){for (int column=0; column<cols; column++){Console.Write("matrix[{0},{1}] = ",row, column);inputNumber = Console.ReadLine();matrix[row, column] = int.Parse(inputNumber);

}}

66

Page 12: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 12

Printing a matrix on the console:

for (int row=0; row<matrix.GetLength(0); row++){for (int col=0; col<matrix.GetLength(1); col++){Console.Write("{0} ", matrix[row, col]);

}Console.WriteLine();

}

67

Can have standard C-style jagged arraysint[] array = new int[30];

int[][] array = new int[2][];

array[0] = new int[100];

array[1] = new int[1];

◦ Stored in random parts of the heap

◦ Stored in row major order

68

02-99

69

List<T>

Dynamic Arrays

70

Lists are arrays that resize dynamically◦ When adding or removing elements◦ Also have indexers ( like Array)◦ T is the type that the List will hold

E.g. List<int> will hold integers

List<object> will hold objects

Basic Methods and Properties◦ Add(T element) – adds new element to the end◦ Remove(element) – removes the element ◦ Count – returns the current size of the List

71

List<int> intList=new List<int>();for( int i=0; i<5; i++){

intList.Add(i);}

72

int[] intArray=new int[5];for( int i=0; i<5; i++){

intArray[i] = i;}

Is the same as

The main difference

When using lists we don't have to know the exact number of elements

Page 13: Introduction to Programming - EEMB DERSLEROct 03, 2010  · EEE-425 Programming Languages (2013) 5 25 SalesTax program 26 A program that allows user input is an interactive program

9/25/2017

EEE-425 Programming Languages (2013) 13

73

List<string> days = new List<string>();//Add to the listdays.Add("Monday");days.Add("Tuesday");days.Add("Saturday");//reverse the listdays.Reverse();//to learn how many elements it hasConsole.WriteLine("The number of Elements:{0}", days.Count);//Remove from the Listdays.Remove("Tuesday");foreach (string eleman in days){

Console.WriteLine(eleman);}

Lets have an array with capacity of 5 elements

If we want to add a sixth element ( we have already added 5) we have to do

With List we simply do

int[] intArray=new int[5];

int[] intArray = new int[5];int newValue = 99;int[] copyArray = intArray;intArray = new int[6];

for (int i = 0; i < 5; i++) copyArray[i] = i;for (int i = 0; i < 5; i++) intArray[i] = copyArray[i];

intArray[5] = newValue;

for (int i = 0; i < 6; i++) Console.WriteLine(intArray[i]);

list.Add(newValue);

74

int newValue = 99;List<int> intList = new List<int>();

for (int i = 0; i < 5; i++){

intList.Add(i);}intList.Add(newValue);

for (int i=0; i<6; i++) Console.WriteLine(intList[i]);

Sometimes we must copy the values from one array to another one◦ If we do it the intuitive way

◦ // Copy the source to the target. //

◦ Array.Copy(source, target, n);

n size of the array

75

Questions?

Prof. Roger Crawfis

◦ http://www.cse.ohio-state.edu/~crawfis/cse459_CSharp/index.html

◦ Pls listen the podcast about the chapter 2

◦ These slides are changed and modified

Programming C#, 4th Edition - Jesse Liberty –Chapter 2

77