Tag Archives: #mastery11

Mastery 11

In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is:

type name ( parameter1, parameter2, …) { statements }

Where:

  • type is the type of the value returned by the function.
  • name is the identifier by which the function can be called.
  • parameters (as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example: int x), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from.
  • statements is the function’s body. It is a block of statements surrounded by braces { } that specify what the function actually does.

This program is divided in two functions: addition and main. Remember that no matter the order in which they are defined, a C++ program always starts by calling main. In fact, main is the only function called automatically, and the code in any other function is only executed if its function is called from main (directly or indirectly).

In the example above, main begins by declaring the variable z of type int, and right after that, it performs the first function call: it calls addition. The call to a function follows a structure very similar to its declaration. In the example above, the call to addition can be compared to its definition just a few lines earlier:

The parameters in the function declaration have a clear correspondence to the arguments passed in the function call. The call passes two values, 5 and 3, to the function; these correspond to the parameters a and b, declared for function addition.

At the point at which the function is called from within main, the control is passed to function addition: here, execution of main is stopped, and will only resume once the addition function ends. At the moment of the function call, the value of both arguments (5 and 3) are copied to the local variables int a and int b within the function.

Then, inside addition, another local variable is declared (int r), and by means of the expression r=a+b, the result of a plus b is assigned to r; which, for this case, where a is 5 and b is 3, means that 8 is assigned to r.

The final statement within the function:

return r;

Ends function addition, and returns the control back to the point where the function was called; in this case: to function main. At this precise moment, the program resumes its course on main returning exactly at the same point at which it was interrupted by the call to addition. But additionally, because addition has a return type, the call is evaluated as having a value, and this value is the value specified in the return statement that ended addition: in this particular case, the value of the local variable r, which at the moment of the return statement had a value of 8.

Therefore, the call to addition is an expression with the value returned by the function, and in this case, that value, 8, is assigned to z. It is as if the entire function call (addition(5,3)) was replaced by the value it returns (i.e., 8).

Then main simply prints this value by calling:

cout << "The result is " << z;

Similar to the addition function in the previous example, this example defines a subtract function, that simply returns the difference between its two parameters. This time, main calls this function several times, demonstrating more possible ways in which a function can be called.

Let’s examine each of these calls, bearing in mind that each function call is itself an expression that is evaluated as the value it returns. Again, you can think of it as if the function call was itself replaced by the returned value:

1
2
z = subtraction (7,2);
cout << "The first result is " << z;

If we replace the function call by the value it returns (i.e., 5), we would have:

1
2
z = 5;
cout << "The first result is " << z;

With the same procedure, we could interpret:

cout << "The second result is " << subtraction (7,2);

as:

cout << "The second result is " << 5;

since 5 is the value returned by subtraction (7,2).

In the case of:

cout << "The third result is " << subtraction (x,y);

The arguments passed to subtraction are variables instead of literals. That is also valid, and works fine. The function is called with the values x and y have at the moment of the call: 5 and 3 respectively, returning 2 as result.

The fourth call is again similar:

z = 4 + subtraction (x,y);

The only addition being that now the function call is also an operand of an addition operation. Again, the result is the same as if the function call was replaced by its result: 6. Note, that thanks to the commutative property of additions, the above can also be written as:

z = subtraction (x,y) + 4;

With exactly the same result. Note also that the semicolon does not necessarily go after the function call, but, as always, at the end of the whole statement. Again, the logic behind may be easily seen again by replacing the function calls by their returned value:

1
2
z = 4 + 2; // same as z = 4 + subtraction (x,y);
z = 2 + 4; // same as z = subtraction (x,y) + 4;

http://www.cplusplus.com/doc/tutorial/functions/

TC1017

llamar funciones #Mastery11

#Mastery11
here is my mastery http://youtu.be/9K1hmyU77ps

llamar funciones #Mastery11

#Mastery11
here is my mastery http://youtu.be/9K1hmyU77ps

Mastery

#Mastery11

Calling C++ functions

Para llamar a una función definida y realizada fuera del int main es necesario incluir primero la libreria iostream y el using namespace std; seguido de la función que llamaremos en el int main.

Creamos el código y la funcion principal int main con los cout cin necesarios, variables y tipos de variables, y a la hora de imprimir el resultado que dará nuestro programa, solamente se llama a la función con el nombre de la función y los parametros utilizados en ella.

Se cierra el programa de igual manera con un return 0; y guardamos, compilamos y corremos el programa.

Aquí un ejemplo de lo anterior:

#Mastery11

I just made a video explaining how to call function here it is: http://youtu.be/86h7Kq_2C64?hd=1

Mastery 11

Para este Mastery utilizaré el código del WSQ08

Para este ejercicio teníamos que crear distintas funciones, que son subrutinas creadas para realizar tereas específicas. Primero debes definir una función para después poder utlizarla en cualquier parte del mismo código.

 

En este ejercicio podemos ver la siguiente función:

def suma(x,y):

answer = x + y

return answer

 

Ya que tenemos nuestra función creada lo siguiente es utilizarla o “llamarla” en nuestro código.

Para esto, primero debemos sustituir las variables que fueron impuestas, en este caso son “x” y “y”, las cuales serán valores que asignará el usuario en “num1” y “num2”.

Esto se observa aquí:

do_sum = suma(num1,num2)

Esto significa que aplicamos la función que creamos y que answer = x + y será sutituida por answer = num1 + num2.

Más adelante podemos ver el resultado dado y comprobar que nuestra función funciona 😀

MASTERY 12 Creating Python Functions

CREAR FUNCIONES DE PYTHON

Ya sabemos qué es una función y cómo llamarlos para sacar la respuesta y mostrarla en la terminal. Hay que considerar que Python tiene sus funciones como “type” que sirve para identificar en su argumento qué tipo de valor es, “int” que sirve para convertir valores a números enteros, “str” que sirve para convertir valores en un string, etc. También estarían los que pertenecen a un módulo, pero eso se va ver más tarde. Hay otra cosa más en el tema de las funciones: nosotros podemos crear nuestras propias funciones y usarlos como queremos.
La clave para crear una función es teclear primero “def”, que es lo que definirá la función, luego poner su nombre y el argumento que se utilizará para esta función. Utilizaré el ejemplo del Mastery anterior:
MASTERY 12 Creating Python Functions
La primera línea es el “header” que sería el nombre de la función creada con su argumento. Hay que poner dos puntos que sería para definir las siguientes declaraciones y expresiones que se utilizará en el resto de la función, es decir, el “body”. Ahí en el body siempre debe haber un espacio adelante del header porque se podrá comprender que esas declaraciones y operaciones pertenecen a esa función. El resto de la función, llamarla y mostrar su respuesta en la terminal se pude ver en el Mastery anterior.

MASTERY 11 Calling Python Function

LlAMAR UNA FUNCIÓN EN PYTHON

Una función es una secuencia de declaraciones que realiza una operación. Una función debe tener un nombre y un parámetro que es el argumento que se tomará y lo regresará como resultado dependiendo de la operación de la función.
Vamos crear una función donde se sume unos valores:
MASTERY 11 Calling Python Function
Hay que considerar que para “regresar” el valor que se usó dentro de la función como el resultado se debe utilizar el comando “return” y la variable que se quiera mostrarse como el resultado dependiendo de como va la operación.
Ahora lo clave para este Mastery: llamar la función ¿Cómo?
Declara una variable AFUERA de la función y pon el nombre de la función con su respectivo argumento (en este caso, suma(n)). Esa variable tendrá el resultado de esa función. Luego, utiliza el comando print hacia la variable que contiene la función y el resultado te saldrá en la terminal o output como en la imagen de allá arriba.

MASTERY 12 Creating Python Functions

CREAR FUNCIONES DE PYTHON

Ya sabemos qué es una función y cómo llamarlos para sacar la respuesta y mostrarla en la terminal. Hay que considerar que Python tiene sus funciones como “type” que sirve para identificar en su argumento qué tipo de valor es, “int” que sirve para convertir valores a números enteros, “str” que sirve para convertir valores en un string, etc. También estarían los que pertenecen a un módulo, pero eso se va ver más tarde. Hay otra cosa más en el tema de las funciones: nosotros podemos crear nuestras propias funciones y usarlos como queremos.
La clave para crear una función es teclear primero “def”, que es lo que definirá la función, luego poner su nombre y el argumento que se utilizará para esta función. Utilizaré el ejemplo del Mastery anterior:
MASTERY 12 Creating Python Functions
La primera línea es el “header” que sería el nombre de la función creada con su argumento. Hay que poner dos puntos que sería para definir las siguientes declaraciones y expresiones que se utilizará en el resto de la función, es decir, el “body”. Ahí en el body siempre debe haber un espacio adelante del header porque se podrá comprender que esas declaraciones y operaciones pertenecen a esa función. El resto de la función, llamarla y mostrar su respuesta en la terminal se pude ver en el Mastery anterior.