When we want to make clear that a function does not need to return any value, we can use "void" as return data type, as we have done so far with "Main" and as we did with our "Greet" function.
But that's not what happens to the mathematical functions that we often use: they return a value, which is the result of an operation. For
example, if we calculate the square root of 4, we obtain a number (2).
Similarly, we will usually want our function to perform a series of calculations and then "return" the result of these calculations, so that it can be used from any other part of our program. For example, we could create a function to calculate an integer squared as follows:
public static int square ( int n )
{
return n*n;
}
and we could use the result of that function as if it were a number or a variable, like this:
result = square( 5 );
A more detailed example would be:
/*---------------------------*/
/* C# Example #49: */
/* example49.cs */
/* */
/* Function "square" */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example49
{
public static int square ( int n )
{
return n*n;
}
public static void Main()
{
int number;
int result;
number= 5;
result = square(number);
Console.WriteLine("The square of the number {0} is
{1}",
number, result);
Console.WriteLine("and the square of 3 s {0}", square(3));
}
}
We can create a function that tells us which is the greater of two real numbers as follows:
public static float greater ( float n1, float n2 )
{
if (n1 > n2)
return n1;
else
return n2;
}
Suggested exercises:
· (5.4.1) Create a function to calculate the cube of a real number (float). The result should be another real number. Test this function to calculate the cube of 3.2 and 5.
· (5.4.2) Create a function that calculates which is the smaller of two integers. The result will be an integer number.
· (5.4.3) Create a function called "sign", which gets a real number, and returns an integer with the value: -1 if the number is negative, 1 if it is positive or 0 if it is zero.
· (5.4.4) Create a function that returns the first letter of a string. Use this function to display the first letter of the phrase "Hello".
· (5.4.5) Create a function that returns the last letter of a string. Use this function to calculate the last letter of the phrase "Hello".
· (5.4.6) Create a function that receives a number and displays the perimeter and area of a square that has that number as its side.
No comments:
Post a Comment