Lecture 4 - Md Rezaul Huda Chowdhury

advertisement
By: Md Rezaul Huda Reza
creativereza@yahoo.com
Decision and iteration statements. Methods.
E. I. Teodorescu
UNIVERSITY of South Asia

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’)
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
3
3
UNIVERSITY of South Asia
 Using
decision statements
 Using repetition statements
 Methods in general
 Instance methods and variables
 Code generated by Visual Studio
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
4
4
UNIVERSITY of South Asia
 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
E. I. Teodorescu
Md Rezaul Huda Reza
creativereza@yahoo.com
5
5
Using decision statements
Using repetition statements
E. I. Teodorescu
UNIVERSITY of South Asia
 Central
 Involves

to both selection and iteration constructs
conditional expression - “the test”
Produces a Boolean result
 Declaring


Boolean variable bool
can hold a value that is either true or false
Example
bool someCondition = false;
bool areYouReady = true;
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
7
7
UNIVERSITY of South Asia
Do not confuse the equality operator
==
with the
assignment operator = .
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
8
8
UNIVERSITY of South Asia
 &&
(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
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
9
9
UNIVERSITY of South Asia
 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-way


When expression evaluates to false, statement
following expression is skipped or bypassed
No special statement(s) is included for the
false result
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
10
10
UNIVERSITY of South Asia
One-way Selection Statement
if (boolExpression)
{
statement;
}
Curly brackets are
required with multiple
statements
Try should use them
even if you have one
statement. Why?
Two-way Selection Statement
if (boolExpression)
{
statement;
}
else
{
statement;
}
Either the true statement(s)
executed or the false
statement(s) — but not both
Md Rezaul Huda Reza
creativereza@yahoo.com
11
11
UNIVERSITY of South Asia
int seconds ;
What is the
difference
between “==“
and “=“ ?
if (seconds == 59) {
seconds =0;
}
else {
seconds++;
}
// Note : == is different than =
//Note : you can use Boolean var as
an expresion
if (seconds = 59) { // Compile error
seconds =0;
}
else
…...
bool isReady;
if (isReady == true) // OK
…..
if (isReady) // OK
…...
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
12
12
UNIVERSITY of South Asia
int 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
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
13
13
UNIVERSITY of South Asia
 You
can nest if statements inside other if
statements
if(Condition1)
Statement1;
else if(Condition2)
Statement2;
else if(Condition3)
Statement3;
else
Statement-n;
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
14
14
UNIVERSITY of South Asia
.... // some code before
age = int.Parse(textBox1.Text);
if (age<18) {
label1.Text =
}
else if(18<=age
{
label1.Text =
}
else if(65<=age
{
label1.Text =
}
"to young to drink!";
and age<65)
“Work hard, Party Hard";
and age<100)
“Easy on Work, Still Party Hard";
else
{
label1.Text = “Wow! Tell me your secret";
}
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
15
15
UNIVERSITY of South Asia
 Executes
a set of logic depending on the value of a
given parameter
 Multiple
 Also
selection structure
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
E. I. Teodorescu
Md Rezaul Huda Reza
creativereza@yahoo.com
16
16
UNIVERSITY of South Asia
Switch Statements General Form
switch (controllingExpression)
Selector
expression is an integral
{
or string type expression.
case value1:
statement(s);
Value must be a
break;
of the same type
...
as selector
case valueN:
The embedded
statement(s);
statement(s) is
break; // jump-statement
executed if control is
[default:
transferred to the case
or the default.
statement(s);
break;]
Optional
}
E. I. Teodorescu
Md Rezaul Huda Reza
creativereza@yahoo.com
17
17
UNIVERSITY of South Asia
Switch Statements Example
int n = int.Parse(textBox1.Text);
int cost = 10;
switch(n)
{
case 0:
case 1:
cost +=
break;
case 2:
cost +=
break;
case 3:
cost +=
break;
default:
cost+ =
break;
}
25;
28;
50;
30;
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
18
18
UNIVERSITY of South Asia
 Useful
because you can repeat
instructions with many data sets
repetition or iteration structures
 statements are executed in order, except when
a jump statement is encountered.

 keywords





are used in iteration statements:
while
do
for
foreach – later, when we study collections
in
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
19
19
UNIVERSITY of South Asia
while (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 = BAD
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
20
20
UNIVERSITY of South Asia
do
{
statement;
}
while( conditional
expression);
 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
Md Rezaul Huda Reza
creativereza@yahoo.com
21
21
UNIVERSITY of South Asia
int y = 0;
string s ;
while (y < 3) // No semicolon
{
s= “Number: “ + y ;
y++ ;
}
int y = 0;
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?
What happens in the
do…while loop?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
22
22
UNIVERSITY of South Asia
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?
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?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
23
23
UNIVERSITY of South Asia
 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
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
24
24
UNIVERSITY of South Asia
 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
for(i = 0; i<5; i++) {
s = s + i + “\n”;
}
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
25
25
UNIVERSITY of South Asia
 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);
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
26
26
Defining and Using Methods
E. I. Teodorescu
UNIVERSITY of South Asia
 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 data

Methods: A sequence of statements with a
name;

A piece of code that does something (it has a task)
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
28
28
UNIVERSITY of South Asia
 It
has:

A name: first line stating important information about the
method

A body: Enclosed in a block
 Can
 All

{
}
be called (invoked) one or more times
programs consist of at least one method,
Main( )
 Methods
are defined inside classes
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
29
29
UNIVERSITY of South Asia
Method structure
optional
[Method access] returnType methodName ( [ParametersList]
)
{
optional
//method body statements go here
}
Example:
public int CalculateAge(int y)
{
int birthYear = y;
return 2010-y;
}
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
30
30
UNIVERSITY of South Asia
 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!
Calling a method
result = methodName ( [ParametersList] );
optional
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
31
31
UNIVERSITY of South Asia
 Follow
the rules for creating an identifier

Starts with capital

Sensible name
 Examples

CalculateSalesTax( )

AssignSectionNumber( )

DisplayResults( )

InputAge( )

ConvertInputValue( )
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
32
32
UNIVERSITY of South Asia
 Enclosed
 Include
in curly brackets { }
statements ending in semicolons

Declare variables

Do arithmetic

Call other methods
 Value
returning methods must include return
statement
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
33
33
UNIVERSITY of South Asia

The method header is followed by the method body
// Program.cs
public class Hello
{
public static void Main()
{
Application.Run(new Form1());
}
}
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
34
34
UNIVERSITY of South Asia
 Indicates
what type of value is returned
when the method is completed
 Always
listed immediately before method
name
 void

No value being returned
 return
statement

Required for all non-void methods

Compatible value (with declared type)
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
35
35
UNIVERSITY of South Asia
A

any data type can be a return type
What types do you know?:
bool
char
double
int
object
Short

byte
decimal
float
long
sbyte
string
You must write a return statement inside the method
 Void
= no return type. The return type is set to void
by default.
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
36
36
UNIVERSITY of South Asia
public void Calculate ( )
{
int x = 7;
int y = 3;
var result = 0;
result = x * y;
What is special about it?
}
Is the Calculate() method returning anything?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
37
37
UNIVERSITY of South Asia
Return type
public double CalcSpeed(double m, int h)
{
double miles = m;
int hours = h;
return miles / hours;
}
Compatible value (double)
returned
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
38
38
UNIVERSITY of South Asia
private int AddValues(int x, int y)
{
return x + y ;
If you want a method to return
information you must write a
}
return statement inside the
…….
method!
The return statement is usually
positioned at the end of your method.
Why?
If the return type is “void”, the method doesn’t return
a statement !
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
39
39
UNIVERSITY of South Asia
 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.
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)

Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
40
40
UNIVERSITY of South Asia
Declaring a method with parameters
public int AddValues( int x, int y, int z)
{
return x+y+z;
formal parameters
When the method is declared.
}

 Calling
the method
int r = AddValues(1,2,3) ;
AddValues ( r, AddValues(3,3,3), 3*r );
Exact match of the method’s
Actual arguments
name you are calling (case
When the method is called.
sensitive)
Md Rezaul Huda Reza
41
E. I. Teodorescu
creativereza@yahoo.com
41
UNIVERSITY of South Asia
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

Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
42
42
UNIVERSITY of South Asia
void method1()
{
int myVar;
}
void method2()
{
myVar = 22;
}
int myField;
void method1()
{
myField = 22;
}
void method2()
{
myField++;
}
Will get an error
Is there anything wrong with the given examples?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
43
43
UNIVERSITY of South Asia
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
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
44
44
UNIVERSITY of South Asia
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;
}
2 methods with the
same name!
What are the
signature of these
methods?
………..
x = Add(3, 2)+ Add(4, 5, 6);
string s = “Result= “ + x;
}
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
45
45
UNIVERSITY of South Asia
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;
}
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
46
46
UNIVERSITY of South Asia
 .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( ) method
 ToString( ) method
 The Convert methods




Convert.ToDouble( )
Convert.ToInt32( )
etc
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
47
47
E. I. Teodorescu
UNIVERSITY of South Asia
What is this?
What is the red
“thing”?
What is the role of \n?
MessageBox.Show(
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
49
49
UNIVERSITY of South Asia
Switch Selection
What is s and what is it set to?
What is Parse(s) and what does it do?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
50
50
UNIVERSITY of South Asia
private void button1_Click(object sender, EventArgs e)
{
Event created by double clicking button1
int y = 0;
string s = " ";
do // No semicolon on this line
{
s = s + y + " " + y++ + " " + ++y + "\n";
What is the difference between ++y and y++?
}
while (y < 3);
label1.Text = s;
What would the output be if the condition was y<0
?
}
What will be the output in the label?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
51
51
UNIVERSITY of South Asia
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
52
52
UNIVERSITY of South Asia
What is this?
What is this?
What is this?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
53
53
UNIVERSITY of South Asia
What are they?
name
What is this?
public double ConvertFahranheitToCelsius(int aNumber)
{
result = (5.0 / 9.0) * (aNumber - 32);
return Math.Round(result,2);
}
What is this?
What id Round(…)?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
54
54
UNIVERSITY of South Asia
 When
the button is clicked : ,
inputNumber =
int.Parse(textBoxInput.Text);
labelResult.Text =
inputNumber + " Fahranheit is " +
ConvertFahranheitToCelsius(inputN
umber)+ " Celsius";
Who is this?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
55
55
UNIVERSITY of South Asia
What would happen if the formula is written :
(5/9) * (aNumber – 32)
What will the value of the result variable be ?
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
56
56
UNIVERSITY of South Asia
Available applications on teachmat for week 2:
 doWhileEx


AgeExample


For loop
MethodExample


If statements
ForLoopExample


Parse() method, switch, while
IfElseExample


do...while and while examples
methods, parameters(arguments)
SwitchApp
Md Rezaul Huda Reza
E. I. Teodorescu
creativereza@yahoo.com
57
57
UNIVERSITY of South Asia
Md Rezaul Huda Reza
creativereza@yahoo.com
58
UNIVERSITY of South Asia
Md Rezaul Huda Reza
creativereza@yahoo.com
59
Download