Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A common kind of puzzle question is \"how many numbers between 1 and 1000 contai

ID: 3675624 • Letter: A

Question

A common kind of puzzle question is "how many numbers between 1 and 1000 contain the digit 11". Write a function countNumsfithDigit(upperNumber, digit) that returns the number of numbers from 1 through upperNumber that contain the given digit. For example countNumsf ithDi git (10, 9) should return 1, countNumsf ithDi git (10, 1) should return 2, and countNumsWithDigit(30, 2) should return 12. Your function must use a list comprehension (but remember, it returns a number not a list!) and have only one line of code (in addition to the def line).

Explanation / Answer

#include<stdio.h> // Preprocessor directive

//Main function
int main(){
    int x;
    int digit,range;
  

    printf("Enter the digit to be counted:");
    scanf("%d",&digit);
    printf("Enter the range in which the digit to be counted: ");
    scanf("%d",&range);
  
    //calling the function
    x=countOccurrences(range,digit);
    printf("%d numbers between %d and %d contain the digit '%d'",x,digit, range, digit);
  
  
    getch();
}


int countOccurrences(int range, int digit)
{
    int counter = 0,c=0;
    int i;
    for(i=1; i<=range; i++)
    {
        int j = i;
        while(j > 0)
        {
            if(j%10 == digit)
                counter++;
            j /= 10;
        }
        if(counter!=0)
                     c++;
                     counter=0;
    }
    return c;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote