params
Keyword
The params
keyword allows a method to accept a variable number of arguments as a single parameter, which is treated as an array inside the method.
params
parameter is allowed per method.params
to Sum Numbers
class Program
{
// Method accepts variable number of integers
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int num in numbers)
{
total += num;
}
return total;
}
static void Main()
{
Console.WriteLine(Sum(1, 2, 3)); // Output: 6
Console.WriteLine(Sum(10, 20, 30, 40)); // Output: 100
int[] arr = {5, 15, 25};
Console.WriteLine(Sum(arr)); // Output: 45
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!