How do I create a function that will take two integers, num1
, num2
, and return an integer and the function will check if the numeric value of the number num2
is in the digits of the number num1
.
example num1 = 51749
, num2 = 566
:
num1
have 17
, num2
sum is 17
int func(int num1, int num2)
this is the start of the function with no array.
I started this one but for some reason it's not working can you please explain me what is the problem.
#include <stdio.h>
#include <stdlib.h>
int func(int num1, int num2) {
int sum = 0, sum2 = 0, ad = 0;
int digit;
while (num1 > 0) {
digit = num1 % 10;
sum = sum digit;
num1 = num1 / 10;
}
while (num2 > 0) {
digit = num2 % 10;
sum2 = sum2 digit;
num2 = num2 / 10;
}
while (ad < 10) {
if (sum =! num2)
printf("The number is correct");
ad ;
}
printf("Different");
}
int main() {
int a, b;
printf("Type the first number ");
scanf("%d", &a);
printf("Type the second number ");
scanf("%d", &b);
if (func(a, b) == 1)
printf("Yes");
if (func(a, b) == 0)
printf("No");
return 0;
}
CodePudding user response:
There is a typo in if (sum =! num2)
: you probably mean this instead:
if (sum != num2)
In case you wonder why the bogus expression compiles at all, sum =! num2
is parsed as sum = !num2
which assigns 0
or 1
to sum
if num2
is zero or not.
Note also that your function does not test whether the sum of digits in num2
exists inside num1
. You must use a different method:
- compute
sum2
: the sum of digits innum2
- test if this number is present in
num1
either as a 1-digit or a 2-digit number (becausesum2
has either 1 or 2 digits). - you may need to make a special case of (0, 0).
Here is a modified version:
#include <stdio.h>
int func(int num1, int num2) {
int sum2 = 0;
while (num2 > 0) {
sum2 = num2 % 10;
num2 /= 10;
}
if (sum2 == 0 && num1 == 0)
return 1; // special case for (0, 0)
while (num1 > 0) {
if (num1 % 10 == sum2)
return 1; // sum2 has 1 digit and is present
if (num1 % 100 == sum2)
return 1; // sum2 has 2 digits and is present
num1 /= 10;
}
return 0; // sum2 is not present
}
int main() {
int a = 0, b = 0;
printf("Type the first number: ");
scanf("%d", &a);
printf("Type the second number: ");
scanf("%d", &b);
if (func(a, b)) {
printf("Yes\nsum of digits in %d is present in %d\n", b, a);
} else {
printf("No\nsum of digits in %d is not present in %d\n", b, a);
}
return 0;
}