Tag Archives: #include

#TC1017 #Mastery27

Validated user input in C++.

Muchas veces los programs nos exigen validar el input que un usuario nos da para asi ver si continuar o no con el programa.

Este es un pequeño codigo para una demostración.

using namespace std;

int main()
{
int a;

 coutcin>>a;
while(1)
{
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits::max(),’n’);
coutcin>>a;
}
if(!cin.fail())
break;
}

coutreturn 0;
}

Creation and use of vectors in C++ #TC1017 #Mastery23

Creation and use of vectors in C++ 1017 23

Vector is a template class that is a perfect replacement for the good old C-style arrays. It allows the same natural syntax that is used with plain arrays but offers a series of services that free the C++ programmer from taking care of the allocated memory and help operating consistently on the contained objects.

The first step using vector is to include the appropriate header:

 

  1. using namespace std;
  2. //…
  3. vector v;

Here is my link

https://www.dropbox.com/s/m0popqb0mg8qbxo/Mastery23.mov?dl=0

Is a short video explaining a really easy vector 🙂 

Here is other link about vectors :D:

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

http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm

#Mastery23 #TC1017

Un vector es una estructura de tamaño dinámico que permite guardar muchos elementos de un mismo tipo y almacenarlos juntos, en orden. Debido a esto se les puede encontrar dentro del nombre y con su posición. Para crear un vector es necesario poner #include con las librerías, aunque no sea en si una. Podemos definir el número de elemntos que el vector tendrá o dejarlo libre. este se logra de la siguiente manera:

#include

vector (número de elementos)

para nombrar un elemento se usan los corchetes. []

Usamos mucho los vectores en el programa de Sudoku.cpp

Aquí el link: https://github.com/kenwbauer/JuanPabloSquared/blob/master/sudoku.cpp

Más en: https://www.mochima.com/tutorials/vectors.html

#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.

#mastery27 #TC1017

27 1017

Validated user input in C++

Inputs have to be validated before allowing any kind of processing or operations to be performed on it. This is extremely important because , an unhandled wrong input  might have the complete ability to crash a system.  C++ has some  good  validation techniques that  can be used to validate most kind of inputs. This post  discusses some of the techniques and its shortcomings and  what could be done to improve the quality of validation.

Now, consider a program has to accept only integer inputs and reject all the others. So, the developer would have declared to store the integer value in say “int a;”. So “a” will store the input value.

When the user input is accepted using the “cin>>a” statement, we can use the inbuilt methods surrounding the “cin”  statement to test its status.

Here is a sample program: –



using namespace std;

int main()
{
int a;

 coutcin>>a;
while(1)
{
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits::max(),’n’);
coutcin>>a;
}
if(!cin.fail())
break;
}

coutreturn 0;
}

#mastery23 #TC1017

23 1017

Creation and use of vectors in C++

Vector is a template class that is a perfect replacement for the good old C-style arrays. It allows the same natural syntax that is used with plain arrays but offers a series of services that free the C++ programmer from taking care of the allocated memory and help operating consistently on the contained objects.The first step using vector is to include the appropriate header:

Note that the header file name does not have any extension; this is true for all of the Standard Library header files. The second thing to know is that all of the Standard Library lives in the namespace std. This means that you have to resolve the names by prepending std:: to them:

  1. std::vector v; // declares a vector of integers

For small projects, you can bring the entire namespace std into scope by inserting a using directive on top of your cpp file:

  1. using namespace std;
  2. //…
  3. vector v; // no need to prepend std:: any more

This is okay for small projects, as long as you write the using directive in your cpp file. Never write a using directive into a header file! This would bloat the entire namespace std into each and every cpp file that includes that header. For larger projects, it is better to explicitly qualify every name accordingly. I am not a fan of such shortcuts. In this article, I will qualify each name accordingly. I will introduce some typedefs in the examples where appropriate—for better readability.

#Mastery13 #TC1017

Importing and using C++ Libraries

Primero que nada necesitas llamar tus librerías, un ejemplo es el #include . Esta librería contiene los procesos para cin y cout que recogen(guardar información) e imprimen información. Algunos de los casos más comunes son el cmath, cfloat, entre otros, no se deben de confundir con los contenedores como aunque se usen para lo mismo y de la misma manera.

 Más en : http://www.cplusplus.com/reference/

Creating your own and using C++ libraries #TC1017 #Mastery14

Creating your own and using C++ libraries 1017 14

There are many easy ways I found this 

  1. Create your file  with the name that you want like this “myfirstlibrary.cpp” and “a.h”. Then compile the library without a main program
  2. It will create a file called “a.o”.
  3. Then can your library with  
  4. Compile the program and add the library “a.o”.  

I found also this link for you guys 🙂 

http://stackoverflow.com/questions/4496411/c-how-to-build-my-own-utility-library

Creating your own and using C++ libraries

 

 

#Mastery01 #MASTERY01

01  01

I am doing this mastery again because i want to get the two points.

Well in this one I want to teach how to create and run a c++ from command line.

Im going to give you a couple of steps to make it easier to you to understand it:

     1.- Open your editor (notepad, notepad++, sublime, jeditor, etc..).

     2.- Save your program as a c++ file and in the end of the name add “.cpp” so the terminal will run it.

     3.- Start coding. 

          3.1.- Include your libraries, ALWAYS include (#include , ) the cstdlib is not always             necessary but add it anyway.

          3.2.- Before everything put “usingnamespace std;” so you don´t have to put it all over your code.

          3.3.- You will always have a “int main()” it doesn´t matter if you have functions or not.

          3.4.- ALWAYS at the end of the “int main()” put ” return 0;” is not really necesary eaither but every programmer             will tell you to put it.

     4.- Open your ternimal (cygwin, mac, linux, etc..) wait until it recognize your computer and then put “cd” to change        directory then put “/” to go were ever is your code you made in your editor.

     5.- Finally after it compiles you have to execute it with “./a.exe” in wondows, “./a.out” on Mac an Linux.

 

Hope you understand and learn from it.

#Mastery01 – Ability to create C++ file and run from command line

 

Crear y correr un archivo de C++

Una línea de comandos es un tipo de interfaz el cual se usa para manipular un programa o sistema operativo mediante instrucciones escritas.

En mi caso, por recomendacion, mi CLI es cygwin. Entonces, para correr un archivo de C++ debemos seguir los siguientes pasos:

Abrir el programa en el cual escribiremos el código ( sublime text 2 ).

Una vez que abrimos el programa empezaremos nuestro codigo con el usual , seguido por nuestro código.

Una vez terminado seleccionaremos la opcion “file” y “save”.

Surgira una ventana donde le asignaremos el nombre y lugar donde lo guardaremos. 

Es importante que al final de nuestro nombre debemos ponerle la extencion “.cpp”.

Ya teniendo el codigo hecho procederemos a ejecutarlo en la linea de codigo para ejecutarlo estos son los pasos:

1- Abriremos el programa cygwin.

2- Una vez que la ventana esta abierta debemos escribir los siguientes comandos:

 

  • cd cygdrive/
  • cd c/
  • cd users/
  • cd (nombre del usuario) /
  • Enseguida comenzaremos a escribir el mismo comando “cd” seguido de la carpeta donde guardamos nuestro archivo, por ejemplo cd desktop/  

 

3- Una vez que nos encontramos en la carpeta donde guardamos el programa debemos escribir g++ seguido del nombre de nuestro programa junto con “.cpp” y presionamos enter.

4- Esperaremos un par de segundos antes de que vuelva a aparecer los comandos que ya habiamos escrito antes. Si no existe ningun error debemos escribir “./a.out” y presionaremos enter.

5- Finalmente el programa comenzara a ejecutar nuestro código.

 

 

01 1017