Introduction to Algorithms and Programming Logic

Basic Elements of Programming and Data Types

Data types are defined as properties or attributes of data that determine the specific values they can represent and the operations that can be performed with them. Every programming language defines the specific data types it can manipulate. In general terms for algorithms, data types are categorized as follows:

  1. Numerics
  • Integer (int): Occupies 4 bytes4\,bytes in both 32 bit32\,bit and 64 bit64\,bit systems.
  • Floating Point (float): Occupies 4 bytes4\,bytes in both 32 bit32\,bit and 64 bit64\,bit systems.
  • Double: Occupies 8 bytes8\,bytes in both 32 bit32\,bit and 64 bit64\,bit systems.
  • Long Double: Occupies 16 bytes16\,bytes in both 32 bit32\,bit and 64 bit64\,bit systems.
  1. Text
  • Character (char): Occupies 1 byte1\,byte in both 32 bit32\,bit and 64 bit64\,bit systems.
  • String (cadena): Occupies 1 byte1\,byte per character in both 32 bit32\,bit and 64 bit64\,bit systems.
  1. Logical (Boolean)
  • True (Verdadero): Represented as 11.
  • False (Falso): Represented as 00.
  1. Date: Specialized type for handling dates.

  2. Abstract: Includes classes or objects.

The Null Value: Defined as the absence of a value within a variable or structure.

According to the space they occupy in memory, data types are classified into:

  • Static: These include Simple or Primary types. Ordinal types consist of integer, logical, and text. Non-ordinal types consist of real numbers. Structured types include ordered or unordered collections and structures of different types.
  • Dynamic: These include Pointers, which occupy between 4 bytes4\,bytes and 8 bytes8\,bytes.

Variables, Constants, and Operators

Variables and Constants A variable in programming is the symbolic name assigned to a memory space containing a piece of data or value that can change throughout the execution of the algorithm. Conversely, a constant is a symbolic name for a memory space that maintains the same data value throughout the entire algorithm.

Arithmetic Operators These operators perform mathematical operations on operands:

  • Suma (+): Addition.
  • Resta (-): Subtraction.
  • Multiplicación (*): Multiplication.
  • División (/): Division.
  • Potencia ():** Power/Exponentiation.
  • Residuo (%): Remainder/Modulus.
  • Asignación simple (=): Simple assignment.

Relational Operators These allow comparison operations between two operands (variable and variable, or variable and value), forming a condition to test validity. The result of a relational expression is 11 (true) if the condition is met and 00 (false) if it is not.

  • Igual (==): Equal to.
  • Distinto de (!=): Not equal to.
  • Mayor que (>): Greater than.
  • Mayor o igual que (>=): Greater than or equal to.
  • Menor que (
  • Menor o igual que (

Logical Operators Logical operators allow for the unification of conditions and the validation of their fulfillment. The union can be mandatory using "and" (&&) or optional using "or" (∣∣||). The operator "!" represents "not" or negation. The operational hierarchy dictates that "and" operations are processed before "or" operations, similar to how multiplication precedes addition in mathematics. Parentheses ()() can be used to override the default hierarchy of arithmetic or logical operations.

Logical Truth Tables:

  • 1\,&&\,1 = 1
  • 1\,&&\,0 = 0
  • 0\,&&\,1 = 0
  • 0\,&&\,0 = 0
  • 1 ∣∣ 1=11\,||\,1 = 1
  • 1 ∣∣ 0=11\,||\,0 = 1
  • 0 ∣∣ 1=10\,||\,1 = 1
  • 0 ∣∣ 0=00\,||\,0 = 0

Monary (Unary) and Assignment Operators

  • Increment (++): Example: i++i++ is equivalent to i=i+1i = i + 1. If i=5i = 5, the result is 66.
  • Decrement (--): Decreases value by 11.
  • Compound Assignment (=, /=, +=, -=):   - i </em>= 5i\,</em>=\,5 is i=i×5i = i \times 5.   - i −= −2i\,-=\,-2 is i=i−(−2)i = i - (-2), resulting in i=5+2=7i = 5 + 2 = 7.

Expressions and Conditions

An Expression is a combination of values and operations that produces a result, which can be assigned to a variable (e.g., j=j−1j = j - 1).

A Condition is an expression or set of expressions that results in true (11) or false (00).

  • Simple Condition: Compares two elements using relational operators (e.g., x>yx > y).
  • Compound Condition: Consists of several simple conditions joined by logical operators (e.g., ((edad >= 18)\,&&\,(libras > 10))\,||\,(libras < 50)).

Example Evaluation: If edad=20edad = 20 and libras=25libras = 25: Expression: (edad >= 18\,&&\,libras > 10)\,||\,(libras < 50) Substitution: (20 >= 18\,&&\,25 > 10)\,||\,(25 < 50) Logical Evaluation: (1\,&&\,1)\,||\,1 \rightarrow 1\,||\,1 \rightarrow 1 (True).

Basic Operations and Structures in an Algorithm

There are four basic operations in an algorithm:

  1. Declaration: Assigns the data type (e.g., "entero x;").
  2. Reading (Lectura): Obtains input data (e.g., "leer(x);").
  3. Writing (Escritura): Presents results on screen or paper (e.g., "imprimir(x);").
  4. Processing: Performs operations through specific structures.

Sequential Structures:

  • Simple: Value assignment (e.g., x=15;x = 15;).
  • Counter (Contador): Increment or decrement by a constant (e.g., x=x+1;x = x + 1;).
  • Accumulator (Acumulador): Increment or decrement by a variable value (e.g., x=x+y;x = x + y;).
  • Work: Expressions using constants and variables (e.g., x=1+x×(x+y);x = 1 + x \times (x + y);).

Alternative (Conditional) Structures:

  • Simple: Executes an action if a condition is met (Si).
  • Double: Executes one block if true, and a different block if false (Si-de otro modo).
  • Multiple Nested: Evaluates several alternative conditions (Si-de otro modo si).
  • Multiple Selection: Evaluates a variable and executes instructions based on its assigned value (Segun).

Repetitive (Iterative) Structures: These execute instructions until conditions are met, utilizing loops:

  • Mientras (While)
  • Hasta que (Repeat/Until)
  • Para (For)

Desktop Testing and Debugging

Depuración (Debugging): The process of eliminating errors. Because complexity increases the probability of human error, the following principles should be applied:

  • Make every effort to force the algorithm to fail.
  • Include all possible situations, both normal and exceptional.
  • Verify all results with skepticism.

Prueba de Escritorio (Desktop Test): A manual execution of the algorithm to verify results without a programming language. It requires a record of input data, variables, process assignments, and final results.

Steps to Resolve an Algorithm:

  1. Problem Definition
  2. Analysis and Design:    - Input: Identify data provided, data to be entered, and necessary variables.    - Process: Identify operations required to reach the output.    - Output: Identify the result requested by the problem.
  3. Programming:    - Algorithm construction.    - Desktop Testing (UTP format).    - Debugging.

Algorithm Structure and Example

General Structure:

Algoritmo NombreAlgoritmo {
    // Bloque Declarativas de Constantes
    tipo_de_datos NOMBRE_CONSTANTE = valor;

    // Bloque Declarativas de Variables
    tipo_de_datos nombreVariable1, nombreVariable2;

    // Bloque de Instrucciones
    imprimir("texto:");
    leer(nombre_variable1);
}

Example: Calculating Vehicle Distance

  • Problem: Calculate distance (kmkm) at constant velocity (km/hkm/h) over time (hh). If distance exceeds 1,000 km1,000\,km, prompt maintenance; otherwise, show distance.
  • Input: Velocity (VV), Time (TT). Variables are integers.
  • Process: distancia=velocidad×tiempodistancia = velocidad \times tiempo.
  • Logic: If Distancia>=1,000Distancia >= 1,000 then "Debe realizar el mantenimiento del auto", else "Distancia".

Algorithm Implementation:

Algoritmo CalculoDistancia {
    entero v, t, d;
    imprimir("Ingrese la velocidad");
    leer(v);
    imprimir("Ingrese el tiempo");
    leer(t);
    d = v * t;
    si (d > 1000) {
        imprimir("Debe realizar el mantenimiento del auto");
    } de otro modo {
        imprimir(d);
    }
}

Desktop Test Example (SumaTresValores Trace):

  1. Variable declaration: v=?,t=?,d=?v = ?, t = ?, d = ?
  2. Screen: "Ingrese la velocidad"
  3. User Input/Memory: v=5v = 5
  4. Screen: "Ingrese el tiempo"
  5. User Input/Memory: t=4t = 4
  6. Arithmetic Operation: d=5×4=20d = 5 \times 4 = 20
  7. Logic Operation: Is 20>1,00020 > 1,000? (False)
  8. Screen: "20"

Rules and Best Practices

  1. Start with the word "Algoritmo" followed by the name.
  2. Use curly braces { } for the body and instruction blocks.
  3. End instructions with a semicolon (;).
  4. Use indentation (sangría).
  5. Use comments: // for single lines or /* */ for blocks to identify Constant, Variable, and Instruction sections.
  6. Use only specified types: entero, flotante, cadena, caracter.
  7. Use standard operators (++, −-, <em><em>, //, </em>∗</em>*, %, ====, !=!=, >>, <<, >=>=, <=<=, &&, ∣∣||, !!, ==).
  8. Naming Nomenclature:    - Constants: UPPERCASE.    - Variables: camelCase (e.g., nombreApellidoCasada).    - Functions: camelCase.    - Instructions (leer, imprimir): lowercase.    - Control Structures: lowercase.