I'm having some problems regarding 2 recursive problems:
Code:
/*Write a function that takes an unsigned n and returns the number on even positions. */
#include <stdio.h>
unsigned evenPositions(unsigned n){
if(n<10)
return 0;
else return n%10+evenPositions(n/100)*10;
}
int main(){
unsigned a = 123456;
printf("The new number is %d", evenPositions(a));
return 0;
}
Output: 246
But for n = 1234567
Output : 357
This only works if the number if made out of an even number of digits. How may I fix this?
Code:
/*Write a function that takes an unsigned n and returns the number on odd positions.*/
unsigned oddPositions(unsigned n){
if(n<10)
return n;
else
return n/10%10+oddPositions(n/100)*10;
}
int main(){
unsigned n = 12345678;
printf("The new number is %d", oddPositions(n));
return 0;
}
Output: 1357
But for n = 123456789;
Output: 12468
I have the same problem with this problem, it only works for an even number of digits. Just to clarify, the problem statement does not specify the way that the digits should be counter (left to right or right to left). How can I improve my code/logic?