{"record":{"id":"fd22bf84e568d154","repo":"TheAlgorithms/C-Sharp","slug":"input-must-be-a-non-negative-integer","errorCode":null,"errorMessage":"Input must be a non-negative integer.","messagePattern":"Input must be a non-negative integer\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Numeric/SumOfDigits.cs","lineNumber":22,"sourceCode":"\n/// <summary>\n///     Provides functionality to calculate the sum of the digits of an integer.\n/// </summary>\npublic static class SumOfDigits\n{\n    /// <summary>\n    ///     Calculates the sum of the digits of a non-negative integer.\n    ///     The method iteratively uses the modulus operator (%) to get the last digit\n    ///     and the division operator (/) to drop the last digit until the number is 0.\n    /// </summary>\n    /// <param name=\"number\">The non-negative integer whose digits are to be summed.</param>\n    /// <returns>The sum of the digits of the input number.</returns>\n    /// <exception cref=\"ArgumentException\">Thrown if the input number is negative.</exception>\n    public static int Calculate(int number)\n    {\n        if (number < 0)\n        {\n            throw new ArgumentException(\"Input must be a non-negative integer.\", nameof(number));\n        }\n\n        if (number == 0)\n        {\n            return 0;\n        }\n\n        int sum = 0;\n        int currentNumber = number;\n\n        // Loop until the number becomes 0\n        while (currentNumber > 0)\n        {\n            // Get the last digit (e.g., 123 % 10 = 3)\n            int digit = currentNumber % 10;\n\n            // Add the digit to the sum\n            sum += digit;","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Numeric/SumOfDigits.cs#L4-L40","documentation":"SumOfDigits.Calculate computes digit sums only for non-negative integers; digit extraction from a negative number would never terminate or would be ill-defined for this implementation, so it throws ArgumentException with the parameter name when number < 0.","triggerScenarios":"Calling Calculate(-5) or Calculate on a value that became negative through subtraction, overflow, or unvalidated user input.","commonSituations":"Processing signed user input such as temperatures or account deltas; int.MinValue arithmetic that wrapped negative; passing unchecked form/console input.","solutions":["Validate the number is >= 0 before calling, or use Math.Abs when sign is irrelevant","Fix upstream logic that lets values go negative when they should not","Catch ArgumentException and map it to a user-facing 'value must be non-negative' message"],"exampleFix":"// before\nvar sum = SumOfDigits.Calculate(userValue); // may be negative\n// after\nif (userValue < 0) throw new FormatException(\"digits expected\");\nvar sum = SumOfDigits.Calculate(userValue);","handlingStrategy":"validation","validationCode":"if (number < 0) throw new ArgumentOutOfRangeException(nameof(number));","typeGuard":"static bool IsNonNegative(int n) => n >= 0;","tryCatchPattern":"try { return SumOfDigits.Calculate(number); }\ncatch (ArgumentException ex) when (ex.ParamName == \"number\") { /* handle negative input */ }","preventionTips":["Validate user input sign before numeric processing","Apply Math.Abs only when sign is genuinely irrelevant","Watch for integer overflow that can wrap values negative"],"tags":["argument-validation","negative-number","numeric"],"backgroundTag":"invalid-argument-value","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}