01 · Scope
About Portugol Studio 2.0
Portugol is a name used for several pseudolanguages. This page covers Portugol Studio 2.0 specifically; its rules do not define one universal standard for every pseudolanguage called Portugol.
The rules presented here describe the Portugol Studio 2.0 pseudolanguage and follow the sources listed at the end of this reference.
02 · Organization
Program structure
A file starts with programa and a block enclosed in braces. Library includes appear at the beginning of the block; global declarations and functions may follow. The conventional entry point is a function named inicio.
programa {
inclua biblioteca Matematica --> mat
const inteiro tentativas = 3
inteiro acertos = 0
funcao inicio() {
escreva("Welcome to the exercise")
}
}
Functions, conditions and loops use { and } for blocks. Semicolons separate the three fields in a para header; common examples place one statement on each line without ending every statement with a semicolon.
03 · Writing
Names, comments and literals
- Identifiers start with an ASCII letter or underscore; following characters may be ASCII letters, digits or underscores. The published grammar does not allow accented letters in identifiers.
- Keywords are written without accents and the grammar recognizes their lowercase forms, such as
programa,funcaoandenquanto. - Line comments start with
//; block comments are enclosed by/*and*/. - Real numbers use a period as the decimal separator. Strings use double quotes and individual characters use single quotes; the lexer also defines escapes and hexadecimal literals.
- Logical values are
verdadeiroandfalso.
// line comment
/* block
comment */
cadeia mensagem = "Hello"
caracter inicial = 'A'
real media = 7.5
logico aprovado = verdadeiro
04 · Data
Types, variables and constants
| Type | Use |
|---|---|
inteiro | Whole numbers. |
real | Numbers with a fractional part. |
logico | verdadeiro or falso values. |
caracter | A single character. |
cadeia | A sequence of characters. |
vazio | Marks a function with no return value. |
Place the type before the name. A declaration can group names of the same type and include an initial expression. The const keyword marks constant declarations. Values and types must be compatible.
inteiro idade = 18, ano
real altura = 1.72
const real pi_aproximado = 3.14
cadeia nome = "Lia"
logico concluiu = falso
A variable declared inside a function or block has local scope; declarations in the main program outside functions are global. Declarations also allow vector and matrix initializers, described in Vectors and matrices.
05 · Expressions
Operators and precedence
| Group | Operators | Meaning |
|---|---|---|
| Arithmetic | + - * / % | Addition, subtraction, multiplication, division and remainder. |
| Unary | + - nao ~ ++ -- | Sign, logical negation, bitwise negation, increment and decrement. ++ and -- may appear before or after an identifier. |
| Assignment | = += -= *= /= | Simple and compound assignment. = is not the equality operator. |
| Comparison | == != > < <= >= | Equality, inequality and relational comparisons. |
| Logical | e ou | Logical conjunction and disjunction. |
| Bitwise | ^ << >> & | | XOR, left and right shifts, bitwise AND and OR. |
| Grouping | ( ) | Explicitly controls evaluation order. |
The official grammar defines operators through recursive alternatives, but it does not publish a clear precedence table for every combination. Use parentheses to make evaluation order explicit, especially when mixing comparisons, logic and bitwise operations.
06 · Interaction
Input and output
escreva displays one or more expressions. To start a new line, include the \n escape sequence in a string passed to the function. leia reads values into variables. The predefined function limpa() clears the output area.
programa {
funcao inicio() {
cadeia nome
escreva("What is your name? ")
leia(nome)
escreva("Hello, ", nome, "!\n")
}
}
The way data is displayed and read depends on the functions and libraries available in the runtime described by the references.
07 · Decisions
Conditions and selection
se runs a branch when a logical expression is true; senao defines the alternative branch. Blocks can contain multiple statements. Multiway selection uses escolha, caso labels and the fallback case contrario.
se (nota >= 7) {
escreva("Passed\n")
} senao {
escreva("Keep practicing\n")
}
escolha (opcao) {
caso 1:
escreva("Start\n")
pare
caso contrario:
escreva("Unknown option\n")
}
pare ends the current escolha case or exits a loop. Use a logical expression as the condition.
08 · Loops
Repetition
Portugol Studio 2.0 defines conditional loops and a loop with initialization, condition and increment fields:
inteiro contador = 1
enquanto (contador <= 3) {
escreva(contador, "\n")
contador++
}
faca {
contador--
} enquanto (contador > 0)
para (inteiro i = 0; i < 3; i++) {
escreva(i, "\n")
}
enquanto checks before each repetition; faca ... enquanto checks after the block. In para, semicolons separate fields that can initialize a variable, check a condition and update a counter. pare exits the current loop.
09 · Collections
Vectors and matrices
Vectors use one index in square brackets; matrices use two. An explicit size must be a positive integer constant expression; in declarations with an initializer, the size can be inferred. The grammar also allows matrices initialized by rows.
programa {
funcao inicio() {
inteiro notas[3] = {8, 9, 10}
inteiro quadro[2][2] = {{1, 2}, {3, 4}}
escreva(notas[0], "\n")
escreva(quadro[1][0], "\n")
}
}
Indices are integer expressions. Function parameters can declare dimensions without fixed sizes, for example inteiro valores[] or inteiro tabela[][].
10 · Reuse
Functions and parameters
A function may declare its return type before its name; omitting the type means it returns no value, which may also be written as vazio. Parameters have a type and name, can be comma-separated, and may receive vectors or matrices. An & before the name marks a reference parameter.
funcao inteiro dobrar(inteiro valor) {
retorne valor * 2
}
funcao atualizar(inteiro &total, inteiro acrescimo) {
total += acrescimo
}
funcao inicio() {
inteiro resultado = dobrar(4)
atualizar(resultado, 1)
escreva(resultado, "\n")
}
retorne ends the function and may return an expression. The official reference describes calls in expressions, functions with return values and functions without one.
11 · Standard resources
Portugol Studio 2.0 libraries
Include a library with inclua biblioteca Name; an alias may follow -->. Calls use the name or alias followed by a period. The table summarizes the pseudolanguage modules documented in the sources for this reference; class documentation lists signatures, parameters and constants.
| Library | Reference features |
|---|---|
Arquivos | Open, close, read and write files; check end of file, select files, list files and folders, create folders, replace text, and check or delete files. |
Calendario | Day, month, year, hour, minute, second, millisecond and weekday names. |
Graficos | Graphics windows, geometric drawings, images, GIF animation, text, fonts, colors, gradients, dimensions, full-screen mode and visual transformations. |
Internet | Timeout, read content from an address, download images and check availability. |
Matematica | PI, potencia, raiz, arredondar, logaritmo, sine, cosine, tangent, absolute value, maximum and minimum. |
Mouse | Check buttons and pointer position; hide or show the cursor. |
Objetos | Create objects from JSON/XML or properties, read and assign typed properties, work with property vectors, and release or export objects. |
ServicosWeb | Web connections and requests, headers and parameters; get, publish, update and delete data. |
Sons | Load, play, pause, stop and release sounds; read position, duration and volume. |
Teclado | Check and read keys and characters, with constants for common keys, letters, numbers and function keys. |
Texto | numero_caracteres, caixa_alta, caixa_baixa, substituir, preencher_a_esquerda, obter_caracter, posicao_texto and extrair_subtexto. |
Tipos | Check whether text represents numbers, logical values or characters, and convert among strings, integers, reals, logical values and characters. |
Util | User directory, vector and matrix sizes, random values, wait and elapsed time. |
inclua biblioteca Matematica --> mat
funcao inicio() {
escreva(mat.potencia(2, 3), "\n")
}
The libraries belong to the Portugol Studio 2.0 reference environment; not every library fits every interpreter or execution context.
Signatures and results
The calls below use the mat alias from the previous example. Functions return values that can be assigned to variables or combined in expressions.
| Library | Signature or call | Behavior |
|---|---|---|
Matematica | potencia(base, expoente) | Returns a real value with the base raised to the exponent. Example: potencia(2, 3) returns 8. |
Matematica | raiz(radicando, indice) | Returns a real value for the root specified by the index. raiz(27, 3) returns 3. |
Matematica | arredondar(numero, casas), logaritmo(numero, base) | Return real values: rounding to the requested decimal places and a logarithm in the given base. |
Matematica | seno(angulo), cosseno(angulo), tangente(angulo) | Return real values for trigonometric functions; angles are in radians. |
Matematica | valor_absoluto(numero), maior_numero(a, b), menor_numero(a, b), PI | Return real values: absolute value, the greater or lesser of two numbers, and the π constant. |
Texto | numero_caracteres(cadeia), caixa_alta(cad), caixa_baixa(cad) | The first returns an integer; the others return a string in uppercase or lowercase. |
Texto | substituir(cad, pesquisa, substituto) | Returns a string with every occurrence of the searched text replaced. |
Texto | preencher_a_esquerda(car, tamanho, cad) | Returns a string padded on the left up to the requested length; strings that already have that length are unchanged. |
Texto | obter_caracter(cad, indice), posicao_texto(texto, cadeia, posicao_inicial) | The first returns a character; the second an integer position. Indices start at zero; the search returns -1 when the text is not found. |
Texto | extrair_subtexto(cadeia, posicao_inicial, posicao_final) | Returns a string from the starting index up to, but not including, the final index. Example: extrair_subtexto("salgado", 0, 3) returns "sal". |
Tipos | cadeia_e_inteiro(cad, base), cadeia_e_real(cad), cadeia_e_logico(cad), cadeia_e_caracter(cad) | Return logical values indicating whether a string represents the given type. Documented integer bases are 2, 10 and 16. |
Tipos | inteiro_e_caracter(valor), caracter_e_inteiro(car), caracter_e_logico(car) | Return logical values testing whether the values can be converted to the indicated types. |
Tipos | cadeia_para_inteiro(valor, base), cadeia_para_real(valor), cadeia_para_logico(valor), cadeia_para_caracter(valor) | Return an integer, real, logical or character, depending on the function. Logical conversion accepts verdadeiro or falso; conversion to a character requires exactly one character. |
Tipos | inteiro_para_cadeia(valor, base), inteiro_para_caracter(valor), inteiro_para_logico(valor), inteiro_para_real(valor) | Return a string, character, logical or real value; use base 2, 10 or 16 for strings. |
Tipos | caracter_para_cadeia(valor), caracter_para_inteiro(valor), caracter_para_logico(valor), logico_para_cadeia(valor), logico_para_inteiro(valor), logico_para_caracter(valor), real_para_cadeia(valor), real_para_inteiro(valor) | Return a string, integer, logical or character depending on the source type and function; check the library reference for each conversion. |
Util | obter_diretorio_usuario(), numero_elementos(vetor), numero_linhas(matriz), numero_colunas(matriz) | The first returns a string; the others return integer dimensions. A matrix must have at least one row to query its columns. |
Util | sorteia(minimo, maximo), aguarde(intervalo), tempo_decorrido() | sorteia returns an integer from the inclusive range when minimo is less than maximo; aguarde returns no value and pauses in milliseconds; tempo_decorrido returns an integer elapsed in milliseconds since the library was first used. |
inclua biblioteca Texto --> txt
funcao inicio() {
cadeia palavra = "logica"
escreva(txt.numero_caracteres(palavra), "\n")
escreva(txt.caixa_alta(palavra), "\n")
escreva(txt.extrair_subtexto(palavra, 0, 3), "\n")
}
Output: 6, LOGICA and log, each on its own line.
inclua biblioteca Tipos --> tipos
funcao inicio() {
escreva(tipos.cadeia_e_inteiro("101", 2), "\n")
escreva(tipos.cadeia_para_inteiro("101", 2), "\n")
}
Output: verdadeiro and 5. The first call validates the binary notation; the second converts the same value to an integer.
12 · Example
Complete program
This example combines a declaration, input and output, a condition, a function and a logical expression:
programa {
funcao logico eh_par(inteiro numero) {
retorne numero % 2 == 0
}
funcao inicio() {
inteiro valor
escreva("Enter an integer: ")
leia(valor)
se (eh_par(valor)) {
escreva("The number is even\n")
} senao {
escreva("The number is odd\n")
}
}
}
13 · Reading tips
Common mistakes and how to avoid them
- Mixing assignment and equality: use
=to assign and==to compare values. - Forgetting the separators in a
paraloop: initialization, condition and update fields are separated by semicolons. - Using an index outside a vector: indices start at zero; a vector of size 3 has positions
0through2. - Expecting a function from another library: include the module with
inclua biblioteca Nameand use its name or alias before the period. - Confusing length with the last index: a six-character string has last index
5; inextrair_subtexto, the final index is the boundary and is not included in the result. - Using
pareanywhere: it ends the current loop or selection case; outside those contexts, it does not replaceretorne.
14 · Further reading
Portugol Studio 2.0 pseudolanguage references
Portugol Studio 2.0 originates from Portugol Studio. That project appears in this section only as a source for the references used to document the pseudolanguage.
- The official Portugol Studio repository identifies the pseudolanguage as Portugol Studio 2.0.
- The official grammar and official lexer.
- The official input/output help, including the
\nnewline escape, and its semantic analyzer, which lists predefined functions. - Standard library source code and documented functions; see Matematica, Texto, Tipos and Util directly.
These references belong to separate projects. Check them for behavior and compatibility details before relying on a specific function.