Author Archives: ivanna lases

Mastery17


Mastery17

Mastery17

Use of “switch” as a conditional
The body of a switch statement may have an arbitrary number of case: labels, as long as the values of all constant_expressions are unique (after conversions/promotions). At most one default: label may be present (although nested switch statements may use their own default: labels or have case: labels whose constants are identical to the ones used in the enclosing switch)
If condition evaluates to the value that is equal to the value of one of constant_expressions, then control is transferred to the statement that is labeled with that constant_expression.
If condition evaluates to the value that doesn’t match any of the case: labels, and the default: label is present, control is transferred to the statement labeled with the default: label.
The break statement, when encountered in statement exits the switch statement:
switch(1) {
case 1 : cout #TC1017

Mastery14

Creating your own and using C++ libraries
1) Create the files "mylibrary.h" and "mylibrary.cpp".
2) Only compile the library, and it shouldn’t have a "main()" function in it. This step will generate an object file called "myfile.o".
3) Create another file called something like "main.cpp". In main.cpp you need to "mylibrary.h".
4) Compile main.cpp and add the library from step 2 to link in (in this case "myfile.o"). If you don’t add this library, you’ll get a error message like "linker error – can’t find function definition", or something like that.

TC1017

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

Mastery 13

Creación de la librería

Primero que nada crearemos una carpeta de nombre libUtilidades en C:Dev-Cppbin en la cual iremos guardando todos los archivos del proyecto. Abrimos el Dev-C++ y vamos a Archivo -> Nuevo -> Proyecto, seleccionamos Static Library y el nombre del proyecto será libUtilidades
Ahora agregamos un nuevo fichero, para esto vamos a Proyecto -> Nuevo Código Fuente, escribimos el siguiente código ahí y guardamos el archivo como utilidades.h:
Como podemos ver aquí definimos únicamente el prototipo o molde de las funciones a usar. La primera devolverá el resultado de la suma de 2 enteros y la segunda función devolverá 1 si la cadena ingresada como parámetro es palindroma ó 0 si no lo es.

Si, anteriormente dije que una librería debe tener funciones agrupadas de acuerdo a su utilidad. En este caso estas funciones no tienen nada que ver una con la otra, pero sirve de ejemplo para comprender ciertas cosas.

Otra cosa, en este fichero .h únicamente colocamos los prototipos de funciones que queramos hacer públicas, es decir que queramos que los usuarios vean y por lo tanto puedan usar.

Ahora vamos a crear la implementación de las funciones anteriores, para esto esto vamos a Proyecto -> Nuevo Código Fuente, escribimos el siguiente código ahí y guardamos el archivo como utilidades.cpp
Podemos ver que están las implementaciones de las 2 funciones anteriores, pero además está la función longitud, como dije, esta función será privada es decir no podrá ser llamada directamente por el usuario que use la librería, ya que no incluímos su prototipo en el archivo .h. Esta función será de utilería y la usaremos en forma interna.

Bien, ahora vamos a compilar la librería para ello, simplemete presionamos CTRL+F9 y podemos ver en la parte inferior de la ventana que se ha creado el fichero libUtilidades.a

Bien con esto ya hemos creado nuestra librería. Si vamos al Explorador de Windows a nuestra carpeta de trabajo, podemos ver que se han creado algunos ficheros, de todos estos, los que nos son útiles para poder usar la librería son: utilidades.h y libUtilidades.a, los demás ficheros tienen el fuente de la biblioteca. Si queremos distribuír nuestra librería sólo son necesarios los 2 ficheros anteriores

TC1017

http://www.programacionenc.net/index.php?option=com_content&view=article&id=63:creacion-y-uso-de-una-libreria-estatica-h&catid=37:programacion-cc&Itemid=55

Mastery16


Mastery16

Mastery16

Use of “else” with a conditional
The nested if…else statement has more than one test expression. If the first test expression is true, it executes the code inside the braces{ } just below it. But if the first test expression is false, it checks the second test expression. If the second test expression is true, if executes the code inside the braces{ } just below it. This process continues. If all the test expression are false, code/s inside else is executed and the control of program jumps below the nested if…else

Conditional/Ternary Operator ?:
Conditional operators are the peculiar case of if…else statement in C++ Programming.
link: http://www.programiz.com/cpp-programming/if-else#if-else

mastery 19


mastery 19

mastery 19

Use of loops with “while”
Syntax:
The syntax of a while loop in C++ is:

while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

link: http://www.tutorialspoint.com/cplusplus/cpp_while_loop.htm

WSQ06


WSQ06

WSQ06

Use of loops with “while”


Use of loops with “while”

Use of loops with “while”

In this Code i am using While.

WSQ13


WSQ13

WSQ13


A little video from youtube:
link:
https://www.youtube.com/watch?v=sZmz7znP6x0

WSQ12


WSQ12

Here is my WSQ12