Function Calculator, Params And Return Value Of Main - C# Programming Exercise

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.

 Category

Functions

 Exercise

Function Calculator, Params And Return Value Of Main

 Objective

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

 Write Your C# Exercise

// 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
    }
}

 Share this C# exercise

 More C# Programming Exercises of Functions

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Function MinMaxArray

    In this exercise of C#, you will create a function named MinMaxArray that receives an array of numbers and returns the minimum and maximum values using ...

  •  Function Reverse, recursive

    In this exercise of C#, you need to create a program that uses recursion to reverse a string of characters. The program should receive a string as input...

  •  Function WriteRectangle

    In this exercise of C#, you need to create two functions: one called WriteRectangle to display a filled rectangle on the screen using asterisks, and another ca...

  •  Function Palindrome, iterative

    In this exercise in C#, you need to create an iterative function that checks if a string is symmetric (a palindrome). A palindrome is a word, number, phrase, or other...

  •  Function Palindrome, recursive

    In this exercise in C#, you will need to create a recursive function to check if a string is symmetric (a palindrome). A palindrome is a word, number, phrase, ...

  •  Function GetMinMax

    In this exercise in C#, you will need to write a function named "GetMinMax", which will ask the user to enter a minimum value (a number) and a maximum value (a...