Imagine an exercise that asks you to read the grades of 30 students, compute the average and then list the students above it. With simple variables you would need nota1, nota2 … nota30 — thirty variables and thirty Leer instructions. And you still couldn't loop over them. Arrays solve this: a single name that holds many values, each identified by a position number called an index.
In this guide you'll learn to create arrays with Dimension, fill and print them with loops, perform the classic operations (sum, average, maximum, search, count, sort) and work with two-dimensional matrices. Every program is complete and runs in the PSeInt online editor, where the Variables tab shows the full contents of each array as it changes.
What is an array?
An array (arreglo or vector in Spanish course material) is a fixed-size collection of values of the same type, stored under one name. Think of a row of numbered lockers:
| Index | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
notas | 7.5 | 9 | 6 | 8.5 | 10 |
notas[3] is 6. notas[5] is 10. The index can be a number, a variable or any expression that results in a whole number — and that is what makes arrays so powerful together with loops.
Declaring an array with Dimension
Definir notas Como Real
Dimension notas[30]
Definirsets the type of the elements (all elements share it).Dimensioncreates the array and fixes its size — here, 30 elements.- You can create several arrays in one line:
Dimension a[10], b[20]. - The size can be a variable you have already read, such as
Dimension notas[n].
[1] and the last is [size]. Some university profiles switch to zero-based arrays ([0] to [size-1]), like C or Java. Our online editor uses base 1. Accessing a position outside the valid range causes an error.Filling and printing an array
The Para loop is the natural companion of arrays: its control variable walks every index.
Algoritmo LlenarYMostrar
Definir n, i Como Entero
Definir notas Como Real
Escribir "¿Cuántos alumnos?"
Leer n
Dimension notas[n]
Para i <- 1 Hasta n Hacer
Escribir "Nota del alumno ", i, ":"
Leer notas[i]
FinPara
Escribir "Notas ingresadas:"
Para i <- 1 Hasta n Hacer
Escribir "Alumno ", i, ": ", notas[i]
FinPara
FinAlgoritmo
To fill an array with calculated values instead of input, assign inside the loop, for example the squares of 1 to 10: cuadrados[i] <- i * i.
Sum, average and values above the average
Here is the exercise from the introduction, solved. Notice that it needs two passes over the data: one to compute the average and another to compare each grade with it. That second pass is impossible without an array.
Algoritmo SobreElPromedio
Definir n, i, cantidad Como Entero
Definir notas, suma, promedio Como Real
n <- 5
Dimension notas[n]
notas[1] <- 7.5
notas[2] <- 9
notas[3] <- 6
notas[4] <- 8.5
notas[5] <- 4
suma <- 0
Para i <- 1 Hasta n Hacer
suma <- suma + notas[i]
FinPara
promedio <- suma / n
Escribir "Promedio: ", promedio
cantidad <- 0
Para i <- 1 Hasta n Hacer
Si notas[i] > promedio Entonces
Escribir "Alumno ", i, " supera el promedio con ", notas[i]
cantidad <- cantidad + 1
FinSi
FinPara
Escribir cantidad, " alumnos superan el promedio"
FinAlgoritmo
The average is 7, so students 1, 2 and 4 are listed. We used fixed values so you can check the result by hand; replace them with a reading loop for a real program.
Maximum, minimum and their positions
Often you need not only the largest value but where it is. Track the index instead of the value:
Algoritmo PosicionDelMayor
Definir v, i, pos Como Entero
Dimension v[6]
v[1] <- 14
v[2] <- 3
v[3] <- 27
v[4] <- 9
v[5] <- 27
v[6] <- 1
pos <- 1
Para i <- 2 Hasta 6 Hacer
Si v[i] > v[pos] Entonces
pos <- i
FinSi
FinPara
Escribir "El mayor es ", v[pos], " en la posición ", pos
FinAlgoritmo
The result is "27 en la posición 3". Because the comparison is strict (>), the first occurrence wins; change it to >= to get the last one.
Searching an array
Linear search checks each element in order until it finds the value. Using Mientras with a flag lets it stop as soon as the value appears:
Algoritmo BusquedaLineal
Definir datos, i, buscado Como Entero
Definir encontrado Como Logico
Dimension datos[8]
Para i <- 1 Hasta 8 Hacer
datos[i] <- i * 5
FinPara
Escribir "Número a buscar:"
Leer buscado
encontrado <- Falso
i <- 1
Mientras i <= 8 Y NO encontrado Hacer
Si datos[i] = buscado Entonces
encontrado <- Verdadero
SiNo
i <- i + 1
FinSi
FinMientras
Si encontrado Entonces
Escribir "Encontrado en la posición ", i
SiNo
Escribir "No está en el arreglo"
FinSi
FinAlgoritmo
The array contains 5, 10, 15 … 40. Search for 25 and the program reports position 5; search for 7 and it reports that the value is not there.
Sorting: the bubble sort algorithm
Sorting is a classic exam topic. Bubble sort compares neighbouring elements and swaps them when they are in the wrong order. After each full pass, the largest remaining element has "bubbled" to the end, so each pass can stop one position earlier.
Algoritmo Burbuja
Definir v, i, j, aux, n Como Entero
n <- 6
Dimension v[n]
v[1] <- 42
v[2] <- 8
v[3] <- 23
v[4] <- 57
v[5] <- 3
v[6] <- 15
Para i <- 1 Hasta n - 1 Hacer
Para j <- 1 Hasta n - i Hacer
Si v[j] > v[j + 1] Entonces
aux <- v[j]
v[j] <- v[j + 1]
v[j + 1] <- aux
FinSi
FinPara
FinPara
Para i <- 1 Hasta n Hacer
Escribir Sin Saltar v[i], " "
FinPara
Escribir ""
FinAlgoritmo
Output: 3 8 15 23 42 57. Pay attention to the swap: it needs an auxiliary variable (aux), because assigning v[j] <- v[j+1] directly would lose the original value of v[j]. Step through the program in the online editor and watch the array in the Variables tab — the "bubbling" becomes obvious.
To sort in descending order, change > to < in the comparison.
Matrices: two-dimensional arrays
A matrix organises values in rows and columns, like a spreadsheet or a game board. Give Dimension two sizes, and use two indices — row first, then column — to access an element.
Definir m Como Entero
Dimension m[3, 4] // 3 filas y 4 columnas
m[2, 3] <- 99 // fila 2, columna 3
Walking a matrix requires two nested loops: the outer one moves through the rows, the inner one through the columns of the current row.
Algoritmo TablaDeMultiplicar
Definir t, f, c Como Entero
Dimension t[5, 5]
Para f <- 1 Hasta 5 Hacer
Para c <- 1 Hasta 5 Hacer
t[f, c] <- f * c
FinPara
FinPara
Para f <- 1 Hasta 5 Hacer
Para c <- 1 Hasta 5 Hacer
Escribir Sin Saltar t[f, c], " "
FinPara
Escribir ""
FinPara
FinAlgoritmo
The tab character inside the quotes aligns the columns. The result is the 5×5 multiplication table, printed row by row.
Row and column totals
Algoritmo VentasPorSucursal
Definir ventas, f, c, totalFila, totalCol Como Entero
Dimension ventas[3, 4]
Para f <- 1 Hasta 3 Hacer
Para c <- 1 Hasta 4 Hacer
ventas[f, c] <- f * 10 + c
FinPara
FinPara
Para f <- 1 Hasta 3 Hacer
totalFila <- 0
Para c <- 1 Hasta 4 Hacer
totalFila <- totalFila + ventas[f, c]
FinPara
Escribir "Sucursal ", f, ": ", totalFila
FinPara
Para c <- 1 Hasta 4 Hacer
totalCol <- 0
Para f <- 1 Hasta 3 Hacer
totalCol <- totalCol + ventas[f, c]
FinPara
Escribir "Trimestre ", c, ": ", totalCol
FinPara
FinAlgoritmo
Each row is a branch and each column a quarter. Notice how swapping the order of the loops changes what you add up: rows in the first block, columns in the second. Resetting the accumulator inside the outer loop is essential — otherwise each total would include the previous ones.
The main diagonal
In a square matrix, the main diagonal contains the elements where row and column are equal: m[1,1], m[2,2], m[3,3]. You only need one loop to visit them: suma <- suma + m[i, i]. The examples page has a complete "Matrix (2D Array)" program that does exactly this.
Parallel arrays
When each item has several pieces of data — a student's name and grade, a product's code and price — a common technique is to use parallel arrays: several arrays of the same size where the same index refers to the same item. nombres[3] and notas[3] describe the third student. Just remember to swap the elements of every array when you sort them, or the data gets mixed up.
Passing arrays to functions
Arrays can be passed to a SubProceso or Funcion. They are passed by reference, so the subprocess can modify the original — very convenient for "fill" or "sort" routines.
SubProceso Llenar(v, n)
Definir i Como Entero
Para i <- 1 Hasta n Hacer
v[i] <- i * i
FinPara
FinSubProceso
Funcion total <- Sumar(v, n)
Definir i Como Entero
total <- 0
Para i <- 1 Hasta n Hacer
total <- total + v[i]
FinPara
FinFuncion
Algoritmo ArreglosYFunciones
Definir cuadrados Como Entero
Dimension cuadrados[10]
Llenar(cuadrados, 10)
Escribir "Suma de los cuadrados del 1 al 10: ", Sumar(cuadrados, 10)
FinAlgoritmo
The result is 385. Passing the size as a second parameter (n) keeps the subprocesses reusable for arrays of any length.
Common mistakes with arrays
- Index out of range. With
Dimension v[10],v[0]andv[11]don't exist in base 1. Watch the limits of your loops, especially in bubble sort, wherev[j + 1]requiresjto stop atn - 1. - Using the array before Dimension. Create the array before reading or writing its elements.
- Dimensioning twice. An array can be dimensioned only once.
- Printing the whole array at once.
Escribir vdoesn't print the elements; loop through them. - Swapping without an auxiliary variable. You'll end up with two copies of the same value.
- Forgetting to reset accumulators in nested loops (row totals, column totals).
Practice exercises
- Read 10 numbers and print them in reverse order.
- Count how many elements of an array are even.
- Copy the positive elements of one array into a second array and print it.
- Read a 3×3 matrix and print its transpose (rows become columns).
- Store the temperatures of a week and print the days that were above the weekly average.
Once arrays feel natural, look at how your algorithms translate into diagrams in the PSeInt flowcharts guide.
Frequently asked questions
Do arrays in PSeInt start at 0 or 1?
At 1 in the default flexible profile. Some profiles chosen by universities use base 0. Check which profile your course uses; our online editor uses base 1.
Can I change the size of an array after creating it?
No. The size is fixed by Dimension. If you don't know how many values you'll get, read the quantity first and then dimension the array with that variable.
Can an array hold text?
Yes. Declare it with Definir nombres Como Caracter before Dimension nombres[20], and each element will hold a string.
How many dimensions can an array have?
Two (matrices) are by far the most common in exercises. Our online editor accepts more, but most course exercises never need them.