Count number of occurrences of a digit with while/do while without using array in c++

Dani AI

Generated

was right to ask for assumptions. Typical interpretation: given an integer N (base 10) and a single digit D (0..9), count how many times D appears in N using arithmetic only (no arrays/strings). Below are two compact, safe examples — one using while, one using do...while — plus notes about negative input and edge cases. asked what you have so far; if your code differs, show it and these points can be adapted.

#include <iostream>
using namespace std;

int main() {
    long long n; int d;
    if (!(cin >> n >> d)) return 0;
    if (d < 0 || d > 9) return 0;
    unsigned long long temp = n >= 0 ? (unsigned long long)n
        : (unsigned long long)(-(n + 1)) + 1ULL; // safe for LLONG_MIN
    int count = 0;
    if (temp == 0 && d == 0) count = 1;
    while (temp > 0) {
        if (temp % 10 == (unsigned)d) ++count;
        temp /= 10;
    }
    cout << count << '\n';
}
#include <iostream>
using namespace std;

int main() {
    long long n; int d;
    if (!(cin >> n >> d)) return 0;
    if (d < 0 || d > 9) return 0;
    unsigned long long temp = n >= 0 ? (unsigned long long)n
        : (unsigned long long)(-(n + 1)) + 1ULL;
    int count = 0;
    do {
        if (temp % 10 == (unsigned)d) ++count;
        temp /= 10;
    } while (temp > 0);
    cout << count << '\n';
}

Notes: validate d is 0..9. The do...while naturally handles n == 0. Converting to unsigned long long with the -(n+1)+1 trick avoids overflow when n == LLONG_MIN. In C++ the sign of a % b follows the dividend, so working with a nonnegative value avoids negative remainders (see operator % behaviour on cppreference) (Remainder behaviour).

Recommended Answers

All 2 Replies

Seems like a homework question for you. What code do you have so far and where are your stuck? We’ll try to help.

One would have to make assumptions on this assignment such as are the digits in some integer and we assume base 10. Assumptions mean solutions could be incorrect. Show your work and don't leave out details such as the digits are in some integer and what base number system is to be used.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.