Category Archives: C++

Pointers I

Un puntero es una variable que contiene la dirección de memoria de un dato o de otra variable que contiene el dato. Quiere esto decir, que el puntero apunta al espacio físico donde está el dato o la variable.

Su sintaxis de declaración sería:
tipo *NombrePuntero;

Donde tipo es el tipo de dato al que referenciará este puntero, es decir, que si se necesita guardar la dirección de memoria de un dato int, se necesita un puntero de tipo int.

int a=0; //Declaración de variable entera de tipo entero
int *puntero; //Declaración de variable puntero de tipo entero
puntero = &a; //Asignación de la dirección memoria de a

El operador *, nos permite acceder al valor de la dirección que almacena el puntero, en este caso nos permite acceder al valor que contiene a. De esta forma “a” y “*puntero” muestran el mismo dato, pero esto no quiere decir que sea lo mismo, uno es un entero el otro un puntero.

Operadores

Operador addresof (&): Este devuelve la dirección en memoria de una variable que le pasamos como parámetro. Funciona a priori como una función, cuyo retorno es una dirección de memoria.

Operador de Indirección (*): Ademas de que nos permite declarar un tipo de dato puntero, también nos permite ver el VALOR que está en la dirección a la que apunta el puntero.

No confundir con type * name, lo que sería una declaración de puntero, ni 2*2, lo que sería una operación aritmética, en este caso la multiplicación.

En C++ el símbolo de * está pluriempleado.  :mrgreen:

Recursion – The basics

Recursion – The basics

 

COMPUT: a programming technique where a routine performs its task by delegating part of it to another instance of itself.

Introduction
For new computer science students, the concept of recursive programming is often difficult. Recursive thinking is difficult because it almost seems like circular reasoning. It’s also not an intuitive process; when we give instructions to other people, we rarely direct them recursively.

For those of you who are new to computer programming, here’s a simple definition of recursion: Recursion occurs when a function calls itself directly or indirectly.

A classic example of recursion
The classic example of recursive programming involves computing factorials. In mathematics, the factorial of a nonnegative integer, n (denoted n!) is the product of all positive integers less than or equal to n. For example, 5! is the same as 5*4*3*2*1, and 3! is 3*2*1.

An interesting property of a factorial is that the factorial of a number is equal to the starting number multiplied by the factorial of the number immediately below it. For example, 5! is the same as 5 * 4! You could almost write the factorial function as:

int factorial(int n)
{
   return n * factorial(n - 1);
}

Listing 1. First cut factorial function

However, there is a small problem with this; it will run forever because there is no place where it stops calling itself. It therefore needs a condition to tell it to stop. Since a factorial is for positive numbers only it makes sense to stop the recursion when the input is 1 and return 1 as the result. The modified code will look like this:

int factorial(int n)
{
   if(n == 1)
   {
      return 1;
   }
   else
   {
      return n * factorial(n - 1);
   }
}

Listing 2. better factorial function

As you can see, as long as the initial value is above zero, this function will terminate. Note that more work will need to be done to guard again invalid initial values.

The point at with the recursion is stopped is called the base case. A base case is the bottom point of a recursive program where the operation is so trivial as to be able to return an answer directly. In the case of a factorial 1! = 1. All recursive programs must have at least one base case and must guarantee that they will hit one eventually; otherwise the program would run forever or until the program ran out of memory or stack space.

recursion

Basic steps of recursive programs
All recursive programs follows the same basic sequence of steps:
1: Initialize the algorithm. Recursive programs often need a seed value to start with.
2: Check to see whether the current value(s) being processed match the base case. If so, process and return the value.
3: Redefine the answer in terms of a smaller or simpler sub-problem or sub-problems.
4: Run the algorithm on the sub-problem.
5: Combine the results in the formulation of the answer.
6: Return the results.

 

Advantages and drawbacks of recursion

Main advantage of recursion is programming simplicity. When using recursion, programmer can forget for a while of the whole problem and concentrate on the solution of a current case. Then, returning back to the whole problem, base cases (it’s possible to have more than one base case) and entry point for recursion are developed.

On the other hand, recursion has a serious disadvantage of using large amount of memory. Moreover, for most programming languages, recursion use stack to store states of all currently active recursive calls. The size of a stack may be quite large, but limited. Therefore too deep recursion can result in Stack Overflow. To resolve this problem recursion can be simulated, using loop and stack data structure.

Method Vs Function

Method Vs Function

A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).

All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.

1. It is implicitly passed the object for which it was called

2. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class – the class is the definition, the object is an instance of that data)
(this is a simplified explanation, ignoring issues of scope etc.)

Summarizing…

A method is on an object.A function is independent of an object.

For Java, there are only methods.For C, there are only functions.

For C++ it would depend on whether or not you’re in a class.

Global and Local Variables

A scope is a region of the program and broadly speaking there are three places, where variables can be declared:

  • Inside a function or a block which is called local variables,
  • In the definition of function parameters which is called formal parameters.
  • Outside of all functions which is called global variables.

We will learn what is a function and it’s parameter in subsequent chapters. Here let us explain what are local and global variables.

#include <iostream>
using namespace std;

int main ()
{
  // Local variable declaration:
  int a, b;
  int c;

  // actual initialization
  a = 10;
  b = 20;
  c = a + b;

  cout << c;

  return 0;
}

Global Variables:

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

#include <iostream>
using namespace std;

// Global variable declaration:
int g;

int main ()
{
  // Local variable declaration:
  int a, b;

  // actual initialization
  a = 10;
  b = 20;
  g = a + b;

  cout << g;

  return 0;
}

A program can have same name for local and global variables but value of local variable inside a function will take preference. For example:

#include <iostream>
using namespace std;

// Global variable declaration:
int g = 20;

int main ()
{
  // Local variable declaration:
  int g = 10;

  cout << g;

  return 0;
}

When the above code is compiled and executed, it produces the following result:

10

Initializing Local and Global Variables:

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows:

Data Type Initializer
int 0
char ‘\0’
float 0
double 0
pointer NULL

It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.

‘this’ pointer in C++

The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
For a class X, the type of this pointer is ‘X* const’. Also, if a member function of X is declared as const, then the type of this pointer is ‘const X *const’.

Following are the situations where ‘this’ pointer is used:

1) When local variable’s name is same as member’s name

#include
using namespace std;
 
/* local variable is same as a member's name */
class Test
{
private:
   int x;
public:
   void setX (int x)
   {
       // The 'this' pointer is used to retrieve the object's x
       // hidden by the local variable 'x'
       this->x = x;
   }
   void print() { cout << "x = " << x << endl; }
};
 
int main()
{
   Test obj;
   int x = 20;
   obj.setX(x);
   obj.print();
   return 0;
}

Output:

x = 20

Static

Static

Los métodos static no requieren una instancia de la clase, ni pueden acceder a los datos de la clase/objeto de forma implícita.

Un método static se distingue en algunos lenguajes de programación con la palabra clave static colocada en algún lugar en la firma del método.

Los metodos estaticos se cargan en memoria en tiempo de compilación y no a medida que se ejecutan las líneas de código del programa. Van precedidos del modificador static. Para invocar a un método estático no se necesita crear un objeto de la clase en la que se define:

  • Si se invoca desde la clase en la que se encuentra definido, basta con escribir su nombre.
  • Si se le invoca desde una clase distinta, debe anteponerse a su nombre, el de la clase en la que se encuentra seguido del operador punto (.) .metodoEstatico

Suelen emplearse para realizar operaciones comunes a todos los objetos de la clase.

Dado que los métodos estáticos tienen sentido a nivel de clase y no a nivel de objeto (instancia) los métodos estáticos no pueden acceder a datos miembros que no sean estáticos.

C++

Class MyClass {
public:
static float areaCirc (radio){
  //do some math here
  return area;
 }
};

Java

public class Mechanics {

    // add an instance variable for the object ID    
    private int cadence;
    private int gear;
    private int speed;

    //static method
    public static double speedURM (int dist, float time){
     // do some math here
    return urmSpeed;
}
}

Static methods

Static

 

Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance. A static method is distinguished in some programming languages with the static keyword placed somewhere in the method’s signature.

In statically typed languages such as Java, static methods are called “static” because they are resolved statically (i.e. at compile time) based on the class they are called on and not dynamically as in the case with instance methods which are resolved polymorphically based on the runtime type of the object. Therefore, static methods cannot be overridden.

C++

Class MyClass {
public:
static float areaCirc (radio){
  //do some math here
  return area;
 }
};

Java

public class Mechanics {

    // add an instance variable for the object ID    
    private int cadence;
    private int gear;
    private int speed;

    //static method
    public static double speedURM (int dist, float time){
     // do some math here
    return urmSpeed;
}
}