
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Count numbers from 1 to n that have 4 as a digit in C++
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.
Example
#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; }
Output
Count of numbers from 1 to 328 that have 4 as a digit is 60
- Related Articles
- Count of all N digit numbers such that num + Rev(num) = 10^N - 1 in C++
- Count n digit numbers not having a particular digit in C++
- Count numbers having 0 as a digit in C++
- Count divisors of n that have at-least one digit common with n in Java
- Count all possible N digit numbers that satisfy the given condition in C++
- Find count of Almost Prime numbers from 1 to N in C++
- Count n digit numbers divisible by given number in C++
- Count of Binary Digit numbers smaller than N in C++
- Count the numbers < N which have equal number of divisors as K in C++
- Count numbers (smaller than or equal to N) with given digit sum in C++
- C++ Program to count ordinary numbers in range 1 to n
- C++ program to count minimum number of binary digit numbers needed to represent n
- Finding all the n digit numbers that have sum of even and odd positioned digits divisible by given numbers - JavaScript
- Count ‘d’ digit positive integers with 0 as a digit in C++
- Count of different ways to express N as the sum of 1, 3 and 4 in C++

Advertisements