Write a C# program to create a function to calculate the sum of the individual digits of a given number

Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability..

using System;
 
public class functionexcercise
{
    public static int SumCal(int number)
    {
        string n1 = Convert.ToString(number);
        int sum = 0;
        for (int i = 0; i < n1.Length; i++)
            sum += Convert.ToInt32(n1.Substring(i, 1));
        return sum;
    }
 
    public static void Main()
    {
        int num;        
        Console.Write("Enter a number: ");
        num = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("The sum of the digits of the number {0} is : {1} \n", num, SumCal(num));
        Console.ReadLine();
    }
}

Result

Write a C# program to create a function to calculate the sum of the individual digits of a given number
Write a C# program to create a function to calculate the sum of the individual digits of a given number

Leave a Comment