How to write this C ++ code in apple dylan

I am new to programming. I need help with this task. I need to convert this simple C ++ source code to Apple Dilan 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 someone help me write this code in apple dylan?

Regards Paul

+4
source share
1 answer

Here's a recursive solution:

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

(Obviously, this could benefit from some verification for n <1.)

To run the method, you must run the command:

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

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

You can create the main method as follows:

 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; 
+3
source

Source: https://habr.com/ru/post/1392747/


All Articles