Recursion not getting me the output I need - c

I'm new to programing and I'm doing recursion exercises, and one of them was to count how many odd numbers I have inside a number:
this is my code:
int countOdd(int num, int count)
{
int temp;
printf("num\n%d", num);
if (num<ZERO)return count;
temp = num % 10;
if ((temp % 2) != 0) countOdd(num / 10, count + ONE);
printf("test");
countOdd(num / 10, count);
}
its suppose to get the number and count how many odd number there is and return it as a value, could someone explain to me why it isn't working, tips and ideas will be highly appreciated.

whatever non-negative value divided by 10 will be again non-negative.
But your recursion termination condition is if (num<ZERO)return count;, that will never happen.
A fixed variant of your code may look like this (still using recursion for your educational reasons, otherwise non recursive code would be better):
int countOdd(int num) {
if (num <= 0) return 0;
return (num&1) + countOdd(num/10);
}
Also don't use printf for debugging your code, use proper debugger.

As you said, you're supposed to return something. So make sure you return something, i.e., add the missing return statements. Also terminate the recursion when you reach zero, or you'll have an infinite loop.
int countOdd(int num, int count)
{
int temp;
printf("num\n%d", num);
if (num<=ZERO) return count;
temp = num % 10;
if ((temp % 2) != 0) return countOdd(num / 10, count + ONE);
printf("test");
return countOdd(num / 10, count);
}

Related

recursive Function, to find even or odd digits inside given number

Basically, its printing only one instance when it happens, and i don't understand why, maybe has something to do with the code reseting every time and starting the variable at 0 again, and i got another question if someone can help me with, i have to return both values when its odd and even, like how many digits are even and odd at the same time, i'm having a little trouble figuring out how to do it
#include <stdio.h>
int digits(int n)
// function that checks if the given value is odd or even, and then add
// + 1 if it's even, or odd, it's supposed to return the value of the quantity
// of digits of the number given by the main function
{
int r;
int odd = 0;
int even = 0;
r = n % 10;
if (r % 2 == 0) // check if given number is even
{
even = even + 1;
}
if (r % 2 != 0) // check if its odd
{
odd = odd + 1;
}
if (n != 0) {
digits(n / 10); // supposed to reset function if n!=0 dividing
// it by 10
}
if (n == 0) { return odd; }
}
int
main() // main function that sends a number to the recursive function
{
int n;
printf("type number in:\n ");
scanf("%d", &n);
printf("%d\n", digits(n));
}
odd and even variables are local in your code, so they are initialized by zero every time.
I think they should be declared at caller of the recursive function, or be declared as global variables.
#include <stdio.h>
void digits(int n, int *even, int *odd)//function
{
int r;
r = n % 10;
if (r % 2 == 0)//check if given number is even
{
*even = *even + 1;
}
else //otherwise, its odd
{
*odd = *odd + 1;
}
n /= 10;
if (n != 0)
{
digits(n, even, odd);//supposed to reset function if n!=0 dividing it by 10
}
}
int main()
{
int n, even = 0, odd = 0;
printf("type number in:\n ");
scanf("%d", &n);
digits(n, &even, &odd);
printf("even: %d\n", even);
printf("odd: %d\n", odd);
return 0;
}
Maybe I found the problem you are facing. You you initialized you odd and even variable as zero. every time you call the function it redeclares their value to zero again. You can use pointer caller or use those as your global variable so that every time they don't repeat their initial values again.
Implementing a function that counts the number of odd and even digits in a number, is not to be done using recursive. That is simply a wrong design choice.
But I assume that it's part of your assignment to use recursion so ... okay.
You want a function that can return two values. Well, in C you can't!! C only allows one return value. So you need another approach. The typical solution is to pass pointers to variables where the result is to be stored.
Here is the code:
void count_odd_even(const int n, int *even, int *odd)
{
if (n == 0) return;
if (((n % 10) % 2) == 1)
{
*odd += 1;
}
else
{
*even += 1;
}
count_odd_even(n/10, even, odd);
}
And call it like
int odd = 0;
int even = 0;
count_odd_even(1234567, &even, &odd);

Recursion in C: why does my simple code doesn't work?

Given i the value of 3, the output should be the sum of 3/(3+1) + 2/(2+1) + 1/(1+1), always stopping on 1.
I can't seem to figure out what's wrong with what I did, thank you for your attention.
#include <stdio.h>
#include <math.h>
int sum_recur(int i) {
if (i > 1) {
return sum_recur(i - 1) / (sum_recur(i - 1) + 1);
} else {
return 1;
}
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%d \n", sum_recur(i));
}
I think this would be the right recursive implementation of your formula
int sum_recur(int i){
if(i >= 1){
return (i / (i + 1)) + sum_recur(i-1);
} else{
return 0;
}
}
Also, as #atirit mentioned, you should consider making the output to be float or double in order to preserve the floating points values of the division result. Otherwise, the result of sum_recur will always be 0 since i / (i + 1) is always 0 for integer type
#include <stdio.h>
#include <math.h>
float sum_recur(int i){
if(i >= 1){
return (i / (i + 1.0)) + sum_recur(i-1);
} else{
return 0;
}
}
int main(void){
int i;
printf("Inform a number:\n");
scanf("%d",&i);
printf("%f \n",sum_recur(i));
}
Here's what I believe you're trying to implement, no need for recursion, but it's there if you need it:
#include <stdio.h>
double sum_recur(double i) {
if (i < 1) return 0;
return i / (i + 1) + sum_recur(i - 1);
}
double sum_iter(double i) {
double sum = 0;
for (; i >= 1; i--) {
sum += i / (i + 1);
}
return sum;
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%f \n", sum_iter((double) i));
printf("%f \n", sum_recur((double) i));
}
The summary is this:
There's no need for the math library.
Use float or double and not int - in the code itself and in the printf.
Correct the logic in the recursion.
It can be solved iteratively quite nicely.
I don't understand what are you trying to achieve from this code. The code that you've written will always return 2.
sum_recur will always stop at 1 and you return statement will calculate 1/1+1, which is always 2. For input 3, the sum_recur will generate following:
sum_recur reaches 1 and hence returns 1 for input value 2
1/1 + 1 = 2, so for i=2 sum_recur will again return 2
This is will go on for any input number. This is why no matter what the input is, output of this recursion will always be 2. Further, what you expect this function to do in your question statement is not possible if you're using division between recursion calls. The result that you're looking to achieve is simply addition of 2 n-times or multiplication of 2 with n.
The answers written here explain the problem reasonably well, I just want to add a little bit on your code specifically,
While you do f(i-1)/f(i-1)+1 this is a terrible way of doing this and in case of a larger seed input this might cause you runtime problem with stackoverflow. So I suggest you should try something that's more efficient if at all you have to use recusion. Like this by storing the fun call value
int n = f(i-1);
return n/n +1;

Reverse two numbers and obtain the reverse of the sum

I am coming to SO as a last resort. Been trying to debug this code for the past 2 hours. If the question is suited to some other SE site, please do tell me before downvoting.
Here it goes:
#include <stdio.h>
#include<math.h>
int reverse(int n) {
int count = 0, r, i;
int k = (int)log(n * 1.0);
for(i = k; i >= 0; i--)
{
r = (n % 10);
n = (n / 10);
count = count + (r * pow(10, k));
}
return count;
}
int main(void) {
int t;
scanf("%d", &t);
while(t--)
{
int m, n, res;
scanf("%d %d", &m, &n);
res = reverse(m) + reverse(n);
printf("%d", reverse(res));
}
return 0;
}
My objective is to get 2 numbers as input, reverse them, add the reversed numbers and then reverse the resultant as well.I have to do this for 't' test cases.
The problem: http://www.spoj.com/problems/ADDREV/
Any questions, if the code is unclear, please ask me in the comments.
Thank you.
EDIT:
The program gets compiled successfully.
I am getting a vague output everytime.
suppose the 2 numbers as input are 24 and 1, I get an output of 699998.
If I try 21 and 1, I get 399998.
Okay, if you had properly debugged your code you would have notices strange values of k. This is because you use log which
Computes the natural (base e) logarithm of arg.
(took from linked reference, emphasis mine).
So as you are trying to obtain the 'length' of the number you should use log10 or a convertion (look at wiki about change of base for logarithms) like this: log(x)/log(10) which equal to log10(x)
And now let's look here: pow(10, k) <-- you always compute 10^k but you need 10^i, so it should be pow(10, i) instead.
Edit 1: Thanks to #DavidBowling for pointing out a bug with negative numbers.
I don't know how exactly you have to deal with negative numbers but here's one of possible solutions:
before computing k:
bool isNegative = n < 0;
n = abs(n);
Now your n is positive due to abs() returning absolute value. Go on with the same way.
After for loop let's see if n was negative and change count accordingly:
if (isNegative)
{
count = -count;
}
return count;
Note: Using this solution we reverse the number itself and leave the sign as it is.
It looks like Yuri already found your problem, but might I suggest a shorter version of your program? It avoids using stuff like log which might be desirable.
#include <stdio.h>
int rev (int n) {
int r = 0;
do {
r *= 10;
r += n % 10;
} while (n /= 10);
return r;
}
int main (void) {
int i,a,b;
scanf("%d",&i);
while (i--) {
scanf("%d %d",&a,&b);
printf("%d\n",rev(rev(a) + rev(b)));
}
return 0;
}
Hopefully you can find something useful to borrow! It seems to work okay for negative numbers too.
Under the hood you get char string, reverse it to numeric, than reverse it to char. Since is more comfortable work with chars than let's char:
char * reverse (char *s,size_t len) //carefull it does it in place
{
if (!len) return s;
char swp, *end=s+len-1;
while(s<end)
{
swp =*s;
*s++=*end;
*end--=swp;
}
return s;
}
void get_num(char *curs)
{
char c;
while((c=getchar())!='\n')
*curs++=c;
*curs=0;
}
int main()
{
double a,b,res;
char sa[20],sb[20],sres[20],*curs;
get_num( sa);
get_num(sb);
reverse(sa,strlen(sa));
reverse(sb,strlen(sb));
sscanf(sa,"%f",&a);
sscanf(sb,"%f",&b);
res=a+b;
sprintf(sres,"%f",res);
reverse(sres);
printf(sres);
}

How often is a number divisible without a rest?

I am currently trying to write a method which checks how often a number is divisible by 5 with a rest of 0 (e.g. 25 is two times; 125 is three times).
I thought my code is correct but it always states that it is possible one more time than it actually is (e.g. 25 is three times; wrong).
My approach is the following:
int main()
{
div_t o;
int inp = 25, i = 0;
while(o.rem == 0){
o = div(inp, 5);
inp = o.quot;
i++
}
return 0;
}
I debugged the code already and figured that the issue is that it steps once more into the loop even though the rest is bigger 0. Why is that? I can't really wrap my head around it.
First: 25/5 = 5; Rest = 0;
Second: 5/5 = 1; Rest = 1; - Shouldn't it stop here?
Third: 1/5 = 0; Rest = 1;
Ah... got it. The point where the remainder is 0 is reached when the division is done with the number which results in a rest bigger zero which is after i got increased.
What is the cleanest approach to fix that? i -= 1 seems kinda like a workaround and I wanted to avoid using an if to break
You're using div() to do the division, which I had to look up to verify that it's part of the standard. I think it's kind of rarely used, and more suited for cases where you really care about performance. This doesn't seem like such a case, and so I think it's a bit obscure.
Anyhow, here's how I would expect it to look, without div():
#include <stdio.h>
unsigned int count_factors(unsigned int n, unsigned int factor)
{
unsigned int count = 0;
for(; n >= factor; ++count)
{
const int remainder = n % factor;
if(remainder != 0)
break;
n /= factor;
}
return count;
}
int main(void) {
printf("%u\n", count_factors(17, 5));
printf("%u\n", count_factors(25, 5));
printf("%u\n", count_factors(125, 5));
return 0;
}
This prints:
0
2
3
Change the while loop condition in :
while(o.rem == 0 && inp >= 5)
In this way your division will stop after that you are inspecting the number 5.
A suggestion: use a const variable to wrap the 5 ;)
As far as I understand you want to know whether the input is an integer power of 5 (or in general whether v == N^x) and if it is, you want to calculate and return the power (aka x). Otherwise return 0. This is more or less a logN function except that it requires integer results.
I would go for code like this:
#include <stdio.h>
unsigned int logN_special(unsigned int v, unsigned int n)
{
unsigned int r = 0;
if (n == 0) return 0; // Illegal
if (n == 1) return 0; // Illegal
if (v < n) return 0; // Will always give zero
if (n*(v/n) != v) return 0; // Make sure that v = n^x
// Find the x
while(v != 1)
{
v /= n;
++r;
}
return r;
}

Recursive function In C

I have a recursive function and I want to count the number of zeros in it, how do I use a constant to count the zero and not allowing to reset.
int countZeros(int num)
{
int count = 0;
if (num > 0)
{
if (num % 10 == 0)
count++;
return(countZeros(num / 10));
}
if (num <= 0)
return count;
}
For my code, my count will reset once my return function is called. Is there any way to prevent this from happening? I have to return the value back to my main function and display from there.
case 9:
printf("Enter a number: ");
scanf("%d", &recursion);
printf("number of zeros = %d",countZeros(recursion));
break;
Try this code:
int countZeros(int num)
{
if (num > 0 && num % 10 == 0)
return(countZeros(num / 10)+1);
else
return 0;
}
It will work in the same way, only note that if your num is negative (but still with zeroes, like -100, it will return 0).
In order to work with negative numbers, use this:
int countZeros(int num)
{
if (num !=0 && num % 10 == 0)
return (countZeros(num / 10)+1);
else
return 0;
}
Make your int static:
static int count = 0;
Here is a sample run.
Pointers will work as well:
#include <stdio.h>
int countZeros(int num, int * count)
{
if (num > 0)
{
if (num % 10 == 0)
(*count)++;
return(countZeros(num / 10,count));
}
if (num <= 0)
return *count;
}
int main(void)
{
int count = 0;
printf("Count = %d",countZeros(1000,&count) );
return 0;
}
Avoid static variables, they are evil, for multiple reasons...
The only algorithm that works, and doesn't just count the trailing zeros, is ring0's answer, but please, local variables are free, and explicit code helps not only the reader, but is much more maintainable.
Run it here.
#include <stdio.h>
int main(void)
{
printf("Count = %d\n", countZeros( 10100) );
printf("Count = %d\n", countZeros(-10010) );
return 0;
}
int countZeros(int num)
{
// Final stop
if (num == 0 )
return 0;
// Recursion for numbers to the left
int count = countZeros(num / 10);
// Increase count if current unit is 0
if (num % 10 == 0)
count++;
return count;
}
Explanation:
For the recursion, you need a converging process and a stop condition.
The first IF is the base case. Dividing 3 (or -3 for that matter) by 10 will always end up being 0. This is what ends the recursion (stop condition).
The second and last blocks are interchangeable. If the rightmost number is 0, you increase the counter, but then, you also need to add the count result from all the numbers to the left. This is done by seeding it only what you didn't count, hence the division by 10 (to converge).
Both division and modulo works the same for negative and positive numbers, so you keep the behavior for both ends of the integer range.
Without any more variable
int countZeros(int n) {
return n ? (n % 10 ? 0:1)+countZeros(n/10) : 0;
}
countZeros works also with negative numbers.
Example
printf("%d\n", count( 10001)); // prints "3"
printf("%d\n", count(-10001)); // prints "3"
use static variable.
static int count = 0;

Resources