इस ट्यूटोरियल में, हम 1 से n तक की संख्याओं को खोजने के लिए एक प्रोग्राम पर चर्चा करेंगे, जिसमें 4 अंक होंगे।
इसके लिए हमें एक नंबर n प्रदान किया जाएगा। हमारा काम उन सभी नंबरों को गिनना है जिनमें 4 अंकों में से एक है और उसका प्रिंट आउट लेना है।
उदाहरण
#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