Lab 11 Be sure to put each class in its own file. Put the call by reference sample program in a loop. Prompt for and input a value. Use that value for each of the calls. Display the value before and after each call. Repeat until a negative number is entered. Use the entered values in the parameters when you call the procedures.
// Fig. 7.18: ReferenceAndOutputParameters.cs
// Reference, output and value parameters.
using System;
class ReferenceAndOutputParameters
{
// call methods with reference, output and value parameters
public void DemonstrateReferenceAndOutputParameters(int x)
{
int y = x; // initialize y to 5
int z; // declares z, but does not initialize it
// display original values of y and z
Console.WriteLine( "Original value of y: {0}", y );
//Console.WriteLine( "Original value of z: uninitialized\n" );
// pass y and z by reference
SquareRef( ref y ); // must use keyword ref
// must use keyword out
// display values of y and z after they are modified by
// methods SquareRef and SquareOut, respectively
Console.WriteLine( "Value of y after SquareRef: {0}", y );
SquareOut(out y);
Console.WriteLine( "Value of z after SquareOut: {0}\n", y );
// pass y and z by value
Square( y );
//Square( z );
// display values of y and z after they are passed to method Square
// to demonstrate arguments passed by value are not modified
Console.WriteLine( "Value of y after Square: {0}", y );
//Console.WriteLine( "Value of z after Square: {0}", z );
} // end method DemonstrateReferenceAndOutputParameters
// uses reference parameter x to modify caller's variable
void SquareRef( ref int x )
{
x = x * x; // squares value of caller's variable
} // end method SquareRef
// uses output parameter x to assign a value
// to an uninitialized variable
void SquareOut( out int x )
{
x = 6; // assigns a value to caller's variable
x = x * x; // squares value of caller's variable
} // end method SquareOut
// parameter x receives a copy of the value passed as an argument,
// so this method cannot modify the caller's variable
void Square( int x )
{
x = x * x;
} // end method Square
} // end class ReferenceAndOutputParameters
// Fig. 7.19: ReferenceAndOutputParamtersTest.cs
// Application to test class ReferenceAndOutputParameters.
using System;
class ReferenceAndOutputParamtersTest
{
static void Main( string[] args )
{
int number=1;
ReferenceAndOutputParameters test =
new ReferenceAndOutputParameters();
do
{
Console.WriteLine("\nPlease enter a number!");
number = Convert.ToInt16(Console.ReadLine());
if (number >0)
test.DemonstrateReferenceAndOutputParameters(number);
} while (number > 0) ; //end whille
} // end Main
} // end class ReferenceAndOutputParamtersTest
Wednesday, May 13, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment