Tag Archives: #0000b0

#mastery21 #TC1017

21 1017

 

Use of recursion for repetitive algorithms

What is recursion? The simple answer is, it’s when a function calls itself. But how does this happen? Why would this happen, and what are its uses?


When we talk about recursion, we are really talking about creating a loop.
Let’s start by looking at a basic loop.

 

For those who don’t yet know, this basic loop displays the sentence, “The number is: ” followed by the value of ‘i’. Like this.


Inside the ‘for loop’ declaration we have the integer variable ‘i’ and have its starting value of 0. So the first time the sentence is displayed it reads, “The number is: 0”. The part of the ‘for loop’ declaration that is ‘i++’ tells the program that each time the loop repeats, the value of ‘i’ should be increased by 1. So, the next time the sentence is displayed it reads, “The number is: 1”.
This cycle will continue to repeat for as long as the value of ‘i’ is less than 10. The last sentence displayed would read, “The number is: 9”. As you can see the basic ‘for loop’ has three parts to its declaration, a starting value, what must remain true in order to continue repeating, and a modifying expression. Everything that is contained within the {braces} is what the program performs. Cout stands for console out, and prints words or characters to the screen.
So what does this have to do with recursion? Remember recursion is a loop. What if I did not want to just print a message to the screen? A loop can be used to perform other tasks as well.

In the following code is the same loop as above only now it is being used to call a function.

Edit & Run

I have declared a void function, which means it returns nothing, and takes a parameter of ‘int i’. The function is named ‘numberFunction’ and as you can see, all it does is display the sentence, “The number is: ” followed by the current value of ‘i’. The function is called into use by the ‘for loop’, which continually calls the function as long as the value of ‘i’ is less than 10.

Now with recursion, we won’t need to use a ‘for loop’ because we will set it up so that our function calls itself. Let’s recreate this same program one more time, only this time we will do it without a ‘for loop’. We will use a recursion loop instead, like this.

Edit & Run

 

We did it! We used recursion! You can see the call to ‘numberFunction’ is made only once in the main part of the program but it keeps getting called again and again from within the function itself, for as long as ‘i’ is less than 10.

Mastery 27

Validated user input in C++

For this mastery, I found  a super useful video that taught me how to make a validation for a user input

Here is also an example code with a validation user input code:

 

 
 

int main(){
    bool valid = false;
    int input;
    while(!valid){
        if(std::cin>>input){//this checks whether an integer was entered
            if(input  0) valid = true;//then we have to see if this integer is in range
        }else std::cin.clear();//some cleaning up
		
        std::cin.ignore(std::numeric_limits<:streamsize>::max(), 'n');//empty input stream

        if(!valid) std::cout "this input is not validn";
    }
    std::cout " is between 1 and 5n";
    std::cin.get();
    return 0;
}

 

Credits:

https://www.youtube.com/watch?v=YIX7UhIKEIk

1017 27

Mastery 23

Creation and use of vectors in C++

Vector

 

Vectors are sequence containers representing arrays that can change in size.

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

Example

Output:

Credits:

http://www.cplusplus.com/reference/vector/vector/vector/

http://www.cplusplus.com/reference/vector/vector/

1017 23

Mastery 21

Use of recursion for repetitives algorithms

What is recursion? The simple answer is, it’s when a function calls itself. But how does this happen? Why would this happen, and what are its uses?

When we talk about recursion, we are really talking about creating a loop. Let’s start by looking at a basic loop.

 



For those who don’t yet know, this basic loop displays the sentence, “The number is: ” followed by the value of ‘i’. Like this.


Inside the ‘for loop’ declaration we have the integer variable ‘i’ and have its starting value of 0. So the first time the sentence is displayed it reads, “The number is: 0”. The part of the ‘for loop’ declaration that is ‘i++’ tells the program that each time the loop repeats, the value of ‘i’ should be increased by 1. So, the next time the sentence is displayed it reads, “The number is: 1”.
This cycle will continue to repeat for as long as the value of ‘i’ is less than 10. The last sentence displayed would read, “The number is: 9”. As you can see the basic ‘for loop’ has three parts to its declaration, a starting value, what must remain true in order to continue repeating, and a modifying expression. Everything that is contained within the {braces} is what the program performs. Cout stands for console out, and prints words or characters to the screen.
So what does this have to do with recursion? Remember recursion is a loop. What if I did not want to just print a message to the screen? A loop can be used to perform other tasks as well.

Credit:

http://www.cplusplus.com/articles/D2N36Up4/

1017 21

Mastery 12

Creating functions in C++

Functions

Functions allow to structure programs in segments of code to perform individual tasks.

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.

 

 

// function example
 <iostream>
using namespace std;

int subtraction (int a, int b)
{
  int r;
  r=a-b;
  return r;
}

int main ()
{
  int x=5, y=3, z;
  z = subtraction (7,2);
  cout << "The first result is " << z << 'n';
  cout << "The second result is " << subtraction (7,2) << 'n';
  cout << "The third result is " << subtraction (x,y) << 'n';
  z= 4 + subtraction (x,y);
  cout << "The fourth result is " << z << 'n';
}
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6

Mastery 11

Calling functions in C++

// function example

 <iostream>
using namespace std;

int addition (int a, int b)
{
  int r;
  r=a+b;
  return r;
}

int main ()
{
  int z;
  z = addition (5,3);
  cout << "The result is " << z;
}

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:

Mastery 11 
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 functionaddition.

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 aplus b is assigned to r; which, for this case, where a is 5 and b is 3, means that 8 is assigned to r.

Mastery 10

Basic output (printing) and inpur (text based) in C++

The standard library defines a handful of stream objects that can be used to access what are considered the standard sources and destinations of characters by the environment where the program runs:

stream description
cin standard input stream
cout standard output stream
cerr standard error (output) stream
clog standard logging (output) stream

Standard output (cout)

On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.

For formatted output operations, cout is used together with the insertion operator, which is written as << (i.e., two “less than” signs).

cout << "Output sentence"; // prints Output sentence on screen
cout << 120;               // prints number 120 on screen
cout << x;                 // prints the value of x on screen  

Standard input (cin)

In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin.

For formatted input operations, cin is used together with the extraction operator, which is written as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the extracted data is stored. For example:

int age;
cin >> age;

Use of the condditional “if”

(Tutorial en español, )

Para este tutorial es necesario por lo menos saber lo basico de la estructura de un programa que lo puede checar en esta pagina: http://www.cplusplus.com/doc/tutorial/program_structure/

El uso de la funcion “If” es un condicional donde si, y solo si, se cumple la condicion que esta dentro del if se realiza lo que esta escrito dentro de ese codigo. Si se cumple la condicion se ejecuta el codigo y sino simplemente se pasa de eso, un ejemplo de esto es: 

1
2
3
4
5
if (x == 100)
{
   cout << "x is ";
   cout << x;
}
 

La estructura de este programa es de “if” seguido de un doble parentesis () donde se pone la condicion que se debe cumplir, por ultimo son llaves {} que es donde se pone el codigo que se va a ejecutar.

Para mas informacion puedes consultar esta pagina: http://www.cplusplus.com/doc/tutorial/control/

 

Basic output and input in C++

(Tutorial en español, ,PIW)

Para este tutorial es necesario por lo menos saber la estructura de un programa que lo puedes checar en este link: http://www.cplusplus.com/doc/tutorial/program_structure/

Las funciones de Input and Output son funciones que se ponen para poder tanto poner o imprimir informacion en pantalla y con otro el poder recibir informacion del usuario al programa.

OUTPUT

Esta funcion de C++ es una funcion que te permite imprimir informacion hacia el usuario. La funcion que se utiliza puede ser de dos maneras, pero la mas facil y mas usado es cout que es una impresion de informacion estandar que despues de usar ese cout se utiliza dos simbolos de << que quiere decir una insercion o lo que va despues de, por ejemplo: 

 

1
2
cout << "Hello";  // prints Hello
cout << Hello;    // prints the content of variable Hello 
 

donde estos simbolos señalan lo que sigue y tambien por ejemplo: 

cout << "I am " << age << " years old and my zipcode is " << zipcode;
 

donde al finalizar de poner todo lo que se quiere anhidar y decir se pone un ; para terminar esa accion.

INPUT

Esta otra funcion de C++ es una funcion que permite recibir informacion que el usuario tecle para introducirla en el programa para asignar el valor a una variable. Este comande es el de cin que se utiliza igual con un simbolo que es el de >> que es el contrario del output, con esto quiere decir que el valor que ponga el usuario. Un ejemplo de esto es: 

1
2
int age;
cin >> age;
 

Pero tambien para esto necesitas declarar las variables que van a recibir algun tipo de valor ya sea string(texto), int(entero), float(numeros decimales), char(caracteres). Y al finalizar tambien se pone un ; para finalizar esa accion.

Si requieren mas informacion visiten esta pagina: http://www.cplusplus.com/doc/tutorial/basic_io/ que es donde me base para hacer este tutorial en español.