how to get sum of the numbers in C# .net using Recursive Function

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string newNumber = string.Empty;
        newNumber = CalculateRecords(txtNumber.Text).ToString();
        lblMessage.Text = newNumber.ToString();

    }
   
Mormal Method
     
    private int CalculateRecords(string test)
    {
        try
        {
            int y = 0;
            string calculatedText = string.Empty;
        Label:
            if (calculatedText != null && calculatedText != string.Empty)
            {
                test = calculatedText;
                y = 0;
            }
            string[] x = new string[test.Length];
            for (int i = 0; i < test.Length; i++)
            {
                x[i] = test.Substring(i, 1);
                y += int.Parse((x[i]));

            }
            string j = y.ToString();
            string[] z = new string[j.Length];
            if (z.Length > 1)
            {
                calculatedText = j;
                goto Label;
            }
            return y;
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

Input:"123456789"
Output:9


Recursive Function Method

Recursive Function is a Function that call itself.

private int CalculateRecords(string test)
    {
        try
        {
            int y = 0;
            if (test.Length > 1)
            {
                string[] x = new string[test.Length];
                for (int i = 0; i < test.Length; i++)
                {
                    x[i] = test.Substring(i, 1);
                    y += int.Parse((x[i]));
                }
                test = Convert.ToString(CalculateRecords(y.ToString()));
            }
            return Convert.ToInt32(test);
        }
        catch (Exception ex)
        {

            throw ex;
        }

    }

No comments: