Skip to main content

#mastery21 #TC1017

4 min read

 

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.

1
2
3

for(int i=0;  i

     cout "The number is: "

}

 



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

 

The number is: 0

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

The number is: 6

The number is: 7

The number is: 8

The number is: 9


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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

using namespace std;

 

void numberFunction(int i) {

  cout "The number is: "

}

 

int main() {

 

for(int i=0; i

  numberFunction(i);

}

 

return 0;

}

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

using namespace std;

 

void numberFunction(int i) {

  cout "The number is: "

  i++;

  if(i

    numberFunction(i);

  }

}

 

int main() {

 

int i = 0;

numberFunction(i);

 

return 0;

}

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.

#mastery26 #TC1017

2 min read

 

 

A matrix is, by definition, a rectangular array of numeric or algebraic quantities which are subject to mathematical operations. Matrices can be defined in terms of their dimensions (number of rows and columns). Let us take a look at a matrix with 4 rows and 3 columns (we denote it as a 4×3 matrix and call it A):

Each individual item in a matrix is called a cell, and can be denoted by the particular row and column it resides in. For instance, in matrix A, element a32 can be found where the 3rd row and the 2nd column intersect.


Matrices are used to represent complicated or time-consuming mathematical operations. A single matrix can hold an infinite number of calculations, which can then be applied to a number, vector, or another matrix. There are several operations that can be done on matrices, including addition, multiplication and inverse calculation; some of which will be discussed shortly. Operations done on one matrix can be transferred to another matrix simply by concatenating the two (by matrix multiplication). Matrices often find their use in 3 dimensional applications, were numerous identical operations are performed on thousands of vectors 30 or 40 times a second. Combining all these operations in one single matrix significantly improves the speed and functionality of a 3D rendering pipeline. Matrices are also used in financial processes (again, where a large number of data has to be processed in a similar fashion).

#mastery28 #TC1017

3 min read

 

Reading and writing of files in C++

So far, we have been using the iostream standard library, which provides cin and coutmethods for reading from standard input and writing to standard output respectively.

This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types:

Data Type

Description

ofstream

This data type represents the output file stream and is used to create files and to write information to files.

ifstream

This data type represents the input file stream and is used to read information from files.

fstream

This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

To perform file processing in C++, header files and must be included in your C++ source file.

Opening a File:

A file must be opened before you can read from it or write to it. Either the ofstream orfstream object may be used to open a file for writing and ifstream object is used to open a file for reading purpose only.

Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

void open(const char *filename, ios::openmode mode);

Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.

Mode Flag

Description

ios::app

Append mode. All output to that file to be appended to the end.

ios::ate

Open a file for output and move the read/write control to the end of the file.

ios::in

Open a file for reading.

ios::out

Open a file for writing.

ios::trunc

If the file already exists, its contents will be truncated before opening the file.

You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case it already exists, following will be the syntax:

ofstream outfile;

outfile.open("file.dat", ios::out | ios::trunc );

Similar way, you can open a file for reading and writing purpose as follows:

fstream  afile;

afile.open("file.dat", ios::out | ios::in );

Closing a File

When a C++ program terminates it automatically closes flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

void close();

Writing to a File:

While doing C++ programming, you write information to a file from your program using the stream insertion operator (

Reading from a File:

You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.

 

 

#mastery25 #TC1017

2 min read

C++ string is an object of the class string, which is defined in the header file and which is in the standard namespace. The string class has several constructors that may be called (explicitly or implicitly) to create a string object.

Examples

 string s1;               // Default constructor - creates an empty or null C++ string of length 0, equal to ""

  string s2("hello");      // Explicit constructor call to initialize new object with C string

  string s3 = "hello";     // Implicit constructor call to initialize new object with C string

  string s4(s2);           // Explicit constructor call to initialize new object with C++ string

  string s5 = s2;          // Implicit constructor call to initialize new object with C++ string

Representation in Memory

Here is another example of declaring a C++ string:

 string name = "Karen";

C++ string

name is a string object with several data members. The data member p is a pointer to (contains the address of) the first character in a dynamically-allocated array of characters. The data member length contains the length of the string. The data member capacity contains the number of valid characters that may currently be stored in the array.

A "null string" is a string with a length of 0:

Null C string

The length of a null string is 0.

 

#mastery27 #TC1017

2 min read

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;
}

#mastery24 #TC1017

1 min read

Creation and use of vectors in C++

C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays:

To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows:

type arrayName [ arraySize ];

This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement:

 

double balance[10];

#mastery23 #TC1017

2 min read


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

2 min read

Importing and using C++ libraries

Estuve investiganco acerca de esto y pues casi no entendi muy bien ,yo trabaje el semestre pasado con visual studio, y se me hizo un poco más practico poder entenderle ahí, entonces pues para añadir una librería lo primero que debemos hacer es instalar esa librería. En Ubuntu debería ser un simple apt-get install, pero tal vez queramos tener una versión más actual o no encontremos nuestra librería en repositorios, por lo que tendremos que compilarla haciendo uso del make que nos traiga su paquete. Una vez instalada, tal vez debamos añadir algunos parámetros en el compilador. Para ello vamos a Run>Set Proyect Configuration>Customize…>C++ Compiler>Command Line>Aditional Options y añadimos ahí las opciones. Por ejemplo, para la librería OpenCV tendríamos que añadir: `pkg-config --cflags opencv` `pkg-config --libs opencv` esto mismo lo podemos hacer buscando las librerías y añadiéndolas en Run>Set Proyect Configuration>Customize…>Linker>Libraries. Una vez ahí debemos darle a “Add library file” o “Add library” y buscar las librerías estandar dinámicas (.a) o estáticas (.so) que suelen estar en el directorio /usr, /usr/lib, /usr/share, etc. una vezh echo todo esto, puede que tengamos problemas con el autocompletado, tambien puede que funcione todo perfectamente. En tal caso tendríamos 2 opciones añadir la dirección de los archivos .h (los de los includes) en: Tools>Options>Code Assintance>C++ Compiler>Adde la segunda opción es que el problema sea que Netbeans nos reconoce los ficheros de cabeceras, pero por problemas en el preprocesado del proyecto se “líe” un poco con los . Por ejemplo, si nuestro problema es que en nuestro archivo cabecera nos aparece, por ejemplo, algo así (y en este sitio es donde nos da el error):#ifndef __MMX__# error "MMX instruction set not enabled"

 

#bonus #TC1017

1 min read

YA CASI FINALEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

https://www.youtube.com/watch?v=8pJPO8oQreA

#proyecto #TC1017

1 min read

al finalizar mi proyecto, me siento realmente satisfecha con el trabajo que hicimos mi compañero Pablo y yo.

para mi fue muy dificil iniciarlo, pero Pablito me ayudó jaja

creo que lo mas dificil fue hacer las condiciones, porque necesitabamos usar demasiada logica, pero cometiendo errores se aprende, y fue asi el resultado, aprendí .

 aqui esta nuestro hermoso proyecto

:

https://github.com/kenwbauer/PabloMitzi

gracias por la ayuda Ken :)