Quite often we will need to tell our function some special data to work with. For example, if we often write real numbers on screen, we can create an auxiliary function to help us to show them with a certain format. We could do it as follows:
public static void displayRealNumber( float n )
{
Console.WriteLine( n.ToString("#.###") );
}
And this function could be used from the body of our program, like this:
displayRealNumber(2.3f);
(remember that the suffix "f" is used to
tell the compiler to treat that number as a "float", because
otherwise if would be considered as "double", and we would get a
compilation error).
The full program could look like:
/*---------------------------*/
/* C# Example #48: */
/* example48.cs */
/* */
/* Function */
/*
"displayRealNumber"
*/
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example48
{
public static void displayRealNumber( float n )
{
Console.WriteLine( n.ToString("#.###") );
}
public static void Main()
{
float x;
x= 5.1f;
Console.WriteLine("The first real number is:");
displayRealNumber(x);
Console.WriteLine("and another:");
displayRealNumber(2.3f);
}
}
These additional data that the we indicate to the function is what we call its "parameters". As shown in the example, we must provide a name for each parameter (there may be several) and a data type. If more we need than one parameter, we indicate the type and name for each one, and separate them with commas:
public static void displaySum ( int x, int y ) {
...
}
Suggested exercises:
· (5.3.1) Create a function to draw a square on the screen, with the width (and height) indicated as a parameter. Create a Main function to test it.
· (5.3.2) Create a function to draw a rectangle on the screen, with the width and height indicated as parameters. Complete the test program with a Main function.
· (5.3.3) Create a function to draw a hollow rectangle on the screen, with the width, height and border symbol indicated as parameters. Complete it with a Main to request that data to the user and draw the rectangle.
No comments:
Post a Comment