4

I'm new to computer programming. I need help with this task. I need to convert this simple C++ source code into apple dylan code. This is the original mathematical statement:

Task: Input an integer number n and output the sum: 1+22+32+...+n2. Use input validation for n to be positive.

I wrote this code in C++:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    if (n < 0) return 1;
    int sum = 0;
    int i = 0;
    while (i <= n) sum += i*i;
    cout << sum;
    return 0;
}

Can anyone help me to write this code into apple dylan?

Best wishes, Paul

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202

1 Answers1

3

Here's a recursive solution:

define method sumSquaresFromOne(n :: <integer>)
  if (n = 1)
    1
  else
    n *n + sumSquaresFromOne(n - 1)
  end
end method;

(Obviously, it could benefit from some checking for n < 1.)

To run the method you would issue the command:

format-out("%d", sumSquaresFromOne(5))

The output of which would be "55" (1 + 4 + 9 + 16 + 25).

You could create a main method like this:

define method main(appname, #rest arguments)
  format-out("Input an integer number n:")
  let n = read-line(*standard-input*)
  format-out("Sum of squares from t to %d is %d\n", n, sumSquaresFromOne(n))
  exit(exit-code: 0);
end method;
Ben Hocking
  • 7,790
  • 5
  • 37
  • 52