Dear Sir,
Please help me on Delphi. Could you tell me how can I do the following question?
Calculate and display the sum of the even numbers from 2 to 20 inclusive.
Cheers,
Dear Sir,
Please help me on Delphi. Could you tell me how can I do the following question?
Calculate and display the sum of the even numbers from 2 to 20 inclusive.
Cheers,
procedure TForm1.Button1Click(Sender: TObject);
Var
i1, iResult: Integer;
begin
iResult := 0;
for i1 := 2 to 20 do
begin
if ((i1 mod 2) = 0) then Inc(iResult, i1);
end;
ShowMessage(IntToStr(iResult));
end;
Hi Turbomen :D
If you want to create a console application then this is also a solution
Program EvenOrNot;
{$APPTYPE CONSOLE}
Uses
SysUtils;
Var i,counter:LongInt;
TheOdds:Boolean; {true or false}
Begin
i:=2;
counter:=0;
Write('The even numbers are: ');
While i<=21 Do Begin
TheOdds:=Odd(i);
If (TheOdds=False) Then Begin
Write(i,' ');
counter:=counter+i;{increase *counter* by *i*}
End;{of if}
Inc(i,1); {increase *i* by 1}
End;{of while}
WriteLn; {put the cursor to the home of the next line}
Write('Total : ',counter);
ReadLn; {press enter to quit}
End. {of main}
{
-=Notes=-
ODD FUNCTION:Tests if the argument is an odd number.
DECLARATION: ODD(X:LONGINT):BOOLEAN;
THE ODD FUNCTION RETURNS *TRUE* IF *X* IS AN ODD NUMBER
-=End Of Notes=-
Created By FlamingClaw 2009.07.12
}
Dear Sir,
Thank you for your kind help but could you mind telling me what is the meaning of the variable 'counter'?
Cheers,
Hi Turbomen :D
We store the sum of the even numbers in the variable named *Counter*.
When the program is running first *Counter* 's value is zero.
Counter:=0;
*TheOdds* variable is holds a *true* or *false* value changed by the built in function Odd(i) that wait longint and send back boolean,true if *i* is odd and false if *i* is even number
If *TheOdds* is false then *i* is an even number,so the *Counter*'s value will increase by *i*
Counter:=Counter+i;
Else *Counter* stays unchanged
Dear Sir,
Thank you for your kind expression. I really understand your meaning.
Cheers,
iResult:=0;
for i:2 to 20 do
if i/2 = round(i/2) then iResult=iResult+i;
eAnswer.text:=StrToInt(iResult)
replace line 8
if ((i1 mod 2) = 0) then Inc(iResult, i1);
with...
if not odd(i1) then Inc(iResult, i1);
which is easier to read.