Thread: Recursion

  1. #1
    Registered User
    Join Date
    Oct 2020
    Posts
    69

    Recursion

    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?
    Last edited by rmmstn; 11-23-2020 at 05:27 PM.

  2. #2
    Registered User
    Join Date
    Sep 2020
    Posts
    425
    You might notice that even and odd are much the same function...

    odd(n);

    will be the same value as:

    even(n/10);

    Also, something about the "if(n < 10)" feels wrong. I feel you should be testing n against zero in some way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. recursion
    By rakeshkool27 in forum C Programming
    Replies: 9
    Last Post: 04-19-2010, 11:59 PM
  2. Recursion
    By supaman in forum C Programming
    Replies: 1
    Last Post: 03-10-2006, 12:09 AM
  3. Recursion
    By dayknight in forum C++ Programming
    Replies: 4
    Last Post: 01-26-2006, 02:02 AM
  4. Recursion help
    By Cstudent2121 in forum C Programming
    Replies: 11
    Last Post: 12-12-2005, 12:40 PM
  5. can someone help me out with recursion
    By JOsephPataki in forum C Programming
    Replies: 10
    Last Post: 05-13-2003, 04:55 PM

Tags for this Thread