# What is wrong with this procedural function to add numbers 1 through n? [closed]

I am trying to write a function to add numbers from 1 through h:

function[h_]:= x=0; For[i=1, i=<h, i++, x = x + i]; Print[x]


But I am getting some strange and inconsistent results. Can someone point out what is wrong here?

• put the right-hand side in parantheses: i.e., function[h_] := (x = 0; For[i = 1, i <= h, i++, x = x + i]; Print[x]). Btw, you don't need to use Print[x], you can use just x instead. – kglr Feb 8 '19 at 6:41
• Thanks alot. Why were the parenthesis necessary? – Jaigus Feb 8 '19 at 6:46
• without the parentheses, you are defining function as function[h_] := x = 0; and the remaining parts are executed as independent expressions: part For[i = 1, i <= h, i++, x = x + i] does not do anything to x (because h is not given a value) and Print[x] is executed separately and prints 0. – kglr Feb 8 '19 at 6:55
• Aahhhh ok. Thanks for making this clear. If you write this as an answer, I'd be happy to give you credit for it? – Jaigus Feb 8 '19 at 6:57

Put the expressions on right-hand-side in parentheses:

function[h_] := (x = 0; For[i = 1, i <= h, i++, x = x + i]; Print[x])

function[10]


55

Without the parentheses, you are defining function as function[h_] := x = 0; and the remaining expressions are not part of the definition of function.

As mentioned by m_goldberg, there are better ways to define such a function. In addition to the ones in m_goldberg's answer, you can also use

ClearAll[function]
function[h_]:= h (h + 1) / 2

function[10]


55

This is not an answer within the constraints of you question, but I think you should be made aware that there are much better ways.

A simple and functional way to write your function in the Wolfram Language would be

function[h_] := Total @ Range[h]


Then

function[10]


returns (and prints)

>55

This version of function is not only more concise than your procedural code, it is many times faster.

Of course, the built-in function Sum is even more concise.

Sum[x, {x, 10}]


55

But Sum works symbolically, so it be used to define an extremely efficient version of function.

Block[{x, h}, function[h_] = Sum[x, {x, h}]];


This gives the definition

Definition @ function


function[h_] = 1/2 h (1 + h)

which is about as good as you can get.

• Might be worth to mention PolygonalNumber` as built-in solution – Lukas Lang Feb 8 '19 at 11:14