EEE-425 Programming Languages (2013) 1

Similar documents
Visual C# Instructor s Manual Table of Contents

Introduction to C# Applications

Chapter 2: Using Data

DigiPen Institute of Technology

Introduce C# as Object Oriented programming language. Explain, tokens,

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

.Net Technologies. Components of.net Framework

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Introduction To C#.NET

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Introduction to Programming Using Java (98-388)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Chapter 1 Getting Started

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Language Specification

Industrial Programming

1 Lexical Considerations

Table of Contents Preface Bare Necessities... 17

Lexical Considerations

Full file at

C # Language Specification

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

C# Language Specification

Lexical Considerations

Review of the C Programming Language

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

egrapher Language Reference Manual

Review of the C Programming Language for Principles of Operating Systems

3. Java - Language Constructs I

DAD Lab. 1 Introduc7on to C#

Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

The Warhol Language Reference Manual

Chapter 6. Simple C# Programs

Chapter 2: Using Data

Java+- Language Reference Manual

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Chapter 2: Basic Elements of C++

Decaf Language Reference Manual

Course Outline. Introduction to java

UNIT- 3 Introduction to C++

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32

IT 374 C# and Applications/ IT695 C# Data Structures

Absolute C++ Walter Savitch

Lesson 02 Working with Data Types MIT 31043, Visual Programming By: S. Sabraz Nawaz

Basics of Java Programming

6.096 Introduction to C++ January (IAP) 2009

C++ Programming: From Problem Analysis to Program Design, Third Edition

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Java Overview An introduction to the Java Programming Language

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Brief Summary of Java

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS201 - Introduction to Programming Glossary By

CS260 Intro to Java & Android 03.Java Language Basics

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

CSCI 1061U Programming Workshop 2. C++ Basics

CS313D: ADVANCED PROGRAMMING LANGUAGE

Array. Prepared By - Rifat Shahriyar

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Operators and Expressions

C#: framework overview and in-the-small features

COMP 202 Java in one week

Objectives. In this chapter, you will:

Chapter 2 Basic Elements of C++

A Comparison of Visual Basic.NET and C#

Short Notes of CS201

Java Primer 1: Types, Classes and Operators

Computer Programming : C++

Problem Solving with C++

3. Java - Language Constructs I

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Tokens, Expressions and Control Structures

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Client-Side Web Technologies. JavaScript Part I

The C++ Language. Arizona State University 1

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Preview from Notesale.co.uk Page 6 of 52

CS201 Some Important Definitions

4 Programming Fundamentals. Introduction to Programming 1 1

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Pace University. Fundamental Concepts of CS121 1

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

NOIDATUT E Leaning Platform

G Programming Languages - Fall 2012

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Microsoft Visual C# Step by Step. John Sharp

Transcription:

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 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 3 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) 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 5 6 EEE-425 Programming Languages (2013) 1

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 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 7 8 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 You can display variable values by using the variable name within a WriteLine() method call 9 10 Program that displays a string and a variable value A format string is a string of characters that contains one or more placeholders. For example: Console.WriteLine( The money is 0 exactly, somemoney); 11 12 EEE-425 Programming Languages (2013) 2

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); 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 (--) 13 14 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 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 15 16 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 Format Specifiers 17 18 EEE-425 Programming Languages (2013) 3

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 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 19 20 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 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 21 22 Program that compares two strings using == Program that compares two strings using Equals() and Compares() 23 24 EEE-425 Programming Languages (2013) 4

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 SalesTax program 25 26 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); 27 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 A a = new A(); A b = a; memory a fields in class A for instance a b 29 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 137 a int a = 137; 137 b int b = a; 30 EEE-425 Programming Languages (2013) 5

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 memory 137 a int a = 137; object o1 = a; object o2 = o1; // Boxing int b = (int)o2; //Unboxing int 137 137 o1 b o2 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 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. 33 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. 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. 35 36 EEE-425 Programming Languages (2013) 6

For variable number of parameters public void f(int x, params char[] ar); call f(1), f(1, s ), f(1, s, f ), f(1, sf.tochararray()); If, else while Must be the last argument in the list for foreach 37 38 The typical for loop syntax is: for (initialization; test; update) statements; Consists of Initialization statement Boolean test expression Update statement Loop body block 39 40 The typical foreach loop syntax is: Iteration over a Collection foreach (Type element in collection) statements; 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 41 42 EEE-425 Programming Languages (2013) 7

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 Print all elements of a string[] array: string[] capitals = "Ankara", "Washington", "London", "Paris" ; foreach (string capital in capitals) Console.WriteLine(capital); 43 44 Live Demo examples 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: 45 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; 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. 47 48 EEE-425 Programming Languages (2013) 8

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) Element of an array Array of 5 elements 0 1 2 3 4 Element index 49 50 Declaration defines the type of the elements Square brackets [] mean "array" Examples: Declaring array of integers: int[] myintarray; Declaring array of strings: string[] mystringarray; 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; 51 52 Use the operator new Specify array length Example creating (allocating) array of 5 integers: myintarray = new int[5]; myintarray 0 1 2 3 4 managed heap (dynamic memory) Creating and initializing can be done together: myintarray = 1, 2, 3, 4, 5; 0 1 2 3 4 myintarray managed heap (dynamic memory) The new operator is not required when using curly brackets initialization 53 54 EEE-425 Programming Languages (2013) 9

Creating an array that contains the names of the days of the week string[] daysofweek = "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ; Live Demo 55 56 Accessing Array Elements Read and Modify Elements by Index 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 57 58 int[] array = new int[] 1, 2, 3, 4, 5; // Get array size int length = array.length; // Declare and create the reversed array int[] reversed = new int[length]; Reading and Printing Arrays on the Console // Initialize the reversed array for (int index = 0; index < length; index++) reversed[length-index-1] = array[index]; 59 60 EEE-425 Programming Languages (2013) 10

First, read from the console the length of the array int n = int.parse(console.readline()); Next, create the array of given size and read its elements in a for loop 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: 1 2 2 1 1 2 3 2 1 1 2 3 3 2 1 bool issymmetric = true; for (int i=0; i<(array.length+1)/2; i++) if (array[i]!= array[n-i-1]) issymmetric = false; 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 array for (int index = 0; index < array.length; index++) // Print each element on a separate line Console.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: ndimensionalarray[index1,, indexn] Getting element value example: int[,] array = 1, 2, 3, 4 int element11 = array[1, 1]; //element11 = 4 Number of rows Setting element value example: 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 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 EEE-425 Programming Languages (2013) 11

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(); Can have standard C-style jagged arrays int[] 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 67 68 02-99 Dynamic Arrays List<T> 69 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 List<int> intlist=new List<int>(); for( int i=0; i<5; i++) intlist.add(i); Is the same as The main difference int[] intarray=new int[5]; for( int i=0; i<5; i++) intarray[i] = i; When using lists we don't have to know the exact number of elements 71 72 EEE-425 Programming Languages (2013) 12

List<string> days = new List<string>(); //Add to the list days.add("monday"); days.add("tuesday"); days.add("saturday"); //reverse the list days.reverse(); //to learn how many elements it has Console.WriteLine("The number of Elements:0", days.count); //Remove from the List days.remove("tuesday"); foreach (string eleman in days) Console.WriteLine(eleman); Lets have an array with capacity of 5 elements int[] intarray=new int[5]; If we want to add a sixth element ( we have already added 5) we have to do 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]); With List we simply do list.add(newvalue); 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]); 73 74 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 Questions? 75 Prof. Roger Crawfis http://www.cse.ohiostate.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 EEE-425 Programming Languages (2013) 13