By: Md Rezaul Huda Reza [email protected]. Decision and iteration statements. Methods. E. I....

59
UNIVERSITY OF SOUTH ASIA Lecture 4: By: Md Rezaul Huda Reza [email protected] CSE- 629 VISUAL PROGRAMMING WITH INTERNET)

Transcript of By: Md Rezaul Huda Reza [email protected]. Decision and iteration statements. Methods. E. I....

UNIVERSITY OFSOUTH ASIA

Lecture 4:

By: Md Rezaul Huda [email protected]

CSE- 629VISUAL PROGRAMMING

WITH INTERNET)

E. I. Teodorescu

Decision and iteration statements. Methods.

UNIVERSITY of South Asia

3Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

3

LAST WEEK: VARIABLES

Area in computer memory where a value of a particular data type can be stored Syntax : type identifier(name);

Assigning a value to a variable Syntax : type identifier = expression;

(Note: read ‘=‘ as ‘becomes’)

E. I. Teodorescu 3

UNIVERSITY of South Asia

4Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

4

THIS WEEK…

Using decision statements Using repetition statements Methods in general Instance methods and variables Code generated by Visual Studio

E. I. Teodorescu 4

UNIVERSITY of South Asia

5Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

COMMENTS In-Line Comments (//)

// This is traditionally the first program written. Everything to the right of the slashes ignored by the

compiler. Carriage return (Enter) ends the comment Multi-line Comment (/* */) block comments

/* This is the beginning of a block multi-line comment. It can go on for several lines or just be on a single line. */

Example:

int x = 3 // this is z comment stating that a variable of type integer was

//declared and initialized to 3

5E. I. Teodorescu

E. I. Teodorescu

Using decision statementsUsing repetition statements

UNIVERSITY of South Asia

7Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

7

MAKING DECISIONS Central to both selection and iteration constructs Involves conditional expression - “the test”

Produces a Boolean result Declaring Boolean variable bool

can hold a value that is either true or falseExample

bool someCondition = false;

bool areYouReady = true;

E. I. Teodorescu 7

UNIVERSITY of South Asia

8Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

8

EQUALITY AND RELATIONAL OPERATORS

E. I. Teodorescu 8

Do not confuse the equality operator == with the assignment operator = .

UNIVERSITY of South Asia

9Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

9

LOGICAL OPERATORS && (AND)True if BOTH the conditions are true

|| (OR)True if EITHER of the conditions are

true

! (NOT)Negates a bool – true becomes false,

false becomes true

E. I. Teodorescu 9

UNIVERSITY of South Asia

10Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

10

IF...ELSE SELECTION STATEMENTS Classified as one-way, two-way, or

nested Alternate paths based on result of

conditional expression Expression must be enclosed in

parentheses Produce a Boolean result

One-wayWhen expression evaluates to false,

statement following expression is skipped or bypassed

No special statement(s) is included for the false result

E. I. Teodorescu 10

UNIVERSITY of South Asia

11Md Rezaul Huda [email protected]

m

SELECTION STATEMENTS (IF STATEMENTS)

if (boolExpression) { statement; }

11

Either the true statement(s) executed or the false statement(s) — but not both

if (boolExpression) { statement; }else{ statement; }

One-way Selection Statement Two-way Selection Statement

Curly brackets are required with multiple statements

Try should use them even if you have one statement. Why?

UNIVERSITY of South Asia

12Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

12

IF…ELSE EXAMPLEint seconds ;

if (seconds == 59) {seconds =0;

}else {

seconds++;}

E. I. Teodorescu 12

// Note : == is different than =

if (seconds = 59) { // Compile error seconds =0;

}else

…...

//Note : you can use Boolean var as an expresion

bool isReady;if (isReady == true) // OK

…..if (isReady) // OK

…...

What is the difference

between “==“ and “=“ ?

UNIVERSITY of South Asia

13Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

13

IF…ELSE EXAMPLE 2int hoursWorked =40 ;double payRate;string resultString;pouble payAmount;

if (hoursWorked > 40) { payAmount = (hoursWorked – 40) * payRate * 1.5 + payRate * 40; resultString= “You worked “ + (hoursWorked – 40) + “ hours overtime.”;

resultString = resultString + “ Your payment is ” + payAmount.}else{ payAmount = hoursWorked * payRate; resultString = “ Your payment is ” + payAmount.} // Next line will be executed, whether the expression evaluates true or false

E. I. Teodorescu 13

UNIVERSITY of South Asia

14Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

14

NESTED IF-S You can nest if statements inside other if

statements

if(Condition1)    

Statement1;

else if(Condition2)    

Statement2;

else if(Condition3)    

Statement3; else    

Statement-n;

E. I. Teodorescu 14

UNIVERSITY of South Asia

15Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

15

NESTED IF-S.... // some code before

age = int.Parse(textBox1.Text);

if (age<18) {

label1.Text = "to young to drink!";

}

else if(18<=age and age<65)

{

label1.Text = “Work hard, Party Hard";

}

else if(65<=age and age<100)

{

label1.Text = “Easy on Work, Still Party Hard";

}

else

{

label1.Text = “Wow! Tell me your secret";

}

E. I. Teodorescu 15

UNIVERSITY of South Asia

16Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

SWITCH SELECTION STATEMENTS Executes a set of logic depending on the value

of a given parameter Multiple selection structure Also called case statement Works for tests of equality only Single variable or expression tested

Must evaluate to an integral or string value

Requires the break for any case No fall-through available

16E. I. Teodorescu

UNIVERSITY of South Asia

17Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

Switch Statements General Form

switch (controllingExpression) { case value1:

statement(s); break; . . . case valueN:

statement(s); break; // jump-statement [default:

statement(s); break;]}

Selector expression is an

integral or string type

expression.

Value must be a of the same type

as selector

Optional

The embedded statement(s) is

executed if control is transferred to the

case or the default.

17E. I. Teodorescu

UNIVERSITY of South Asia

18Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

18

int n = int.Parse(textBox1.Text);int cost = 10;

switch(n) { case 0: case 1:

cost += 25; break;

case 2: cost += 28; break;

case 3: cost += 50; break;

default: cost+ = 30; break;

}

E. I. Teodorescu 18

Switch Statements Example

UNIVERSITY of South Asia

19Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

19

LOOPING (REPITITION, ITERATION) Useful because you can repeat

instructions with many data setsrepetition or iteration structures statements are executed in order, except

when a jump statement is encountered. keywords are used in iteration statements:

whiledo for foreach – later, when we study collections in

E. I. Teodorescu 19

UNIVERSITY of South Asia

20Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

20

USING THE WHILE STATEMENTwhile (conditional expression){

statement(s); // the while body

}

The while statement executes a statement or a block of statements until a specified expression evaluates to false

No semicolon after the conditional expression

the test of expression takes place before each execution of the loop

a while loop executes zero or more times.

infinite loop = BADE. I. Teodorescu 20

UNIVERSITY of South Asia

21Md Rezaul Huda [email protected]

m

DO…WHILE STATEMENTS

Post test do statement is executed at least once regardless of

the value of the expression The do statement executes a statement or a

block of statements repeatedly until the expression evaluates to false

21

do { statement;}while( conditional

expression);

UNIVERSITY of South Asia

22Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

22

WHILE AND DO…WHILE EXAMPLE

int y = 0;string s ;while (y < 3) // No semicolon{ s= “Number: “ + y ;

y++ ; }

What is the value of s at the end of the loop?

E. I. Teodorescu 22

int y = 0;string s ;do // No semicolon on this

line{ s= “Number: “ + y ;

y++ ;

}while (y < 3);

What happens in the do…while loop?

UNIVERSITY of South Asia

23Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

23

WHILE AND DO…WHILE EXAMPLE

int y = 3;string s ;while (y < 3) // No semicolon{ s= “Number: “ + y ;

y++ ; }

What is the value of s at the end of the loop?

E. I. Teodorescu 23

int y = 3;string s ;do // No semicolon on this

line{ s= “Number: “ + y ;

y++ ;

}while (y < 3);

What is the value of s at the end of the loop?

UNIVERSITY of South Asia

24Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

24

FOR LOOP executes a statement or a block of

statements repeatedly until a specified expression evaluates to false. Usually associated with counter-controlled types

packages initialization, test, and update all on one line

General form is:for (initializers; conditional expression; iterator){

statement; }

Interpreted as: for (initialize; test; update)

statement

E. I. Teodorescu 24

UNIVERSITY of South Asia

25Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

25

FOR STATEMENT The for statement executes the statement

repeatedly as follows: First, the initializers are evaluated.Then, while the expression evaluates to true, the

statement(s) are executed and the iterators are evaluated.

When the expression becomes false, control is transferred outside the loop.

Example

E. I. Teodorescu 25

for(i = 0; i<5; i++) { s = s + i + “\n”; }

UNIVERSITY of South Asia

26Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

26

NESTED LOOPS Loop can be nested inside an outer loop

Inner nested loop is totally completed before the outside loop is tested a second time

Example:

int inner;string s = “ “;for (int outer = 0; outer < 3; outer++){ for(inner = 10; inner > 5; inner --) { s = s + outer + “ “ + inner + “\n”; }}MessageBox.Show(s);

E. I. Teodorescu 26

E. I. Teodorescu

Defining and Using Methods

UNIVERSITY of South Asia

28Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

28

METHODS Also known as functions Used to define behaviour. A method

does something active Question: What is the difference

between a method and a variable?Variables simple store dataMethods: A sequence of statements

with a name; A piece of code that does something (it has a

task)

E. I. Teodorescu 28

UNIVERSITY of South Asia

29Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

29

ANATOMY OF A METHOD

It has: A name: first line stating important information

about the methodA body: Enclosed in a block { }

Can be called (invoked) one or more times All programs consist of at least one method,

Main( )

Methods are defined inside classes

E. I. Teodorescu 29

UNIVERSITY of South Asia

30Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

30

DEFINING A METHOD.

[Method access] returnType methodName ( [ParametersList] )

{ //method body statements go here}

E. I. Teodorescu 30

Method structure

Example:

optional

optional

public int CalculateAge(int y)

{

int birthYear = y;

return 2010-y;

}

UNIVERSITY of South Asia

31Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

31

CALLING A METHOD

Q: What is the purpose of declaring/creating methods? So you can use them at a later stage! They are “handy” pieces of code that do something

Use a method by calling it from another part of the code.

A method can be called as many times as you wish A method should be called at least once

• otherwise not much use to it!

E. I. Teodorescu 31

Calling a method result = methodName ( [ParametersList] );

optional

UNIVERSITY of South Asia

32Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

32

METHOD NAMES Follow the rules for creating an

identifier Starts with capitalSensible name

ExamplesCalculateSalesTax( )AssignSectionNumber( )DisplayResults( ) InputAge( )ConvertInputValue( )

E. I. Teodorescu 32

UNIVERSITY of South Asia

33Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

33

METHOD BODY Enclosed in curly brackets { }

Include statements ending in semicolonsDeclare variables

Do arithmetic

Call other methods

Value returning methods must include return statement

E. I. Teodorescu 33

UNIVERSITY of South Asia

34Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

34

METHOD BODY 2 The method header is followed by the method

body

E. I. Teodorescu 34

// Program.cs

public class Hello{

}

public static void Main() {

Application.Run(new Form1());}

UNIVERSITY of South Asia

35Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

35

THE RETURN TYPE Indicates what type of value is

returned when the method is completed

Always listed immediately before method name

voidNo value being returned

return statementRequired for all non-void methods Compatible value (with declared type)

E. I. Teodorescu 35

UNIVERSITY of South Asia

36Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

36

RETURN TYPE A any data type can be a return type

What types do you know?: bool bytechar decimaldouble floatint longobject sbyteShort string

You must write a return statement inside the method

Void = no return type. The return type is set to void by default.

E. I. Teodorescu 36

UNIVERSITY of South Asia

37Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

37

METHOD EXAMPLE

public void Calculate ( ){

int x = 7; int y = 3; var result = 0;

result = x * y; }

E. I. Teodorescu 37

What is special about it?

Is the Calculate() method returning anything?

UNIVERSITY of South Asia

38Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

38

RETURN TYPE

public double CalcSpeed(double m, int h){ double miles = m; int hours = h;

return miles / hours;}

E. I. Teodorescu 38

Return type

Compatible value (double) returned

UNIVERSITY of South Asia

39Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

39

WRITING RETURN STATEMENTS

private int AddValues(int x, int y){

return x + y ;}

…….

E. I. Teodorescu 39

The return statement is usually positioned at the end of your method. Why?

If you want a method to return information you must write a return statement inside the method!

If the return type is “void”, the method doesn’t return a statement !

UNIVERSITY of South Asia

40Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

40

PARAMETERS (ARGUMENTS) Why do we want to use parameters?

you may want a method to do something, but that method needs some external data

The external data can be different every time you call that method.

E. I. Teodorescu 40

public double CalcSpeed(double m, int h){ double miles = m; int hours = h;

return miles / hours;}double porscheSpeed = CalcSpeed(260.0, 1)double tractorSpeed = CalcSpeed(80.0, 2)

UNIVERSITY of South Asia

41Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

41

PARAMETERS (CONTINUED) Declaring a method with parameterspublic int AddValues( int x, int y, int z){ return x+y+z;}

Calling the method

int r = AddValues(1,2,3) ; AddValues ( r, AddValues(3,3,3), 3*r );

E. I. Teodorescu 41

formal parametersWhen the method is declared.

Actual argumentsWhen the method is called.

Exact match of the method’s name you are calling (case sensitive)

UNIVERSITY of South Asia

42Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

42

APPLYING SCOPE. The scope of a variable is the region of the

program where the variable is usable Local scope

Local to a method Declared inside the method body Used only inside the method body !! Local variables must be instantiated

Class scope – next lecture Declared inside the class body, but not inside a

method In C# are called fields (class variables in java) Use fields(class variables) to share information

between methods

E. I. Teodorescu 42

UNIVERSITY of South Asia

43Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

43

QUESTIONvoid method1()

{int myVar;

}void method2()

{ myVar =

22;}

E. I. Teodorescu 43

int myField;void method1()

{myField = 22;}

void method2(){ myField++;}

Will get an error

Is there anything wrong with the given examples?

UNIVERSITY of South Asia

44Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

44

OVERLOADING METHODS A method has the ability to behave differently

according to the types and number of parameters that are passed to it.

C# allows you to define different versions of a method, and the compiler will automatically select the most appropriate one based on the parameters supplied. methods with the same name but with a different set

of parameters signature of a method = Each combination of

parameter types

E. I. Teodorescu 44

UNIVERSITY of South Asia

45Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

45

CALLING OVERLOADED METHODS

public class AddingNumbers

{

int x;

public int Add(int a, int b)

{

return a+b;

}

public int Add(int a, int b, int c)

{

return a+b+c;

}

………..x = Add(3, 2)+ Add(4, 5, 6);

string s = “Result= “ + x;

}E. I. Teodorescu 45

2 methods with the same name!

What are the signature of these

methods?

UNIVERSITY of South Asia

46Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

46

SPOT THE ERROR(S)!public class AddingNumbers

{

double x;

public int AddNumbers(int a, int b) {

return a+b;

}

public int AddNumbers(int c, int d) {

return d+c;

}

public int AddNumbers(int f, double g) {

return d+c;

}

public int AddNumbers(double f, double g) {

return f+g;

}

………..

x = AddNumbers (3, 2)+ AddNumbers (4, 5) + AddNumbers (3.2, 2.0)+

AddNumbers (4, 5.0); ;

string s = “Result= “ + x;

}E. I. Teodorescu 46

UNIVERSITY of South Asia

47Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

47

SOME METHODS YOU KNOW .NET Framework Class Library (FCL) is in

effect code that can be reused. Inside this there are many reusable

methods Last lecture we used some FCL methods

to convert types. Can you remember any?Parse( ) methodToString( ) methodThe Convert methods

Convert.ToDouble( ) Convert.ToInt32( ) etc

E. I. Teodorescu 47

E. I. Teodorescu

CODE EXAMPLES IN VS

QUESTIONING SESSION

UNIVERSITY of South Asia

49Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

49

IF EXAMPLE

E. I. Teodorescu 49

What is the role of \n?

What is the red “thing”?

MessageBox.Show(

What is this?

UNIVERSITY of South Asia

50Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

50E. I. Teodorescu 50

What is s and what is it set to?

What is Parse(s) and what does it do?

Switch Selection

UNIVERSITY of South Asia

51Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

51

DO … WHILE EXAMPLE.

private void button1_Click(object sender, EventArgs e) { int y = 0; string s = " ";

do // No semicolon on this line { s = s + y + " " + y++ + " " + ++y + "\n";

}

while (y < 3);

label1.Text = s;

}

E. I. Teodorescu 51

What is the difference between ++y and y++?

Event created by double clicking button1

What would the output be if the condition was y<0 ?

What will be the output in the label?

UNIVERSITY of South Asia

52Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

52

WRITING A CURRENCY CONVERTER APPLICATION.

E. I. Teodorescu 52

UNIVERSITY of South Asia

53Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

53E. I. Teodorescu 53

What is this?

What is this?

What is this?

UNIVERSITY of South Asia

54Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

54

DECLARING A METHOD

public double ConvertFahranheitToCelsius(int aNumber)

{ result = (5.0 / 9.0) * (aNumber - 32); return Math.Round(result,2); }

E. I. Teodorescu 54

nameWhat are they? What is this?

What id Round(…)?What is this?

UNIVERSITY of South Asia

55Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

55

ADDING THE BEHAVIOUR OF THE BUTTON When the button is clicked : , inputNumber = int.Parse(textBoxInput.Text);

labelResult.Text = inputNumber + " Fahranheit is

" + ConvertFahranheitToCelsius(inputNumber)+ " Celsius";

E. I. Teodorescu 55

Who is this?

UNIVERSITY of South Asia

56Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

56

QUESTION

E. I. Teodorescu 56

What would happen if the formula is written :(5/9) * (aNumber – 32)

What will the value of the result variable be ?

UNIVERSITY of South Asia

57Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

57

CODE AVAILABLE ON TEACHMATAvailable applications on teachmat for week 2: doWhileEx

do...while and while examples AgeExample

Parse() method, switch, while IfElseExample

If statements ForLoopExample

For loop MethodExample

methods, parameters(arguments) SwitchApp

E. I. Teodorescu 57

UNIVERSITY of South Asia

58Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

58

ANY QUESTION ? ? ?

UNIVERSITY of South Asia

59Md Rezaul Huda [email protected]

m

UNIVERSITY of South Asia

59

THANK YOU