+ All Categories
Home > Documents > 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C#...

1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C#...

Date post: 29-Dec-2015
Category:
Upload: aileen-strickland
View: 217 times
Download: 1 times
Share this document with a friend
Popular Tags:
86
1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)
Transcript
Page 1: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

1

INF160 IS Development Environments AUBG, COS dept

Lecture 03Title:

Tutorial Introduction to C#(Extract from Syllabus)

Page 2: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

2

Lecture Contents:C# program – general definition/descriptionC# program – basic structureC# program – demo exampleDetailed description of C# as a conventional

programming language

Page 3: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

3

To students with skills in C# Write a program - Tester for factorial, greatest common divisor, Fibonacci series

number PRELUDE: To compute Fibonacci series nnumber you need a method like this header int Fibonacci( int n ) { … } To compute factorial you need a method like this header int Factorial( int n ) { … } To compute greatest common divisor you need a method like this header int GCD( int m, int n ) { … }

Page 4: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

4

Program – definition/description Program: An organized list of instructions that, when executed,

causes the computer to behave in a predetermined manner.

C# program: Collection of one or more classes, one of which has method titled public static void Main(string[] args).

C# class: mechanism that allows to combine data and operations /named methods/ on that data into a single unit.

C# method: Set of instructions designed to accomplish a specific task.

In OOD the final C# program is a collection of interacting objects /instances of classes/.

Page 5: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

5

C# Program – basic structure

C# programs can consist of one or more files.Each file can contain zero or more

namespaces.A namespace can contain types such as

classes, structs, interfaces, enumerations, and delegates, in addition to other namespaces.

The following is the skeleton of a C# program that contains all of these elements.

Page 6: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

6

‘Review:VB Program – basic structure<Imports declarations><Module heading> Sub Main() <definition/declaration

statements><executable statements>

End Sub<Module end delimiter>

‘ Review: VB program – demo exampleImports SystemModule thisModule Sub Main() Console.WriteLine(“Hello, World!”)

Console.ReadKey() End SubEnd Module

Review

On

VBASIC

Page 7: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

7

// Review: C++ Program – basic structure <preprocessor directives>using namespace <region>;void main() { <definition/declaration statements> <executable statements> }

// Review: C++ Program – demo example

#include <iostream>using namespace std;void main( ) { cout << “\nHello, World!”; system(“pause”); }

Review

On

C++

Native code

Page 8: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

8

// Review: C++ Program – basic structure <preprocessor directives>using namespace <region>;void main() { <definition/declaration statements> <executable statements> }

// Review: C++ Program – demo example

#include "stdafx.h"using namespace System;int main( ){ Console::WriteLine("Hello World");

Console::ReadKey(); return 0;}

Review

On

C++

Managed code

Page 9: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

9

// C# Program – basic structure using System;namespace YourNamespace{ class YourClass { }

interface IYourInterface { }

delegate int YourDelegate();

class YourMainClass { static void Main(string[] args) { //Your program starts here... } }}

// C# Program – demo exampleusing System;namespace MyProject { public class Hello {

public static void Main(string[] args) { Console.WriteLine("Hello world in

C#"); Console.ReadLine(); } }}

New:

C#

Page 10: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

10

.

Detailed descriptionof

C# as Conventional Prog Lan

Page 11: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

11

Lecture Contents (new):• Why C# (instead intro)• Anatomy of a C# program

– Sample source text– Namespaces– Comments– Names – identifiers, reserved words, modifiers– Classes – data fields, 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, etc

• Demo programs - examples

Page 12: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

12C# Programming: From Problem Analysis to Program Design 12

Why C#• Conforms closely to C and C++. Has the added power of C++

• Has the rapid graphical user interface (GUI) features of previous versions of Visual Basic

• Has the object-oriented class libraries similar to Java • 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

Page 13: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

13

C# Plang provides features, such as:

OOP, Event driven programming, visual programming strings, graphics, graphical-user-interface (GUI) components, exception handling, multithreading, multimedia (audio, images, animation and video), file processing, database processing, Internet and WWW-based client/server networking and distributed computing.

• C# programs are created using Integrated Development Environment (IDE).

• With the IDE, a programmer can create, run, test and debug C# programs.

• The process of rapidly creating an application using an IDE is typically referred to as Rapid Application Development (RAD).

Page 14: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

14

Anatomy of a C# program:Sample source text

Page 15: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

15

Syntax for simple C# program

// Program start classusing System;namespace space_name{ public class class_name { // Main begins program execution public static void Main(string[] args) { // implementation of method } }}

Page 16: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

16

Hello World! Console Application

Page 17: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

17

Namespaces. The 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. • C# programmers can use the rich set of namespaces provided by

the .NET framework. The namespaces that are defined in the .NET Framework contain preexisting code known as the .NET Framework Class Library Over 2,000 classes included.

• An example of one of the features in namespace System is Console.• In console applications, we use Console.method when we want to

handle standard input, output, and error streams for our applications

Page 18: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

18C# Programming: From Problem Analysis to Program Design 18

Namespace

• Namespaces provide scope for the names defined within the group

• Groups semantically related types under a single umbrella

• System: most important and frequently used namespace

• Can define your own namespace

• Used to avoid naming collisions

• Each namespace enclosed in curly braces: { }

Page 19: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

19C# Programming: From Problem Analysis to Program Design 19

Namespace (continued)

From Example 1-1

line 1 // This is traditionally the first program written.line 2 using System;line 3 namespace HelloWorldProgram line 4 {

line 12 }

Predefined namespace (System) – part of .NET

FCL

User-defined namespace

Body of user-defined namespace

Page 20: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

20

Concole.WriteLine

• In C# statements we normally precede each class name with its namespace name and a period.

• For example, line of source text would normally be:System.Console.WriteLine( "Welcome to C# Programming!" );

for the program to run correctly.• The using System; directive eliminates the need to

specify explicitly the namespace System when using classes in the namespace. This can save time and confusion for programmers.

Page 21: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

21

Anatomy of a C# program: classes

Page 22: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

22

Line 6-12: Class Welcome1

• Line 6-12 class (these lines collectively are called a class definition).

• C# programs consist of pieces called classes,• Classes 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.

Page 23: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

23

Class Welcome1

• The class keyword begins a class definition in C# and is followed immediately by the class name (Welcome1, in this example).

• 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

Page 24: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

24

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 shown:

static void Main(string[] args)

Page 25: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

25

Main

• These applications begin executing at Main, which is known as the entry point of the program.

• The parentheses after Main indicate that Main is a program building block, called a method.

Page 26: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

26

Page 27: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

27

More Choices

public static void Main() { ...}

public static int Main() { ... return 0;}

public static int Main(string[] args) { ... return 0;}

Page 28: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

28

Syntax of body method

• 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).

• The body method includes/contains statements.

Page 29: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

29

Console.WriteLine(“Welcome to C# programming!”);

• 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

Page 30: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

30

Types of Statements

• Declaration statements - describe the data the function needs:

float miles, kms;

const float KM_PER_MILE = 1.609;

• Executable statements - specify the actions the program will take:

Console.WriteLine(“Welcome to C# programming!”);

Page 31: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

31

Anatomy of a C# program:statements, blocks of statements

• { … }

• Block

• Compound statement

Page 32: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

32

Names: 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.

Page 33: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

33C# Programming: From Problem Analysis to Program Design 33

Reserved Words in C#Keywords (or reserved words) are reserved for use by C# and always consist of lowercase letters.

Page 34: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

34C# Programming: From Problem Analysis to Program Design 34

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

Page 35: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

3535Java Programming: From Problem Analysis to Program Design, 4e

Data

Page 36: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

36

Components of a C# programData – by category

• Literals

• Variables

• Constants

Page 37: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

37

Constant Definition

• Named 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 = 3.14159265358979;

Page 38: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

38

Declaring Variables

datatype variablename = initialvalue;• You don’t have to specify an initial value for a variable, although

being able to do so in the declaration statement is useful. 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, however, that 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.

Page 39: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

39

Components of a C# program:Data – by type

• Value types

• Reference types

Page 40: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

40

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.

Page 41: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

41

Page 42: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

42

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)

Page 43: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

43

All types are compatible with object

- can be assigned to variables of type object

- all operations of type object are applicable to them

Page 44: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

44C# Programming: From Problem Analysis to Program Design 44

Predefined Data Types

• Common Type System (CTS) • Divided into two major categories

Figure 2-3 .NET common types

Page 45: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

45C# Programming: From Problem Analysis to Program Design 45

Value and Reference Types

Figure 2-4 Memory representation for value and reference types

Page 46: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

46C# Programming: From Problem Analysis to Program Design 46

Value Types

• Fundamental or primitive data types

Figure 2-5 Value type hierarchy

Page 47: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

47

Integer type

In C#, an integer is a category of types. They are whole numbers, either signed or unsigned.

Page 48: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

48

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.

Page 49: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

49

The String Type

A string is a string of text characters.

The keyword string is an alias for the class System.String.Either may be used to define a string variable.

string aa = "Sofia";String bb = "BG";System.String cc = " AA ";

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.

Page 50: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

50

Class System.String

Can be used as standard type stringstring s = “AUBG";

Note• Strings are immutable (use class StringBuilder if you want to extend a string)• Can be concatenated with +: “COS @ " + 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, ...

Page 51: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

51

Casting Data from One Data Type to Another

Page 52: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

52

Page 53: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

5353Java Programming: From Problem Analysis to Program Design, 4e

Expressions (operands and operators)

Page 54: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

54

Components of a C# program:Expressions (operands)

• Operands

–Literal Values–Constants–Variables – scalar or indexed–Structure member–Function call–Sub expression like ( … )

Page 55: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

55

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.

Page 56: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

56

Page 57: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

57C# Programming: From Problem Analysis to Program Design 57

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

Page 58: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

58C# Programming: From Problem Analysis to Program Design 58

Mixed Expressions (continued)

• Explicit type coercion– Cast– (type) expression– examAverage = (exam1+exam2+exam3) / (double) count;

Int value1 = 0, anotherNumber = 75;double value2 = 100.99, anotherDouble = 100;

value1 = (int) value2; // value1 = 100 value2 = (double) anotherNumber; // value2 = 75.0

Page 59: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

59

Components of a C# program:Executable Statements

Page 60: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

60

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

Page 61: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

61

Passing Literal Values to a Variable

• The syntax of assigning a literal value (a hard-coded value such as 6 or “guitar”) 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 symbol @, like this:

strFilePath = @”c:\Temp”;• When Visual C# encounters the @ symbol after the equal sign as

shown in the preceding example, it knows not to treat slashes in the string as escape sequences.

Page 62: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

62

Decision Structures - Selection

if (condition) statement;

if (condition) statement1; else statement2;

switch statement

Same syntax for C++, C#, and Java

Page 63: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

63

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");

Page 64: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

64

Switch construct

Same syntax for C++, C#, and Java

switch can only be used to compare an expression with different constants.

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 defaultIf no default specified continuation after the switch statement

Page 65: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

65

switch (x) { case 5: Console.Writeline("x is 5"); break; case 99: Console.Writeline("x is 99"); break; default: Console.Writeline("value of x unknown"); break; }

switch(country) {case"Germany":case"Austria": case"Switzerland": language = "German"; break;case"England":case"USA": language = "English"; break;case null: Console.WriteLine("no country specified"); break;default: Console.WriteLine("don't know language of", country);break;}

Page 66: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

66

Page 67: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

67

Loops

for (initialization; condition; in(de)crement){statement;}

while (Boolean expression) {statements}

do {statements}

while (Boolean expression)

foreach statement

Same syntax for C++, C#, and Java

Page 68: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

68

Loops

for (int n=10; n>0; n--){ Console.Write( n ); Console.Write(", "); }

while ( x > 1 ) {  Console.Writeline("x is ");  Console.Writeline( x ); x--; }

do{  Console.Writeline("x is "); Console.Writeline( x ); x--;} while (x !=1 );

Page 69: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

69

foreach statement: For iterating over collections and arrays. foreach can not be used to change the contents of the array

foreach (Type variableName in container){

// statements;}

// array traverse using foreachint[] a = {3, 17, 4, 8, 2, 29}; foreach (int x in a) sum += x;

// string traverse using foreachstring s = "Hello"; foreach (char ch in s) Console.WriteLine(ch);

Page 70: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

7070Java Programming: From Problem Analysis to Program Design, 4e

Control flow - return

Page 71: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

71

Components of a C# program:Routines (methods)

• Main method Already discussed in section classes(methods(statements))

• Same as in C++, Java

Page 72: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

72

Components of a C# program:Routines (methods)

static void Main(string[] args) { Console.WriteLine("Summing numbers result is = {0}", sum(21,30)); Console.WriteLine("Summing numbers result is = {0}", sum(501, 630)); Console.WriteLine("Multiplying numbers result is = {0}", product(1,10)); }

static int sum(int m, int n) { int i, suma = 0; if (m > n) return -1; if (m == n) return m; for (i=m ; i<=n ; i++) suma += i; return suma; }

static int product(int m, int n) { int i, res = 1; if (m > n) return -1; if (m == n) return m; for (i = m; i <= n; i++) res *= i; return res; }

Page 73: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

73

Components of a C# program: Routines (methods)

static int product(int m, int n) { int i, res = 1; if (m > n) return -1; if (m == n) return m; for (i = m; i <= n; i++) res *= i; return res; }

static int sum(int m, int n) { int i, suma = 0; if (m > n) return -1; if (m == n) return m; for (i=m ; i<=n ; i++) suma += i; return suma; }

static void Main(string[] args) { Console.WriteLine("Summing numbers result is = {0}", sum(21,30)); Console.WriteLine("Summing numbers result is = {0}", sum(501, 630));

Console.WriteLine("Multiplying numbers result is = {0}", product(1,10));

}

Page 74: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

74

Components of a C# program:I/O

Page 75: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

75

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(); // will read the input from the keyboard

x = System.Convert.ToInt32(alpha); // and save it in variable x

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

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.

Page 76: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

76

Page 77: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

77

Page 78: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

78

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() );

Page 79: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

79

WriteLine format

• After performing the calculation, line 33 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:

Page 80: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

80

Page 81: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

81

Components of a C# program:Data collections

• Arrays

• Records (C-like structs)

Page 82: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

82

Data Collections

Typical popular Data collections:

• Arrays• Structures

Detailed discussion on arrays and structures presented in separate lectures later

Page 83: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

83

Demo Programs

D

Page 84: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

84

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

Page 85: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

85

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); } }}

Page 86: 1 INF160 IS Development Environments AUBG, COS dept Lecture 03 Title: Tutorial Introduction to C# (Extract from Syllabus)

86

Thank You For

Your Attention!


Recommended