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
IF (i<=N) THEN
varsum +=i;
//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.


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.


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.

Please advise.


First: go from pseudo-code to real code and try again. Run the debugger and step through your code one step at a time and observe what is going on.