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:
- Numerics
- Integer (int): Occupies in both and systems.
- Floating Point (float): Occupies in both and systems.
- Double: Occupies in both and systems.
- Long Double: Occupies in both and systems.
- Text
- Character (char): Occupies in both and systems.
- String (cadena): Occupies per character in both and systems.
- Logical (Boolean)
- True (Verdadero): Represented as .
- False (Falso): Represented as .
Date: Specialized type for handling dates.
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 and .
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 (true) if the condition is met and (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
Monary (Unary) and Assignment Operators
- Increment (++): Example: is equivalent to . If , the result is .
- Decrement (--): Decreases value by .
- Compound Assignment (=, /=, +=, -=): - is . - is , resulting in .
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., ).
A Condition is an expression or set of expressions that results in true () or false ().
- Simple Condition: Compares two elements using relational operators (e.g., ).
- Compound Condition: Consists of several simple conditions joined by logical operators (e.g., ((edad >= 18)\,&&\,(libras > 10))\,||\,(libras < 50)).
Example Evaluation: If and : 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:
- Declaration: Assigns the data type (e.g., "entero x;").
- Reading (Lectura): Obtains input data (e.g., "leer(x);").
- Writing (Escritura): Presents results on screen or paper (e.g., "imprimir(x);").
- Processing: Performs operations through specific structures.
Sequential Structures:
- Simple: Value assignment (e.g., ).
- Counter (Contador): Increment or decrement by a constant (e.g., ).
- Accumulator (Acumulador): Increment or decrement by a variable value (e.g., ).
- Work: Expressions using constants and variables (e.g., ).
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:
- Problem Definition
- 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.
- 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 () at constant velocity () over time (). If distance exceeds , prompt maintenance; otherwise, show distance.
- Input: Velocity (), Time (). Variables are integers.
- Process: .
- Logic: If 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):
- Variable declaration:
- Screen: "Ingrese la velocidad"
- User Input/Memory:
- Screen: "Ingrese el tiempo"
- User Input/Memory:
- Arithmetic Operation:
- Logic Operation: Is ? (False)
- Screen: "20"
Rules and Best Practices
- Start with the word "Algoritmo" followed by the name.
- Use curly braces
{ }for the body and instruction blocks. - End instructions with a semicolon (
;). - Use indentation (sangría).
- Use comments:
//for single lines or/* */for blocks to identify Constant, Variable, and Instruction sections. - Use only specified types: entero, flotante, cadena, caracter.
- Use standard operators (, , , , , , , , , , , , &&, , , ).
- Naming Nomenclature:
- Constants: UPPERCASE.
- Variables: camelCase (e.g.,
nombreApellidoCasada). - Functions: camelCase. - Instructions (leer, imprimir): lowercase. - Control Structures: lowercase.