C Exercises: Reads an integer and count number of 3s in the given number
Count occurrences of the digit 3 in a number
Write a C program that reads an integer (7 digits or fewer) and counts the number of 3s in the given number.
Sample Input: 538453
Sample Solution:
C Code:
#include<stdio.h>
// Function to count the occurrences of digit '3' in a number
int count_three(int);
int main()
{
int num;
// Prompt user for input
printf("Input a number: ");
scanf("%d", &num);
// Call the function count_three and print the result
printf("The number of threes in the said number is %d\n", count_three(num) );
return 0;
}
int count_three(int num)
{
int ctr = 0; // Initialize counter variable
int remainder; // Variable to store the remainder
// Loop until num is greater than 0
while(num> 0) {
remainder = num % 10; // Get the last digit
num /= 10; // Remove the last digit
if(remainder == 3) // Check if the last digit is 3
ctr++; // Increment counter if it is 3
}
return ctr; // Return the count of occurrences of 3
}
Sample Output:
Input a number: The number of threes in the said number is 2.
Pictorial Presentation:
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to count the frequency of a specified digit in an integer using a loop.
- Write a C program to count how many times the digit 3 appears in a number using recursion.
- Write a C program to count occurrences of digit 3 and compare it with the count of another digit, such as 7.
- Write a C program to compute the frequency of digit 3 in an integer and output the positions where it occurs.
Go to:
PREV :Check if a 5-digit integer is a palindrome.
NEXT : Calculate the average of integers until 888 is entered.
C programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.