How to Find the Sum of odd numbers from 0 to 100 in F# ?

Recently , I started learning F# as hobby and started writing some simple programs . Today , I was trying out a sample program in F# which finds out the sum of odd numbers from 0 to 100 in F#.

How to Find the Sum of odd numbers from 0 to 100 in F# ?

Below is a sample code snippet that does the work.

// Ginktage - F# Program to find the sum of odd numbers from 0 to 100
open System
[<EntryPoint>]
let main argv = 
    let mutable sum = 0
    for indexer=0 to 100 do
        if indexer%2 <> 0 then 
            sum <- sum + indexer
    printfn "Sum is %A" sum
     // Printing the entered input
    let retval = Console.ReadLine()
    0 // return an integer exit code

image

    1 Comment

  1. Anthony
    August 3, 2014
    Reply

    This solution works, but it’s more like C# than F#, a more idiomatic solution would be to have something like:

    [0..100]
    |> List.filter (fun i -> (i % 2) 0)
    |> List.sum
    |> printfn "%i"

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you’ll learn about the error message “FileOpenAccessDenied – You do not have permissions to open this file...
  • .NET
  • December 3, 2024
You might have had a situation where your code once worked fine in ASP.NET application but now throws the below...
  • .NET
  • December 3, 2024
C# uses the flower bracket “{” and “}” to identify the block or scope of the function or program ....
  • .NET
  • December 3, 2024