Lesson objectives
10.4.1.1 Write code in a programming language using functions and procedures
Success criteria
Describes the function / procedure parameters
Uses function / procedure when solving problems
Creates its own function / procedure to solve practical problems
The concepts of function and method
Function is a part of a program that has its own name. This name can be used in the program as a command (this command is called a function call). When a function is called, the commands of which it consists are executed. A function call can return a value (similar to an operation) and therefore can be used in an expression along with operations.
A method is a function that is part of a class that can perform operations on data of this class. In the Java language, the entire program consists only of classes and functions can be described only inside them. That is why all functions in the Java language are methods.
Concept of method
Methods are always defined inside classes:
minOfTwoNumbers - is the method we defined in the Main class, let's consider it.
public - access type (the method can be called from another class). There are other types of access, for example private (the method is available only inside the class) and protected.
static - means that the method is static, it belongs to the class Main, and not to a specific instance of the class Main. We can call this method from another class like this: Main.minOfTwoNumbers ().
Parsing programm code
public class
public static
}
public static void main(String[] args) {
//Your program code is here.
}
}
8
Functions(Subprograms)
Self-contained routines that are identified by a name and have the same structure as main().
They are executed when they are called (calling their names).
main() is also a function but a special one.
12
Example:
#include
using namespace std;
void Builder() {
cout << ” * ” << endl;
cout << ” * * ” << endl;
cout << ” * * ” << endl;
cout << ”*******” << endl;
cout << ”* *” << endl;
cout << ”* *” << endl;
cout << ”* *” << endl;
cout << ”*******” << endl;
cout << endl;
}
void Gardener() {
cout << ” * ” << endl;
cout << ” *** ” << endl;
cout << ” ***** ” << endl;
cout << ”*******” << endl;
cout << ” * ” << endl;
cout << ” * ” << endl;
cout << ” * ” << endl;
cout << endl;
}
void main() {
Builder();
Builder();
Gardener();
Gardener();
}
*
* *
* *
*******
* *
* *
* *
*******
*
* *
* *
*******
* *
* *
* *
*******
*
***
*****
*******
*
*
*
*
***
*****
*******
*
*
*
Executed when we call them
© ООО «Знанио»
С вами с 2009 года.