You are here: Home / Topics / C# Program to Find the Sum of Digits in a Given Number

C# Program to Find the Sum of Digits in a Given Number

Filed under: C# on 2023-09-21 06:56:45

Here you will find an algorithm and program in C# programming language to find the sum of digits in number. Now let us understand this.

Explanation : Suppose we are having number 12548 and we have to calculate the sum of digits in the given number, so here we have the following digits 1, 2, 5, 4, 8 and we will sum all these digits -> 1 + 2 + 5 + 4 + 8 and the result we get is 20 that will be our output.

Sum Of Digits Algorithm
 

START
Step 1: Get number by user
Step 2: Get the modulus/remainder of the number
Step 3: sum the remainder of the number
Step 4: Divide the number by 10
Step 5: Repeat the step 2 while number is greater than 0.
STOP


C# Program to Find the Sum Of Digits in Number
 

using System; 
class LFC { 
static int sum_digit(int num) 

int sum = 0,rem; 
while (num != 0) { 
 rem=num%10;
 num = num / 10; 
 sum=sum+rem; 
 } 
return sum; 
}

public static void Main() 

 int num = 123456; 
 Console.WriteLine("Sum Of"
 + " Digits : " + sum_digit(num)); 


 

Output
Sum Of Digits : 21

About Author:
G
Geetam     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.