-1

Using a while loop, i need count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.

input sample: 2, 124218

output sample: 2

this is my code below:

#include<stdio.h>
int main() {
    int a;
    int num; 
    int i;
    int rev = 0;
    int reminder;
    int count = 1;
    int ans;
    int last;

    scanf("%d",&a);
    scanf("%d", &num );

    while(num!=0)
    {
        reminder=num%10;
        rev=rev*10+reminder;
        num/=10;

        if(a==reminder){
            ans++; 

            last = ans%10;
    
            printf("%d", last);
        }
        count++; 
    }
    return 0;
}
CiaPan
  • 9,381
  • 2
  • 21
  • 35
  • why are you printing `last`? – sittsering Jun 28 '21 at 09:28
  • 1
    Your program doesn't seem to print the result (a final value of the `ans` variable). It's also quite unclear what the purpose of calculating `rev` is. Is it _your_ code? Do you have an idea _why_ it is written that way? – CiaPan Jun 28 '21 at 10:23

2 Answers2

0
#include<stdio.h>
#include<stdlib.h>
int main() {
int a, num, remainder, count = 0;

scanf("%d",&a);
scanf("%d",&num );
int temp = abs(num);
while(temp!=0)
{
    remainder=temp%10;
    temp/=10;
    if(a==remainder)
        count++; 
}
printf("%d",count);
return 0;
}
sittsering
  • 1,219
  • 2
  • 6
  • 13
0
int count_digit(const unsigned digit, int number)
{
    int count = 0;
    if(digit < 10)
    {
        while(number)
        {
            if(digit == abs(number % 10)) count++;
            number /= 10;
        }
    }
    else
    {
        count = -1;  //error 
    }
    return count;
}

int main(void)
{
    printf("%d\n", count_digit(5, 455675));
    printf("%d\n", count_digit(3, -35633435));
}
0___________
  • 60,014
  • 4
  • 34
  • 74