4

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.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Stanimirovv
  • 3,064
  • 8
  • 32
  • 56

1 Answers1

9

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:

  1. First think of the base case when it is not necessary to recurse. This will save you from forgetting it (here, it's the case n <= 0)
  2. The general case: how can you get one step closer to the base case already written? Here it's by invoking the function with n-1.
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281