# Code to calculate the sum of any integer value(N) inputPosted: Sun Sep 04, 2011 2:46 pm

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.

Thanks
Liizz

I’m guessing this is sort of a learning exercise for NAV programming that you are attempting.

Think about each line of code. What is the purpose of the IF statement you have entered? In your loop, would you ever have a time where “i” is greater than “n”? No. So the IF statement doesn’t do anything.

The rest of the code is fine, though. I’m assuming you have defined “n” as an input parameter to your function.

Try also using the debugger and stepping through the code line by line. Figure out in your head what the value of every variable should be before each line executes, and then compare that to the actual values.

Try to write the code using this formula.

sum=n*(n+1)/2;

if n=4 then sum= 10.

Thanks for ur replies.

Yes N is the input value.

Am thinking of it in terms of a pseudocode.

But in the for loop is it incrementing it by 1.

Am not having the sum for the value am testing when my for loop finish to N.

I have done this exercise in C++, this logic works but in Navision. am not getting it.