- Related Questions & Answers
- Average numbers in array in C Programming
- C Program to Multiply two Floating Point Numbers?
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of first n natural numbers in C Program
- HTML DOM console.count() Method
- Print multiples of Unit Digit of Given Number in C Program
- C/C++ Programming to Count trailing zeroes in factorial of a number?
- Sum of squares of first n natural numbers in C Program?
- C++ Programming for Smallest K digit number divisible by X?
- Sum of squares of the first n even numbers in C Program
- To count Vowels in a string using Pointer in C++ Program
- Find all the numbers in a string using regular expression in Python
- Count frequencies of all elements in array in Python using collections module
- Lambda expression in Python to rearrange positive and negative numbers
- Count distinct elements in an array in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this tutorial, we will be discussing a program to find the numbers from 1 to n that have 4 as a digit.

For this we will be provided with a number n. Our task is to count all the numbers which have 4 as one of their digits and print it out.

#include<iostream> using namespace std; bool has4(int x); //returning sum of digits in the given numbers int get_4(int n){ int result = 0; //calculating the sum of each digit for (int x=1; x<=n; x++) result += has4(x)? 1 : 0; return result; } //checking if 4 is present as a digit bool has4(int x) { while (x != 0) { if (x%10 == 4) return true; x = x /10; } return false; } int main(){ int n = 328; cout << "Count of numbers from 1 to " << n << " that have 4 as a digit is " << get_4(n) << endl; return 0; }

Count of numbers from 1 to 328 that have 4 as a digit is 60

Advertisements