Recap - Sigma Function
Part of the Fundamentals section of Coddy's Swift journey — lesson 55 of 86.
Challenge
EasyCreate a function called sigma that calculates the sum of all integers from 1 to a given number.
Parameters:
n(Int): The upper limit of the sum (use_to omit the argument label)
Returns: The sum of all integers from 1 to n (Int)
After defining the function, read an integer from input, call the sigma function with that value, and print the result.
You will receive the following input:
- A single integer representing the value of
n
For example, if the input is 5, the function calculates 1 + 2 + 3 + 4 + 5 = 15, so the output should be:
15Try it yourself
// TODO: Define the sigma function that calculates the sum of integers from 1 to n
// Use _ to omit the argument label
// Read input
let n = Int(readLine()!)!
// Call the function and print the result
print(sigma(n))All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input