Content of the lesson:
We explained in the previous lesson what are procedures and how can we use them. Functions are very similar; there are only a few differences which will be shown in this lesson.
A function is a separated part of a program which should deal with a problem. Functions are used often in these cases:
You cannot make more complex projects without functions because it is not clever and sometimes also not possible to write all source code inside the begin..end block of the main program.
The syntax of each function is illustrated in the following source code:
return value Function name (parameters of functions) //parametry jsou volitelné { variables //volitelná deklarace proměnných pro funkci commands of the function return value }
Each function has to begin with the type of return value (int, float) which is followed by the name of the function. You can also insert parameters into brackets behind the name.
Then you can see the keyword { and the program part of the function which contains all commands and calculations.
The penultimate line is also new - it sets which value should be
returned. Here you should assign the return value to
the function (use the keyword return). The
return value can be assigned directly using a number or text, or you can
assign it using a variable. However, you have to keep the type which was
chosen in the first line, otherwise the program will crash.
Note: assigning the return value to function does not have to be the last
command inside function, you can add commands behind that line.
We will show a very simple function for the beginning to understand the principle of the return value. To simplify all examples, the header part of programs with the name of program and used libraries will not be written because we will not change anything in that part.
#include "stdafx.h" float vratPI() { float pi; pi = 3.14; return pi; } int _tmain(int argc, _TCHAR* argv[]) { printf("%f",vratPI()); fflush(stdin); getchar(); return 0; }
You can see that a function with name vratPI was defined and it only returns the value 3.14. Then this function is used in the main part of program to write the returned value into console. The command writeln(vratpozdrav) does the same as if we wrote printf("3.14"). The whole program writes the value 3.14 into console and waits until any key is pressed to be terminated (in case we did not add the line getchar() we would not be able to read the greeting because the program would be terminated immediately after writing it).
Note that this function does not require any parameters so you do not have to write the empty brackets behind its name.
#include "stdafx.h" int spocitej() { int soucet; soucet=45+54*2; return soucet; } int _tmain(int argc, _TCHAR* argv[]) { printf("%d",soucet()); fflush(stdin); getchar(); return 0; }
We created the function Spocitej which saves the result of a fictive formula into the variable soucet and this variable is returned. The result will be written into console in the main part of program.
We can extend the example by using parameters for our function.
#include "stdafx.h" int spocitej(int a, int b); { int soucet; soucet=a+b; return soucet; } int _tmain(int argc, _TCHAR* argv[]) { int a, b; a=40; b=50; printf("%d",spocitej(a,b)); fflush(stdin); getchar(); return 0; }
Now you see that the function Spocitej requires two parameters – integer numbers which are added and the result is returned. We had to create two variables to insert them as parameters.
These examples were only an illustration, they did not solve any concrete task. We will show other examples in the following parts of the lesson which might be used in real programs.
The return value is a great advantage especially when you want to check a condition of a result and you simultaneously need the result to be computed. Thanks to functions you do not need any other variables because you can insert a function directly inside a condition in case it returns an int value (1 or 0).
Take a look at an example which will add and multiply two numbers and then if both results will be lower than 100 it will write a particular message.
#include "stdafx.h" int vynasob(int x, int y); { int v; if (x*y<100) v:=1 else v:=0; return v; } function Secti(var x,y:integer):boolean; { int s; if (x+y<100) s:=1 else s:=0; return s; } int _tmain(int argc, _TCHAR* argv[]) { int a, b; a=8; b=11; if (secti(a,b) AND vynasob(a,b)) printf"Soucet i soucin jsou mensi nez 100."); fflush(stdin); getchar(); return 0; }
There are two functions defined in this example (Vynasob and Secti). They return boolean value true in case that the sum and the product are lower than 100. We initialize variables at first in the main part and then we use those functions inside a condition to check if the sum and the product are lower than 100. In case that this is 1, a message is written - if we use values 8 and 11 the message will be written.
You can see that functions can be arbitrarily used instead of boolean values and they can be connected using logical conjunctions. This is the main difference between functions and procedures and also one of advantages of functions.
We are using the transfer of the parameter by value in this text. The second method it the transfer of the parameter by pointer, where we access directly to the memory. This method is not described here, because of it is over the scope of this lesson.
We can show one more example of inserting parameters by addresses. Imagine you are writing a program for a particular shop. You get prices of products (we will use 3 products to simplify the situation) without the tax and you need to sum the prices without and then with a tax (we will use 20 % as the value of tax).
#include "stdafx.h" float sectibezdph(float a, float b, float c) { float soucet; soucet = a + b + c; return soucet; } float sectisdph(float a, float b, float c) { float soucet; a=a*1.2; b=b*1.2; c=c*1.2; soucet = a + b + c; return soucet; } int _tmain(int argc, _TCHAR* argv[]) { float a, b, c; a=100; b=200; c=300; printf("Sum of items without tax: %.0f\n", sectibezdph(a,b,c)); printf("Sum of items with tax: %.0f\n", sectisdph(a,b,c)); fflush(stdin); getchar(); return 0; }
It was necessary to use all variables of type extended because we used multiplying by 1.2 in the function sectisdph. Then we added the notation .0 to the line where we output values to console because we want to output the numbers without decimal places.
You know everything important about functions so you can start creating your own functions.
Write a function JeVetsi which will compare two numbers inserted as parameters and will return a boolean value - 1 in case that the first number is bigger, 0 in case that the second number is bigger.
Write a function Maximum which will require an
array of 10 integers as a parameter and will return an integer value. It
will browse through the array and return the maximum value.
Note: initialize the array using random numbers from 1 to 50.
Similar to the previous task, but the function will return the
minimum value.
Note: initialize the array using random numbers from
1 to 50.
Write a function Prumer, which will require an array of 10 integers as a parameter. This function will browse through the
array and compute the arithmetic mean of all items. Do not forget that
the arithmetic mean does not have to be an integer number and it should
be quite accurate (ideally rounded to two decimal places).
Note: initialize the array using random numbers from 1 to 50.