Problem with the sum of 10 numbers with for

Asked

Viewed 216 times

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?

  • I’ve already added the code

  • 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

  • 3

    @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.

  • I understood the problem, that was the "garbage" already stored in the variable, thank you.

  • 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

  • @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.

  • @Robertodecampos all right friend, you can answer. But this is what I said, we have to control the memory management ourselves!

Show 3 more comments

1 answer

2


answer given in the comments and accepted as correct:

Delphi is very weak with memory management, without initializing the variable it can receive "junk" from memory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.