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

C# Program to Count the Number of Digits in a Number

Filed under: C# on 2023-09-21 06:55:39

Here you will find an algorithm and program in C# programming language to count number of digits in a number. First let us understand this.

Explanation : Suppose an input number is given as 12341 then the output will be 5 as there are 5 digits in the given number and digits are 1, 2, 3, 4, 1.

Algorithm to count the number of digits in a given number
 

START
step 1 : Input a number from user. Store it in some variable say num.
step 2 : Initialize another variable to store total digits say digit = 0.
step 3 : If num > 0 then increment count by 1 i.e. count++.
step 4 : Divide num by 10 to remove last digit of the given number i.e. num = num / 10.
step 5 : Repeat step 3 to 4 till num > 0 or num != 0.
STOP


C# Program to Count Number of Digits in a Number
 

using System; 
class LFC { 
static int count_digit(long num) 

 int count = 0; 
 while (num != 0) { 
  num = num / 10; 
  ++count; 
 } 
 return count; 
}

public static void Main() 

 long num = 874512369; 
 Console.WriteLine("Number of"
 + " digits : " + count_digit(num)); 


Output
Number of digits : 9

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