Reference · G-Portugol

G-Portugol

This reference organizes the G-Portugol pseudolanguage rules from the official manual: algorithm structure, variables, matrices, expressions, control flow, functions, and input and output commands. Examples preserve the Portuguese reserved words.

Reference G-PortugolSyntax Portuguese reserved words

01 · Overview

About G-Portugol

G-Portugol organizes algorithms in Portuguese using explicit declarations, imperative statements, and delimited blocks. Its syntax brings together familiar forms from logic courses, such as algoritmo, variáveis, início, se, and para.

This page documents the pseudolanguage according to the manual maintained by the G-Portugol project. It keeps syntax rules separate from the GPT tool's commands and options, which have their own section. The official reference also lists adapting vocabulary to teaching practices as a design goal; GPT does not document a mechanism for configuring those forms, so this page records the standard syntax published by the project.

Scope: this reference describes syntax documented by the project. It does not mean that G-Portugol execution is already integrated into Potoo IDE.

02 · Organization

Program structure

A file begins with the algorithm declaration, may declare global variables, contains the main block, and ends with function declarations. The variable declaration block is optional; when used, it comes before início and contains at least one declaration. Official examples use the .gpt extension.

algoritmo exemplo;

variáveis
    nome : literal;
    idade : inteiro;
fim-variáveis

início
    nome := "Ana";
    idade := 16;
    imprima(nome, " tem ", idade, " anos.");
fim

função dobro(valor:inteiro) : inteiro
    retorne valor * 2;
fim

algoritmo requires an identifier and a semicolon; that name identifies the algorithm in the file but does not change execution. The main block starts with início and ends with fim; functions are declared after it. Simple statements end with a semicolon; blocks close with their own delimiter and no trailing semicolon. Indentation is optional, but it helps show the structure. The main block can also return early with retorne followed by an integer, which acts as the exit code.

03 · Writing

Identifiers, comments, and literals

The pseudolanguage is case-sensitive. Reserved words must keep their defined spelling and accents, including variáveis, início, então, faça, and função. Identifiers — names for variables, algorithms, and functions — start with an ASCII letter (A–Z or a–z) or underscore and may continue with ASCII letters, digits, and underscores.

// Single-line comment.
/* Multi-line
   comment. */

algoritmo dados;
variáveis
    nome_completo : literal;
    inicial : caractere;
    codigo : inteiro;
fim-variáveis
início
    nome_completo := "João";
    inicial := 'J';
    codigo := 0x2A;
fim

The standard reserved words are algoritmo, variáveis, fim-variáveis, início, fim, inteiro, real, caractere, literal, lógico, verdadeiro, falso, matriz, inteiros, reais, caracteres, literais, lógicos, se, então, senão, fim-se, enquanto, faça, fim-enquanto, repita, até, para, de, passo, fim-para, função, retorne, ou, e, and não.

Integers accept decimal, hexadecimal (0x/0X), octal (0c/0C), and binary (0b/0B) bases. Real numbers use a decimal point with digits on both sides. Characters use single quotes; '' represents the null character. Documented character escapes include \n, \r, and \\. Text uses double quotes, may contain escapes, and occupies one physical line of source code.

04 · Data

Types and variables

The official manual documents five primitive types. A declaration lists one or more names, a colon, the type, and a semicolon.

TypeExampleUse
inteiro42Whole numbers.
real3.5Numbers with a fractional part.
caractere'A'A single character.
literal"Olá"A sequence of characters.
lógicoverdadeiroA logical value, verdadeiro or falso.
variáveis
    quantidade, tentativas : inteiro;
    preco : real;
    disponivel : lógico;
fim-variáveis

Declared variables start with a zero or null value, depending on the type. The syntax does not declare constants. User-defined compound types such as records are not documented.

05 · Collections

Vectors and matrices

Homogeneous collections use the word matriz, followed by one bracketed dimension for each axis, de, and the plural name of a primitive type. Each dimension is a positive integer literal; a single dimension forms a vector.

variáveis
    notas : matriz[5] de reais;
    tabuleiro : matriz[3][3] de caracteres;
fim-variáveis

início
    notas[0] := 8.5;
    tabuleiro[1][2] := 'X';
    imprima(notas[0]);
fim

Indexes start at zero. Therefore, the vector valores declared with size 5 has positions 0 through 4; accessing valores[5] is out of bounds. Each element receives its type's default initial value. Matrices passed to functions are copied by value, according to the reference.

06 · Expressions

Assignment and operators

Assignment uses :=. The left side can be a primitive variable or an indexed matrix element; the right side is an expression compatible with the destination type. A whole matrix cannot be assigned or passed to imprima as one value.

OrderOperatorsOperation
1 · lowestou, ||Logical OR.
2e, &&Logical AND.
3|Bitwise OR.
4^Bitwise exclusive OR.
5&Bitwise AND.
6=, <>Equality and inequality.
7>, >=, <, <=Relational comparisons.
8+, -Addition and subtraction.
9*, /, %Multiplication, division, and remainder.
10 · highest+, -, ~, não, ()Unary signs, bitwise NOT, logical NOT, and grouping.
resultado := (a + b) * 2;
se ativo e tentativas < 3 então
    imprima("Pode continuar.");
fim-se

The table follows the documented order, from lowest to highest precedence. Parentheses make the intended order explicit.

07 · Interaction

Input and output

leia() takes no arguments: it reads a line from standard input through the line break and converts the contents to the primitive type expected by its context. It can appear alone on the right side of an assignment, in a condition, or in a matrix index; the reference does not allow combining it with other operands, as in total := base + leia();. imprima() accepts at least one primitive value, converts each value to text, concatenates them in order without separators, and appends a line break.

algoritmo saudacao;
variáveis
    nome : literal;
    idade : inteiro;
fim-variáveis
início
    imprima("Qual é o seu nome?");
    nome := leia();
    imprima("Qual é a sua idade?");
    idade := leia();
    imprima("Olá, ", nome, "! Você tem ", idade, " anos.");
fim

Text cannot be implicitly continued across separate physical lines. To print values of different types together, pass them as separate arguments to imprima.

08 · Decisions

Conditionals

se evaluates an expression and starts a block; senão is optional. Every conditional block ends with fim-se. Parentheses around the condition are optional. The manual documents this as the pseudolanguage's selection structure; it does not describe a separate multi-branch selection statement.

se nota >= 7 então
    imprima("Aprovado");
senão
    imprima("Precisa recuperar");
fim-se

Any expression can be evaluated as a condition: zero, empty text, and the null character are false; nonzero numbers and nonempty text are true. Logical values are also written as verdadeiro and falso.

09 · Repetition

Loops

G-Portugol documents three repetition structures: enquanto, repita, and para. Each structure closes its block with a dedicated reserved word.

enquanto quantidade > 0 faça
    quantidade := quantidade - 1;
fim-enquanto

repita
    quantidade := quantidade + 1;
até quantidade = 3;

para i de 1 até 5 faça
    imprima(i);
fim-para

enquanto checks the condition before each iteration; its body may not run. repita checks after the body and therefore runs at least once. The para bounds are inclusive, the default step is 1, and a negative step traverses the sequence in descending order.

para i de 10 até 0 passo -2 faça
    imprima(i);
fim-para

The reference does not document break or continue; loop control must be expressed through the condition and the variables involved.

10 · Reuse

Functions and return values

A function is declared after the main block. Parameters follow the form name:type; a return type is optional. Local declarations, when needed, appear before the início block.

função fatorial(valor:inteiro) : inteiro
    resultado : inteiro;
    contador : inteiro;
início
    resultado := 1;
    para contador de 1 até valor faça
        resultado := resultado * contador;
    fim-para
    retorne resultado;
fim

retorne returns an expression compatible with the declared type or, in a function without a return type, exits without a value. Functions may call themselves. Parameters and matrices are passed by value; nested functions and variable-length parameters are not supported. Return values are primitive.

11 · Combined example

Count and classify numbers

This program reads a limit and visits the integers from one through that value, reporting whether each is even or odd:

algoritmo contagem;
variáveis
    limite, numero : inteiro;
fim-variáveis

início
    imprima("Digite o limite:");
    limite := leia();

    para numero de 1 até limite faça
        se numero % 2 = 0 então
            imprima(numero, " é par.");
        senão
            imprima(numero, " é ímpar.");
        fim-se
    fim-para
fim

The example combines declarations, input, assignment, remainder, comparison, branching, and an inclusive loop.

12 · Important rules

Behavior and limits

  • Reserved words and identifiers are case-sensitive; accents are part of reserved words but are not accepted in identifiers.
  • Primitive types can form homogeneous vectors and matrices with one or more dimensions. Matrices are initialized element by element and passed to functions by value; they cannot be assigned or returned as a whole.
  • inteiro, real, lógico, and caractere are compatible in numeric operations; literal does not take part in arithmetic. There is no explicit type conversion. Compatible operands are promoted when no data is lost; assignment conversion can truncate a real assigned to an integer. For example, 5 / 2 is integer division, while 5.0 / 2 produces a real result.
  • Equality comparisons between real values can vary because of numeric representation, especially across interpreted, compiled, and translated execution.
  • Text literals are compared with case sensitivity. The official reference defines ordering comparisons between literals by their character counts.
  • Matrix indexes start at zero. GPT checks bounds in interpreted execution; the manual does not describe that check for other modes.
  • GPT provides two built-in input/output functions: leia() and imprima(...). The reference does not document a dedicated statement for including standard libraries.

13 · Reference tool

The GPT program

The official manual describes GPT as the project tool for analyzing and executing G-Portugol files. The options below belong to that program; they do not describe commands available in the Potoo IDE interface.

OptionDocumented purpose
-iInterprets and runs the algorithm.
-o fileCompiles and writes an executable.
-t fileGenerates C source code.
-s fileGenerates Assembly code.
-dAdds hints to the error report.
-hShows the program help.

The general form is gpt [options] files.... When several files are supplied, the first contains the algorithm declaration and main block; the remaining files provide supporting code and must not repeat the algorithm declaration, global variable block, or main block. The GPT_INCLUDE environment variable can also specify additional files; its paths are separated by : on Unix systems and ; on Windows. The manual expects equivalent results from interpretation, compilation, and translation, except that matrix bounds are checked in interpreted mode. Executable generation with -o is limited to 32-bit x86 machines; for other architectures, the manual describes generating C with -t and compiling it with the system toolchain.

14 · Further reading

References

15 · Comparison

Differences from Portugol Studio 2.0

G-Portugol and Portugol Studio 2.0 are distinct pseudolanguages. They share the goal of expressing algorithms in Portuguese, but their programs are not interchangeable: their structure, reserved words, types, operators, and execution rules differ.

AspectG-PortugolPortugol Studio 2.0
Structurealgoritmo name;, a main block início ... fim, then function declarations.programa { ... } with an entry function named funcao inicio().
SpellingReserved words include accents, such as variáveis, início, and função.Keywords omit accents, such as funcao, senao, and nao.
Declarations and typesname : inteiro; types include inteiro, real, caractere, literal, and lógico. const is not documented.inteiro name; it uses caracter, cadeia, logico, and vazio, and documents const.
Assignment and comparison:= assigns; = and <> compare.= assigns; == and != compare. Compound assignments and ++/-- are also documented.
Arrays and matricesmatriz[rows][columns] de inteiros; supports one or more dimensions and passes collections by value.inteiro table[rows][columns]; the reference documents vectors, two-dimensional matrices, initializers, and reference parameters with &.
Control flowUses fim-se, fim-enquanto, repita ... até, and para ... de ... até ... passo; no multi-branch selection or loop interruption command is documented.Uses brace-delimited blocks, escolha/caso, faca ... enquanto, a three-part para loop, and pare.
Functionsfunção dobro(valor:inteiro): inteiro; parameters are passed by value, only primitive return values are supported, and functions cannot be nested.funcao inteiro dobro(inteiro valor); & can pass a parameter by reference and vazio marks a function with no return value.
Input and outputleia() returns a value converted by context; imprima(...) concatenates values and appends a line break.leia(variable) stores input in a variable; escreva(...) does not append a line break automatically.
LibrariesDocuments leia and imprima as built-in functions; no dedicated library-inclusion statement is documented.Includes modules with inclua biblioteca and provides standard libraries such as Matematica, Texto, and Tipos.
ExpressionsAny expression can be used as a condition; zero and empty values are false. Operator precedence is listed explicitly.Conditions are documented with logical values; the grammar does not provide a complete precedence table, so parentheses make the intended order explicit.

The same exercise, in two syntaxes

This example checks whether a number is even. The algorithm is the same; delimiters, operators, and input/output follow each pseudolanguage's rules.

G-Portugol

algoritmo paridade;
variáveis
    numero : inteiro;
fim-variáveis
início
    imprima("Digite um inteiro:");
    numero := leia();
    se numero % 2 = 0 então
        imprima("Par");
    senão
        imprima("Ímpar");
    fim-se
fim

Portugol Studio 2.0

programa {
    funcao inicio() {
        inteiro numero
        escreva("Digite um inteiro: ")
        leia(numero)
        se (numero % 2 == 0) {
            escreva("Par\n")
        } senao {
            escreva("Ímpar\n")
        }
    }
}

For each pseudolanguage's full reference, see Portugol Studio 2.0 and the official G-Portugol rules.

Return to the Potoo IDE Manual

Explore the other references and project information.

Open the Manual