0
0
C Sharp (C#)programming~20 mins

Params keyword for variable arguments in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Params Keyword for Variable Arguments
📖 Scenario: Imagine you are creating a simple calculator that can add any number of integers given by the user. Instead of writing many methods for different numbers of inputs, you want one method that can take any amount of numbers.
🎯 Goal: Build a C# program that uses the params keyword to create a method which adds any number of integers and returns the total sum.
📋 What You'll Learn
Create a method called AddNumbers that uses the params keyword to accept multiple integers.
Call the AddNumbers method with different numbers of arguments.
Print the sum returned by the AddNumbers method.
💡 Why This Matters
🌍 Real World
Using the <code>params</code> keyword helps create flexible methods that can handle different amounts of input without writing many overloads.
💼 Career
Many programming jobs require writing clean, reusable code. Knowing how to use <code>params</code> helps you write methods that are easy to use and maintain.
Progress0 / 4 steps
1
Create the AddNumbers method with params
Write a method called AddNumbers that takes a params int[] numbers parameter and returns an int. Inside the method, create a variable sum initialized to 0.
C Sharp (C#)
Need a hint?

Use params int[] numbers in the method parameter to accept any number of integers.

2
Add numbers inside the AddNumbers method
Inside the AddNumbers method, use a foreach loop with variable num to iterate over numbers and add each num to sum. Then return sum.
C Sharp (C#)
Need a hint?

Use foreach (int num in numbers) to loop through all numbers.

3
Call AddNumbers with different argument counts
In the Main method, call AddNumbers with these arguments: 1, 2, 3 and store the result in result1. Then call AddNumbers with 4, 5, 6, 7, 8 and store the result in result2.
C Sharp (C#)
Need a hint?

Call AddNumbers with the exact numbers and store results in result1 and result2.

4
Print the results
In the Main method, print result1 and result2 each on a new line using Console.WriteLine.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(result1); and Console.WriteLine(result2); to print the sums.