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.
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.