# Find the number of times digit 3 occurs in each and every number from 0 to n

Program to find the number of times digit 3 occurs in each and every number from 0 to n is discussed here. Given a number n as input, count the number of 3s occurring in all the numbers from 0 to n.

For example,

Input: 100
Output: 20
Total number of 3s that appear from numbers 0 to 100 are {3, 13, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 53, 63, 73, 83, 93}

## Algorithm to find the number of times digit 3 occurs in each and every number

1. Input the number n from the user.
2. Initialize count = 0.
3. Repeat for all numbers from o to n.
4. Find if num % 10 == 3
5. Increment count
6. Divide the number by 10 and from step 4.
7. Return count.

Program to find the number of times digit 3 occurs in each and every number from 0 to n is given below.

// C program to find the number of times digit 3 occurs in each and every number from 0 to n

#include

int count_3s(int n)
{
int count = 0;
while (n > 0)
{
if (n % 10 == 3)
{
count++;
}

n = n / 10;
}
return count;
}

int count_in_range(int n)
{
int count = 0 ;
for (int i = 2; i <= n; i++)
{
count += count_3s(i);
}

return count;
}
int main()
{
int n;
printf(“\nEnter the end value : “);
scanf(“%d”, &n);
printf(“\nTotal occurrences of 3 from 0 to %d is %d\n”, n,count_in_range(n));
return 0;
}

// C++ program to find the number of times digit 3 occurs in each and every number from 0 to n

#include
using namespace std;

int count_3s(int n)
{
int count = 0;
while (n > 0)
{
if (n % 10 == 3)
{
count++;
}

n = n / 10;
}
return count;
}

int count_in_range(int n)
{
int count = 0 ;
for (int i = 2; i <= n; i++)
{
count += count_3s(i);
}

return count;
}

int main()
{
int n;
cout << “\nEnter the end value : “;
cin >> n;
cout << “\nTotal occurrences of 3 from 0 to ” << n << ” is ” << count_in_range(n) << endl;
return 0;
}

// Java program to find the number of times digit 3 occurs in each and every number from 0 to n

import java.util.*;
public class Main
{
static int count_3s(int n)
{
int count = 0;
while (n > 0)
{
if (n % 10 == 3)
{
count++;
}

n = n / 10;
}
return count;
}

static int count_in_range(int n)
{
int count = 0 ;
for (int i = 2; i <= n; i++)
{
count += count_3s(i);
}
return count;
}

public static void main(String[] args)
{
int number;
Scanner sc = new Scanner(System.in);
System.out.print(“\nEnter the number : “);
number = sc.nextInt();
System.out.print(count_in_range(number));
}
}

# Python program to find the number of times digit 3 occurs in each and every number from 0 to n

def count_3s(n):
count = 0
while (n > 0):
if (n % 10 == 3):
count = count + 1
n = int(n / 10)
return count

def count_in_range(n):
count = 0
for i in range(2,n):
count = count + count_3s(i);
return count

number = int(input(“Enter the number : “))
print(count_in_range(number))

Output:

Time complexity: O(n)