Exercise
Function Parameters Of Main, Sum
Objective
Write a C# program named "sum", which receives two integer numbers in the command line and displays their sum, as in this example:
sum 5 3
8
Example C# Exercise
Show C# Code
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Main method where the program starts
public static void Main(string[] args)
{
// Checking if the user has provided two arguments
if (args.Length == 2)
{
try
{
// Parsing the arguments to integers safely
int num1 = int.Parse(args[0]); // The first number provided in the command line
int num2 = int.Parse(args[1]); // The second number provided in the command line
// Calculating and displaying the sum of the two numbers
Console.WriteLine(num1 + num2); // The sum of num1 and num2 is printed
}
catch (FormatException)
{
// If the user inputs non-numeric values, catch the exception and display an error message
Console.WriteLine("Error: Please enter valid integers.");
}
}
else
{
// If the user does not provide exactly two arguments, display an error message
Console.WriteLine("Please provide exactly two numbers.");
}
}
}
Output
-- Case 1: Execution with two valid numbers
dotnet run 5 7
12
-- Case 2: Non-numeric input (errors when trying to convert arguments to integers)
dotnet run 5 a
Error: Please enter valid integers.
-- Case 3: Fewer than two arguments
dotnet run 5
Please provide exactly two numbers.
-- Case 4: More than two arguments
dotnet run 5 7 10
Please provide exactly two numbers.