Simple program #13 (Source code to calculate
number of digits)
Enter a number: 456
Number of digits used in given number
456 is 3
The program is written in C#
programming language and will accept a number as input. The logic of the
program is to counter number of digits.
Let’s find out a simple and easy way
to code the program.
Practical Implementation:
using System;
namespace patternProblem.Simple_program
{
class Simple13 //Calculating number of digits
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());
int count = 0;
Console.WriteLine();
//Method 1:
Using string in-built function length
Console.WriteLine("Output from Method1: Using
string in-built function length");
Console.WriteLine("Number of digits used in
given number {0} is {1}", n, n.ToString().Length);
Console.WriteLine();
//Method 2:
Using for loop
int temp = n;
for (; n > 0; )
{
n = n / 10;
count++;
}
Console.WriteLine("Output from Method2: Using
for loop");
Console.WriteLine("Number of digits used in
given number {0} is {1}", temp, count.ToString());
Console.WriteLine();
//Method 3:
Using while loop
count = 0;
n = temp;
while (n > 0)
{
n = n / 10;
count++;
}
Console.WriteLine("Output from Method3: Using
while loop");
Console.WriteLine("Number of digits used in
given number {0} is {1}", temp, count.ToString());
Console.ReadKey();
}
}
}
Output:
The input
number is 4256. The program will count number of digits used in input number.
The output is shown below:
Enter a number: 4256
Output from Method1: Using string in-built function
length
Number of digits used in given number 4256 is 4
Output from Method2: Using for loop
Number of digits used in given number 4256 is 4
Output from Method3: Using while loop
Number of digits used in given number 4256 is 4
Press any key to continue . . .
For any
query, comment us below.
Skip to
Main Table Simple program
Keep learning and sharing...
No comments:
Post a Comment