
Patrick B. answered 07/12/19
Math and computer tutor/teacher
You can use the math shortcut: N * (N+1)/2, as proved by induction.
As an example, for N=5:: 1+2+3+4+5 = 15 vs 5*(5+1)/2 = 5*6/2 = 30/2 = 15
I have a feeling your instructor wants to see the for loop. So I included the
shortcut as a CHECK. Here's the listing:
--------------------------------------------------------------------------------------------------------------------
Program SumFirstNIntegers (input,output);
{*********************************************************}
Function SumFirstNInteger ( N : integer) : longint;
var iLoop : integer;
SumReturn : longint;
Begin
SumReturn:=0;
For iLoop:= 1 to N do
SumReturn := SumReturn + iLoop;
if (sumReturn= ( N * (N+1)/2)) then
SumFirstNInteger:=SumReturn
else begin
SumFirstNInteger:=-1;
writeln(' Calcualtion Fails ');
end;
end;
{**********************************************************}
VAR
N : integer;
BEGIN
{* uncomment this for input *}
repeat
write(' Please input N :>');
readln(N);
until (N>0);
{* comment this out if using input *}
{N:=5;}
writeln(SumFirstNInteger(N));
END.