Fundamentals of Programming Logic and Algorithms

Classified in Computers

Written on in English with a size of 118.85 KB

What is an Algorithm?

An algorithm is formally defined as a finite sequence of steps that lead to the execution of a specific task. Common examples include the basic operations of arithmetic—addition, multiplication, division, and subtraction—performed on real decimal numbers.

Core Characteristics of Algorithms

An algorithm must possess four essential characteristics:

  • Finite: It must eventually come to an end.
  • Definite: Each step must be precisely defined.
  • Inputs: It receives zero or more quantities from the outside.
  • Outputs: It produces at least one result.

Forms of Representation

Algorithms can be represented through various methods:

  • Narrative Description: Using natural language.
  • Flowchart: A conventional graphical representation.
  • Pseudocode: Also known as Structured Portuguese or Portugol.

Basic Control Structures

  • Simple Sequence: Linear execution of steps.
  • Alternatives (Conditional): Branching logic based on conditions.
  • Repetition: Loops that allow actions to be repeated.

Flowchart Symbols and Meanings

Imagen
Terminal: Indicates the starting or stopping point of a program flow.

Imagen
Processing: Indicates arithmetic calculations, formula evaluations, or value distributions.

Imagen
Display: Used for information shown on the video or screen.

Imagen
Keyboard: Represents information received by the computer via manual input.

Imagen
Decision: Indicates a comparison or question with two possible answers: Yes or No.

Imagen
Arrows: Indicate the direction of the process flow.

Imagen
Connector: Used to partition or join parts of a diagram.

Data Storage and Memory Management

Imagen

  • Each memory cell occupies one byte.
  • Each data type requires a specific amount of memory to store information.
  • To retrieve information, the system needs to know the data type (the number of bytes) and the starting position in memory.

For example, to retrieve the string "banana", we know it occupies 6 bytes and starts at position 18. To simplify this, the concept of a variable was created. A variable acts as a reference to an original memory address associated with a specific data type.

Variables and Basic Data Types

All variables belong to a data type that defines the set of values they can store. Basic types include:

  • Number: Integer and Real.
  • Literal: Character or String.
  • Logic: Boolean values (True/False).

Stages of Algorithm Development

To develop an effective algorithm, the problem must be divided into three key stages:

  1. Input: Data provided to solve the problem.
  2. Processing: The transformation of inputs into results.
  3. Output: The final results generated.

Pseudocode Structure and Syntax

In pseudocode, specific keywords define the structure:

  • Algorithm <name>: Marks the beginning and identifies the algorithm.
  • Var: The section where global variables are declared.
  • Start (Inicio): Delimits the beginning of the instruction set.
  • End Algorithm (FimAlgoritmo): Delimits the end of the instruction set.

Detailed Data Types

  • Integer: Positive or negative whole numbers (e.g., 35, 0, -56).
  • Real: Positive, negative, and fractional numbers (e.g., 1.2, -45.987).
  • Character: Sequences of letters, numbers, and symbols enclosed in quotation marks (e.g., "Alpha Street", "574-9988"). Also called strings.
  • Logical: Boolean values representing True or False.

Rules for Naming Identifiers

Variables and constants must follow these naming principles:

  • The first character must always be a letter.
  • Names should consist of letters and numbers only.
  • Use underscores (_) to separate words; do not use blank spaces.
  • Names should be explanatory but not excessively long.
  • Do not use accents, cedillas, or reserved language keywords.

Arithmetic and Logical Operators

Imagen

Logical Operators: Used to combine relational expressions, returning True or False.

Imagen

Truth Table

Imagen

Primitive Instructions and Commands

These are basic commands for input, output, and memory transfer.

Assignment Command

The primary way to store information in a variable. In Visualg, the assignment operator is <-.

Example:
Algorithm ExampleAssignment
Var
  price_unit, price_tot: real
  quant: integer
Start
  price_unit <- 5.0
  quant <- 10
  price_tot <- price_unit * quant
EndAlgorithm

Control Flow Structures

  • Sequential: Commands are executed in a predetermined order, one after another.
  • Decision: The flow is chosen based on logical expressions. Types include Simple (If...Then), Composite (If...Then...Else), and Multiple Choice (Case).
  • Repetition: Used to execute blocks multiple times.
    • Repeat/Until: Executes at least once; tests condition at the end.
    • While/Do: Executes while a condition is true; tests at the start.
    • For/To: Executes a specific number of times based on a counter.

Logic Programming and Variable Concepts

Logic Programming refers to the organized order of instructions to solve a problem. A Variable is a region in the computer's memory identified by a name, used to store data temporarily. It consists of an identifier (the name) and content (the value).

Practical Algorithm Exercises

Exercise 1: Credit Calculation

A bank grants credit based on the average balance of the last year:

  • 0-200: No credit.
  • 201-400: 20% of average balance.
  • 401-600: 30% of average balance.
  • Over 601: 40% of average balance.

Algorithm AverageBalance
Var
  avg_bal, credit_val: real
  name: character
Start
  Read(name, avg_bal)
  If avg_bal <= 200 Then credit_val <- 0
  Else If avg_bal <= 400 Then credit_val <- avg_bal * 0.20
  Else If avg_bal <= 600 Then credit_val <- avg_bal * 0.30
  Else credit_val <- avg_bal * 0.40
  Write(name, avg_bal, credit_val)
EndAlgorithm

Exercise 2: Flowchart to Pseudocode

Imagen

Answer:
Algorithm Enlistment
Var
  name, health, sex: character
  age: integer
Start
  Read(name, sex)
  If sex = "F" Then Write("Not applicable for females")
  Else
    Read(age)
    If (age < 16) or (age > 20) Then Write("Not applicable due to age")
    Else
      Read(health)
      If health = "S" Then Write("Fit")
      Else Write("Not fit due to health")
  EndIf
EndAlgorithm

Exercise 3: Fuel Consumption

Calculate fuel spent on a trip (12 KM/L) given time and speed.

Algorithm TripCalculation
Var
  time, avg_speed, distance, liters: real
Start
  Read(avg_speed, time)
  distance <- time * avg_speed
  liters <- distance / 12
  Write("Distance:", distance, "Liters:", liters)
EndAlgorithm

Exercise 4: Health Insurance Pricing

Determine insurance cost based on age:

  • Up to 10 years: $30.00
  • 11 to 29 years: $60.00
  • 30 to 45 years: $120.00
  • 46 to 59 years: $150.00
  • 60 to 65 years: $250.00
  • Over 65 years: $400.00

Related entries: