C# Exercise: 126 Function calculator, params and return value of Main

In this exercise of C#, you will create a program that calculates mathematical operations like addition, subtraction, multiplication, or division, by analyzing the command line parameters. The program should accept three parameters: a number, an operation sign, and another number, like this example: calc 5 + 379. The allowed signs are +, -, *, x, and /. Furthermore, the program should return error codes in the following cases: 1 if the number of parameters is not 3, 2 if the second parameter is not a valid sign, 3 if the first or third parameter is not a valid number, and 0 if everything is correct. This exercise is useful for learning how to validate command-line inputs, handle errors, and perform dynamic mathematical operations in C#. It’s an excellent way to practice error handling and parameter validation in console applications, ensuring that mathematical operations only occur when the parameters are correct.

This exercise will help you improve your skills in input processing, validation, and error handling in C#, as well as understanding how to build robust programs that interact correctly with the user via the command line.



 Lesson

Functions

 Exercise

Function calculator, params and return value of Main

 Objetive

Write a C# program to calculate a sum, subtraction, product or division, analyzing the command line parameters:

calc 5 + 379

(Parameters must be a number, a sign, and another number; allowed signs are + - * x / )

This version must return the following error codes:
1 if the number of parameters is not 3
2 if the second parameter is not an accepted sign
3 if the first or third parameter is not a valid number
0 otherwise

 Example Code

// Import the System namespace to use basic classes like Console
using System;

class Program
{
    // Main method to drive the program
    public static int Main(string[] args)
    {
        // Check if the correct number of arguments (3) are passed
        if (args.Length != 3)
        {
            // Return error code 1 if the number of parameters is incorrect
            Console.WriteLine("Error: Please provide two numbers and an operator.");
            return 1;
        }

        // Try to parse the first number from the command line arguments
        double num1;
        if (!double.TryParse(args[0], out num1))
        {
            // Return error code 3 if the first parameter is not a valid number
            Console.WriteLine("Error: The first parameter is not a valid number.");
            return 3;
        }

        // Try to parse the second number from the command line arguments
        double num2;
        if (!double.TryParse(args[2], out num2))
        {
            // Return error code 3 if the third parameter is not a valid number
            Console.WriteLine("Error: The third parameter is not a valid number.");
            return 3;
        }

        // Get the operator from the second parameter
        string operatorSign = args[1];

        // Perform the calculation based on the operator
        double result = 0;
        bool validOperation = true;

        // Switch statement to handle different operations
        switch (operatorSign)
        {
            case "+":
                result = num1 + num2; // Perform addition
                break;
            case "-":
                result = num1 - num2; // Perform subtraction
                break;
            case "*":
            case "x": // Allow 'x' as multiplication sign
                result = num1 * num2; // Perform multiplication
                break;
            case "/":
                if (num2 == 0)
                {
                    // Handle division by zero
                    Console.WriteLine("Error: Cannot divide by zero.");
                    validOperation = false;
                }
                else
                {
                    result = num1 / num2; // Perform division
                }
                break;
            default:
                // Return error code 2 if the operator is invalid
                Console.WriteLine("Error: Invalid operator. Use +, -, *, x, or /.");
                validOperation = false;
                break;
        }

        // Output the result if the operation is valid
        if (validOperation)
        {
            Console.WriteLine($"Result: {result}");
            return 0; // Return 0 to indicate successful operation
        }

        // Return an error code if the operation was not valid
        return 2; // Return error code 2 if the operator is invalid
    }
}


More C# Exercises of Functions

 Functions: greeting + farewell
Write a C# program whose Main must be like this: public static void Main() { SayHello(); SayGoodbye(); } SayHello and SayGoodbye are functio...
 Function with parameters
Write a C# program whose Main must be like this: public static void Main() { SayHello("John"); SayGoodbye(); } SayHello and SayGoodbye are f...
 Function returning a value
Write a C# program whose Main must be like this: public static void Main() { int x= 3; int y = 5; Console.WriteLine( Sum(x,y) ); } "Sum" is...
 Function returning a value V2
Write a C# program whose Main must be like this: public static void Main() { __Console.WriteLine("\"Hello, how are you\" contains {0} spaces", __...
 Function write centered
Write a C# function to write centered on screen the text that is indicated as a parameter (supposing a screen width of 80 characters): WriteCentere...
 Function write underlined
Write a C# function able to write centered on screen the text that is indicated as a parameter (supposing a screen width of 80 characters) and then un...
 Function sum of array
Write a C# program to calculate the sum of the elements in an array. "Main" should be like this: public static void Main() { int[] example = {20, ...
 Function double
Write a C# function named "Double" to calculate and return an integer number doubled. For example. Double(7) should return 14....
 Function Double reference parameter
Write a C# function named "Double" to calculate the double of an integer number, and modify the data passed as an argument. It must be a "void" functi...
 Function swap reference parameters
Write a C# function named "Swap" to swap the values of two integer numbers, which are passed by reference. An example of use might be: int x=5, ...
 Function power local variables
Write a C# function named "Power" to calculate the result of raising an integer number to another (positive integer) number. It must return another in...
 Function recursive power
Write a C# function that calculates the result of raising an integer to another integer (eg 5 raised to 3 = 53 = 5 × 5 × 5 = 125). This function must ...
 Function Fibonacci
Write a C# program that uses recursion to calculate a number in the Fibonacci series (in which the first two items are 1, and for the other elements, ...
 Function modify a letter in a string
Write a C# function named "ChangeChar" to modify a letter in a certain position (0 based) of a string, replacing it with a different letter: string...
 Function IsPrimeTarea
Write a C# function named "IsPrime", which receives an integer number and retuns true if it is prime, or false if it is not: if (isPrime(127)) ......
 Function Parameters of Main, Sum
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...
 Function SumDigits
Write a C# function SumDigits that receives a number and returns any results in the sum of its digits. For example, if the number is 123, the sum woul...
 Function Factorial
The factorial of a number is expressed as follows: n! = n · (n-1) · (n-2) · (n-3) · ... · 3 · 2 · 1 For example, 6! = 6·5·4·3·2·1 Create a r...
 Function Parameters of Main, Reverse
Write a C# program named "reverse", which receives several words in the command line and displays them in reverse order, as in this example: revers...
 Function GetInt
Write a C# function named "GetInt", which displays on screen the text received as a parameter, asks the user for an integer number, repeats if the num...
 Function tasks database
Write in C# an improved version of the "tasks database", splitting it into functions....
 Function Greatest value in a array
Write a C# function which returns the greatest value stored in an array of real numbers which is specified as parameter: float[] data={1.5f, 0.7f, ...
 Function factorial (iterative)
Write an C# iterative (non-recursive) function to calculate the factorial of the number specified as parameter: Console.Write ( Factorial (6) ); ...
 Function WriteTitle
Write a C# function named "WriteTitle" to write a text centered on screen, uppercase, with extra spaces and with a line over it and another line under...
 Function return value for Main
Write a C# program in which you write a title (using the previous WriteTitle function) which the user will specify in command line. If no text is spec...
 Function CountDV
Write a C# function that calculates the amount of numeric digits and vowels that a text string contains. It will accept three parameters: the string t...
 Function IsAlphabetic
Write a C# function that tells if a character is alphabetic (A through Z) or not. It should be used like this: if (IsAlphabetic ("a")) System.Cons...
 Function IsNumber
Write a C# function that tells if a string is an intenger number. It should be used like this: if (IsNumber ("1234")) System.Console.WriteLine ("I...
 Function calculator, params of Main
Write a C# program to calculate a sum, subtraction, product or division, analyzing the command line parameters: calc 5 + 379 (Parameters must be...
 Function MinMaxArray
Write a C# function named MinMaxArray, to return the minimum and maximum values stored in an array, using reference parameters: float[] data={1.5f,...
 Function Reverse, recursive
Write a C# program that uses recursion to reverse a string of characters (for example, from "Hello" it would return "olleH")....
 Function WriteRectangle
Write a C# function WriteRectangle to display a (filled) rectangle on the screen, with the width and height indicated as parameters, using asterisks. ...
 Function Palindrome, iterative
Write an C# iterative function to say whether a string is symmetric (a palindrome). For example, "RADAR" is a palindrome....
 Function Palindrome, recursive
Write a C# recursive function to say whether a string is symmetric (a palindrome). For example, "RADAR" is a palindrome....
 Function GetMinMax
Write a C# function named "GetMinMax", which will ask the user for a minimum value (a number) and a maximum value (another number). It should be calle...
 Function Multiply & MultiplyR
Write two C# functions, Multiply and MultiplyR, to calculate the product of two numbers using sums. T he first version must be iterative, and the seco...