how can you write a program that returns the last integer of the inputted number from the keyboard by the user using recursion?

Recommended Answers

All 3 Replies

Why do you ever want to do that? Because it is your homework assignment?

You need a few pieces:

  • Input routine to collect user number
  • Process to split that number into individual digits
  • Recursive call that takes the result of the above operation as input and returns a digit in the terminating case

Recursion can be tricky ... especially when you first try it ... so look up lots of examples where recursion is used.

For a popular example, see 'quick sort'

The following (inefficent design) on a related example may give you some ideas on how to get started ...

/* getLastCharRecursive.c */

#include <stdio.h>
#include <string.h>
#include <ctype.h> /* re. tolower ... */

/*
    this efficient demo uses recursive calls ...
    string passed in MUST BE NON-empty
*/
char getLastDig( const char* s )
{
    char c = s[0];
    if( *(s+1) == 0 ) return c;
    getLastDig( s+1 );
}

/* a handy utility for many C student coding problems ... */
char takeInChar( const char* msg )
{
    char chr;
    fputs( msg, stdout ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' )
        while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}


int main()
{
    char buf[1024], c, *p;

    do
    {
        for( ; ; )
        {
            fputs( "Enter several char's: ", stdout );
            fflush( stdout );

            fgets( buf, sizeof(buf) , stdin );
            p = strchr( buf, '\n' );
            if( p ) *p = 0;
            else while( getchar() != '\n' ); /* flush stding */

            printf( "You entered '%s'\n", buf );

            /* ensure something entered before breaking ... */
            if( buf[0] ) break; /* if( buf[0] != 0 ) break; */
            /* else...    */
            printf( "You *must* enter something ... "
                    "try again ...\n");
        }

        c = getLastDig( buf );

        printf( "The last char entered (before 'Enter pressed') "
                "was: '%c'\n", c );
    }
    while( tolower( takeInChar( "More (y/n) ? " )) != 'n' );

    fputs( "\nPress 'Enter' to continue/exit ... ", stdout );
    fflush( stdout );
    getchar();
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.