I want to learn a bit of OCaml, just to get a taste of a programming language other than C++ and Java. I will be very greatful if you help me with the following program: basically the user inputs a positive integer. The sum of all integers from N to 0 is printed.
Obviously you create an integer N
, let the user enter its value. Create a variable sum
of type int
. Have a for
loop which will add N
to sum
and then decrement N
's value by one. The loop will run while N
is greater than 1. I have no idea how to do this in OCaml's syntax though.
Any help would be highly appreciated.
The way you describe your algorithm is how you would typically implement it in C++ or in Java. You can write it the same way in OCaml, but the idiomatic way would be a recursive function that does not mutate variables, as follows:
let rec print_sum acc n =
if n <= 0
then Printf.printf "Sum: %d\n" acc
else print_sum (acc + n) (n - 1)
Invoke with: print_sum 0 11 ;;
To write a recursive function:
n <= 0
)n-1
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With