Topic: Function
Write a function-‐oriented program that calculates the sum of the sequence number from 1 to n. Thus, if the input is 5, the output should be 15
because:
1 + 2 + 3 + 4 + 5 = 15
Note: you can choose any looping statement if needed.
using System;
public class HelloWorld
{
static void Sum(int n)
{
int count = n * (n + 1) / 2;
Console.WriteLine($"Sum from 1 to {n} = {count}");
}
public static void Main(string[] args)
{
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
Sum(n);
}
}
Comments
Leave a comment