Hi, I was trying to create a function that contains a For loop. Here’s the function I defined
SquareSum[n_Integer]/;n>0:= For[i = 0; x = 0, i < n, i++, term = (x + (i + 1))^2; x = term]
of course the for loop I made is just as I wanted but there is no output upon calling this function. I tried adding Print[x] to the code will does display the result but that doesn’t count as output.
How do I get the value of x from the final stage of loop and display it as proper output upon calling this function.
Attached image will show what I meant with using the Print[x] function.
Hey Martijn, thanks for the bit. I am new to Wolfram language, without knowing many built-in functions For loop was my first intuition. Thanks for the processing time analysis. btw, I can’t use your suggestions in this problem because this was from a challenge problem and this would be called cheating. O well, my method doesn’t land that far from Fold.
Everything in Wolfram Language (Mathematica) is a function. Some functions return a value, some do not. The For[…] does not return a value, i.e. the outcome is Null.
Hence your function calculates everything correctly but does not return the result x. You have to put it explicitly at the end:
(For[i = 0; x = 0, i < n, i++, term = (x + (i + 1))^2; x = term]; x)
BTW: You do not need the intermediate variable term. You can write:
(For[i = 0; x = 0, i < n, i++, x = (x + (i + 1))^2]; x)
BTW: Your function creates global variables i, x and term, which is not desirable. You should write:
SquareSum[n_Integer]/;n>0:= Block[{i,x},
For[i = 0; x = 0, i < n, i++, x = (x + (i + 1))^2];
x];
or Module instead of Block.
BTW: You should not name your variables and functions with a first uppercase letter. This might conflict with WL-defined names. You’d better name your function “squareSum”.