Array with strings in Visualg
I am having difficulty with the following Question:
Create an array M [21,10]. Read 10 names (with a maximum of 20 characters) and store in the first row of the array. After reading, decompose the names letter by letter and store them in the remaining rows of the array from the second. At the end, write The Matrix.
My code looked like this:
algoritmo "Exercício 4"
var
m : vetor[1..21, 1..10] de caractere
nome : caractere
i, j : inteiro
inicio
i := 1
para j de 1 ate 10 faca
repita
escreva("Informe o nome: ")
leia(m[i, j])
se compr(m[i, j]) > 20 entao
escreval("Informe um nome com no máx. 20 caracteres.")
fimse
ate compr(m[i, j]) <= 20
fimrepita
fimpara
para i de 2 ate 21 faca
para j de 1 ate compr(m[1, j]) faca
escreval(copia(m[1, j], j, 1))
fimpara
fimpara
fimalgoritmo
I am not able to distribute the letters in the array, and my code error says it's missing a do on the 5th line from bottom to top, but do is there.
2 answers
Has several errors in its algorithm. I redone it all according to the statement of the exercise.
Try to use descriptive names for your variables. The second loop was backwards and I think the confusion was precisely because of the variable names. Even if you are used to mathematics and have fixed in mind that i
and j
are respectively referring to rows and columns it is better to use more descriptive names.
In the first loop is possible to fix ( hardcoded ) the array row index as 1, after all, the names will only be put on the first line, as the utterance says.
Instead of putting the name typed in the array, even if invalid, I created a variable called nome
to validate before if the name was within the rules, if yes, it goes to the array, otherwise the repita
will continue to execute.
Until then you were doing well, but I can not understand what the goal was from the final code block.
What I did was go through all the columns in the array and for each column go through all the available rows (2 - 21) making the column get 1 character from string
which is in the first row of this column.
algoritmo "Exercício 4"
var
matriz: vetor[1..21, 1..10] de caractere
nome: caractere
linha, coluna, i : inteiro
inicio
para coluna de 1 ate 10 faca
repita
escreva("Informe o nome: ")
leia(nome)
se compr(nome) > 20 entao
escreval("Informe um nome com no máx. 20 caracteres.")
fimse
ate compr(nome) <= 20
matriz[1, coluna] := nome
fimpara
para coluna de 1 ate 10 faca
i := 1
para linha de 2 ate 21 faca
matriz[linha, coluna] := copia(matriz[1, coluna], i, 1)
i := i + 1
fimpara
fimpara
fimalgoritmo