4
I have a doubt in an algorithm that sums 10 numbers with the repetition command for
.
soma_numero := soma_numero + idade;
When I declare the soma_numero
as 0 before the for
the algorithm runs normally, but if I do not declare 0 it prints an unexpected value.
begin
soma_idade := 0;
for cont := 1 to 10 do
begin
writeln('Digite a idade ', cont);
readln(idade);
soma_idade := soma_idade + idade;
end;
writeln('A soma das idades e ', soma_idade);
readln;
end.
And where’s your code
for
?– Victor Stafusa
I’ve already added the code
– Kelven Rodrigues
I couldn’t simulate the problem. For me, your code always works normally even without initializing the
soma_idade
. See here the test: https://ideone.com/i9UR6O– Victor Stafusa
@Victorstafuses Delphi is very weak with memory management, without initializing the variable it can receive "junk" from memory. Waiting to be reopened for a response.
– Junior Moreira
I understood the problem, that was the "garbage" already stored in the variable, thank you.
– Kelven Rodrigues
By default the variable should already start with zero value but to avoid problems and facilitate the understanding of the code it is better to initialize it with the correct value before using. This can avoid a lot of headache later
– Rodrigo Sidney
@Junior, I was going to answer that question, but as I saw that you were waiting for it to be reopened I decided to warn you to answer.
– Roberto de Campos
@Robertodecampos all right friend, you can answer. But this is what I said, we have to control the memory management ourselves!
– Junior Moreira