Code to calculate the sum of any integer value(N) input

liizzliizz Member Posts: 125
Hi all,

I want to write a codeunit that will calculate the sum of any integer value(N).

Lets say N=4, then sum =10(1+2+3+4)

My codes are as follows for the codeunit:

//BEGIN Code
FOR i:=1 TO N DO BEGIN
IF (i<=N) THEN
varsum +=i;
END;
MESSAGE(FORMAT(i));
MESSAGE(FORMAT(varsum));
//END code

The sum is not working when I put till N values. :(

This codeunit will be attached to a form whereby a value will be inserted by user, and generates the sum of that integer value. I cannot restrict users from the values they will input. It should cater for N values.

Please help.

Thanks
Liizz

Comments

  • MBergerMBerger Member Posts: 413
    first : you don't tell us EXACTLY what is wrong. Second, why to IF statement in the loop ? The loop itself make sure I <= N !

    thirdly :there is an easier way to do that sum, without a loop : Sum = (( 1 + N ) / 2) * N
Sign In or Register to comment.