Variable Scope And Duration, Lecture Slide - Computer Science, Slides of C programming

Parameter Passing, Methods Overloading, Local Variables, Summary, Design, Program Development Process, Implementation, Testing, Calendar, Requirement, Stepwise Refinement

Typology: Slides

2010/2011

Uploaded on 10/06/2011

christina
christina 🇺🇸

4.6

(23)

393 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS 112 Introduction to
Programming
Lecture #14:
Variable Scope and Duration;
Program Development Process
and Stepwise Refinement
http://flint.cs.yale.edu/cs112/
2
Outline
rAdmin. and review
qMore about defining and using methods
¦Method header
¦Overloading and signature
¦Method parameter passing
¦Method body
¦Variable scope and duration
rProgram development process
rStepwise refinement using the Calendar
program as an example
3
Review: Method Overloading
rMethod overloading is the process of using
the same method name for multiple methods
mUsually perform the same task on different data types
rThe compiler determines which version of the
method is being invoked by analyzing the
parameters, which form the signature of a
method
mIf multiple methods match a method call, the compiler picks
the best match
mIf none matches exactly but some implicit conversion can be
done to match a method, then the method is invoked with
implicit conversion.
4
More Examples
double TryMe ( int x )
{
return x + 5;
}
double TryMe ( double x )
{
return x * .375;
}
double TryMe (double x, int y)
{
return x + y;
}
TryMe( 1 );
TryMe( 1.0 );
TryMe( 1.0, 2);
TryMe( 1, 2);
TryMe( 1.0, 2.0);
5
Recap: Parameter Passing
rTwo types of parameter passing:
mCall by value: a modification on the formal argument has no
effect on the actual argument
mCall by reference: a modification on the formal argument can
change the actual argument
mDepend on the type of a formal argument
rFor C# simple data types, it is call-by-value
rChange to call-by-reference: ref or out
mThe ref or out keyword is required in both method
declaration and method call
mref requires that the parameter be initialized before enter a
method
mout requires that the parameter be set before return from a
method
Outline
RefOutTest.cs
1// RefOutTest.cs
2// Demonstrating ref and out parameters.
3
4using System;
5using System.Windows.Forms;
6
7class RefOutTest
8 {
9// x is passed as a ref int (original value will change)
10 static void SquareRef( ref int x )
11 {
12 x = x * x;
13 }
14
15 // original value can be changed and initialized
16 static void SquareOut( out int x )
17 {
18 x = 6;
19 x = x * x;
20 }
21
22 // x is passed by value (original value not changed)
23 static void Square( int x )
24 {
25 x = x * x;
26 }
27
28 static void Main( string[] args )
29 {
30 // create a new integer value, set it to 5
31 int y = 5;
32 int z; // declare z, but do not initialize it
33
When passing a value by reference
the value will be altered in the rest
of the program as well
Since x is passed as out the variable
can then be initialed in the method
Since not specified, this value is defaulted to being
passed by value. The value of x will not be changed
elsewhere in the program because a duplicate of the
variable is created.
Since the methods are void
they do not need a return value.
pf3
pf4

Partial preview of the text

Download Variable Scope And Duration, Lecture Slide - Computer Science and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #14:

Variable Scope and Duration;

Program Development Process

and Stepwise Refinement

http://flint.cs.yale.edu/cs112/

Outline

r Admin. and review

q More about defining and using methods

¶ Method header

¶ Overloading and signature

¶ Method parameter passing

¶ Method body

¶ Variable scope and duration

r Program development process

r Stepwise refinement using the Calendar

program as an example

Review: Method Overloading

r Method overloading is the process of using

the same method name for multiple methods

m Usually perform the same task on different data types

r The compiler determines which version of the

method is being invoked by analyzing the

parameters, which form the signature of a

method

m If multiple methods match a method call, the compiler picks

the best match

m If none matches exactly but some implicit conversion can be

done to match a method, then the method is invoked with

implicit conversion.

More Examples

double TryMe ( int x )

return x + 5;

double TryMe ( double x )

return x * .375;

double TryMe (double x, int y)

return x + y;

TryMe( 1 );

TryMe( 1.0 );

TryMe( 1.0, 2);

TryMe( 1, 2);

TryMe( 1.0, 2.0);

Recap: Parameter Passing

r Two types of parameter passing:

m Call by value: a modification on the formal argument has no

effect on the actual argument

m Call by reference: a modification on the formal argument can

change the actual argument

m Depend on the type of a formal argument

r For C# simple data types, it is call-by-value

r Change to call-by-reference: ref or out

m The ref or out keyword is required in both method

declaration and method call

m ref requires that the parameter be initialized before enter a

method

m out requires that the parameter be set before return from a

method

Outline

RefOutTest.cs

1 // RefOutTest.cs 2 // Demonstrating ref and out parameters. 3 4 using System; 5 using System.Windows.Forms; 6 7 class RefOutTest 8 { 9 // x is passed as a ref int (original value will change) 10 static void SquareRef( ref int x ) 11 { 12 x = x * x; 13 } 14 15 // original value can be changed and initialized 16 static void SquareOut( out int x ) 17 { 18 x = 6; 19 x = x * x; 20 } 21 22 // x is passed by value (original value not changed) 23 static void Square( int x ) 24 { 25 x = x * x; 26 } 27 28 static void Main( string[] args ) 29 { 30 // create a new integer value, set it to 5 31 int y = 5; 32 int z; // declare z, but do not initialize it 33

When passing a value by reference

the value will be altered in the rest

of the program as well

Since x is passed as out the variable

can then be initialed in the method

Since not specified, this value is defaulted to being

passed by value. The value of x will not be changed

elsewhere in the program because a duplicate of the

variable is created.

Since the methods are void

they do not need a return value.

Outline

RefOutTest.cs

34 // display original values of y and z 35 string output1 = "The value of y begins as " 36 + y + ", z begins uninitialized.\n\n\n"; 37 38 // values of y and z are passed by value 39 RefOutTest.SquareRef( ref y ); 40 RefOutTest.SquareOut( out z ); 41 42 // display values of y and z after modified by methods 43 // SquareRef and SquareOut 44 string output2 = "After calling SquareRef with y as an " + 45 "argument and SquareOut with z as an argument,\n" + 46 "the values of y and z are:\n\n" + 47 "y: " + y + "\nz: " + z + "\n\n\n"; 48 49 // values of y and z are passed by value 50 RefOutTest.Square( y ); 51 RefOutTest.Square( z ); 52 53 // values of y and z will be same as before because Square 54 // did not modify variables directly 55 string output3 = "After calling Square on both x and y, " + 56 "the values of y and z are:\n\n" + 57 "y: " + y + "\nz: " + z + "\n\n"; 58 59 MessageBox.Show( output1 + output2 + output3, 60 "Using ref and out Parameters", MessageBoxButtons.OK, 61 MessageBoxIcon.Information ); 62 63 } // end method Main 64 65 } // end class RefOutTest

The calling of the SquareRef

and SquareOut methods

The calling of the

SquareRef and SquareOut

methods by passing the

variables by value

Outline

RefOutTest.cs

Program Output

Outline

r Admin. and review

q More about defining and using methods

¶ Method header

¶ Overloading and signature

¶ Method parameter passing

ÿ Method body

ÿ Variable duration and scope

r Program development process

r Stepwise refinement using the Calendar

example

Variable Duration and Scope

r Duration

m Recall: a variable occupies some memory space

m The amount of time a variable exists in memory is

called its duration

r Scope

m The section of a program in which a variable can

be accessed (also called visible)

m A variable can have two types of scopes

• Class scope

– From when created in class

– Until end of class (})

– Visible to all methods in that class

• Block scope

Local Variables

r Created when

declared

r Until end of

block, e.g., }

r Only used

within that

block

class Test { const int NoOfTries = 3; // class scope static int Square ( int x ) // formal arg. { // NoOfTries and x in scope int square = x * x; // square local var. // NoOfTries, x and square in scope return square; } static int AskForAPositiveNumber ( int x ) { // NoOfTries and x in scope for ( int i = 0; i < NoOfTries; i++ ) { // NoOfTries, i, and x in scope string str = Console.ReadLine(); // NoOfTries, i, x, and str in scope int temp = Int32.Parse( str ); // NoOfTries, i, x, str and temp in scope if (temp > 0) return temp; } // now only x and NoOfTries in scope return 0; } // AskForPositiveNumber static void Main( string[] args ) {…} }

Example: Scope.cs

Summary

r Scope

m A local variable is accessible after it is declared

and before the end of the block

m A class variable is accessible in the whole class

m Parameter passing with ref and out makes

some variables aliases of others

r Duration

m A local variable may exist but is not accessible in

a method,

• e.g., method A calls method B, then the local variables in

method A exist but are not accessible in B.

Outline

r Admin. and review

q More about defining and using methods

q Program design

ÿ Stepwise refinement process using the

Calendar program as an example

Calendar: Requirements

r Get a year from the user, the earliest year

should be 1900

r Get a month from the user, the input should

be from 0 to 12

m If 0, print calendar for all 12 months

m Otherwise, print the calendar of the month of the

year

Design: Stepwise Refinement

r Stepwise refinement (or top-down design)

m Start with the main program

m Think about the problem as a whole and identify

the major pieces of the entire task

m Work on each of these pieces one by one

m For each piece, think what is its major sub-pieces,

and repeat this process

Design

year = GetYearFromUser()

month = GetMonthFromUser()

month ?= 0

PrintMonth(month, year) PrintYear(year)

no

yes

PrintMonth( month, year )

January 1900

Sun Mon Tue Wed Thu Fri Sat