Thread: Failing to Use Recursion - Arithmetic Calculator

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    27

    Failing to Use Recursion - Arithmetic Calculator

    Hi all!

    My most recent programming woes stem from a lack of reading comprehension on my part. I am supposed to code a simple arithmetic calculator to handle +/- expressions of any length,

    i.e. 2 + 3 - -7 + 9

    To avoid making my post overly-long with code, here's the link to my previous iteration of program (non-recursive, using a switch): Coursework/evaluate.c at master * burgerkong/Coursework * GitHub

    Unfortunately, I failed to realize that I need to use recursion in my implementation of the program; and the below version (my current attempt) has not been working:

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    float s_exp(float sub_exp, char op);
    char get_op();
    float get_num();
    
    
    int main()
    {
        float exp;
        char op;
        printf("Please enter an arithmetic expression: ");
        exp = get_num();
        op = get_op();
        printf("%f", s_exp(exp, op));
        return 0;
    }
    
    
    float s_exp(float sub_exp, char op)
    {
        if(op != '\n')
        {
            switch(op)
            {
            case '+':
                sub_exp = sub_exp + get_num();
                break;
            case '-':
                sub_exp = sub_exp - get_num();
                break;
            case ' ':
                break;
            default:
                printf("Sorry, there was an invalid operator in your equation.  Please only use +/-.");
                exit(0);
            }
            get_op();
            s_exp(sub_exp, op);
        }
        return sub_exp;
    }
    
    
    char get_op()
    {
        char next_op;
        next_op = getchar();
        return next_op;
    }
    
    
    float get_num()
    {
        float next_num;
        scanf("%f", &next_num);
        return next_num;
    }
    Currently, entering an expression causes an infinite loop. Entering a single integer works correctly.

    How should I implement recursion? And why does my program not correctly interpret the operator?

    Thanks, and sorry if I'm missing something obvious (I feel like I am, but have been struggling for the past hour).

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Your recursive calls ignore their return results; compare with how you call them in main.

    Try say
    op = get_op();
    sub_exp = s_exp(sub_exp, op);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    To implement a parser and interpreter for general algebraic expressions requires parsing techniques; the simplest of which is a recursive decent parser. In order to implement that, you need to refactor your grammar into a non-left recursive form. (It's a straightforward grammar transformation in the case of algebraic expressions). It's not possible to parse and evaluate at the same time. You could benefit from a study of abstract syntax trees and precedence rules. This code simply won't do...

    I don't want to come of as some .............., I'm just trying to give some suggestions.
    Last edited by MacNilly; 02-15-2017 at 01:59 AM.

  4. #4
    Registered User
    Join Date
    Feb 2017
    Posts
    27
    Hey Salem!

    Thanks for the tip, definitely a brainfart on my end with regards to the recursion implementation.

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    float s_exp(float sub_exp, char op);
    char get_op();
    float get_num();
    
    
    int main()
    {
        float exp;
        char op;
        printf("Please enter an arithmetic expression: ");
        exp = get_num();
        op = get_op();
        printf("Result: %.2f", s_exp(exp, op));
        return 0;
    }
    
    
    float s_exp(float sub_exp, char op)
    {
        if(op != '\n')
        {
            switch(op)
            {
            case '+':
                sub_exp = sub_exp + get_num();
                break;
            case '-':
                sub_exp = sub_exp - get_num();
                break;
            case ' ':
                break;
            default:
                printf("Sorry, there was an invalid operator in your equation.  Please only use +/- when using this program in the future.");
                exit(0);
            }
            op = get_op();
            sub_exp = s_exp(sub_exp, op);
        }
        return sub_exp;
    }
    
    
    char get_op()
    {
        char next_op;
        next_op = getchar();
        return next_op;
    }
    
    
    float get_num()
    {
        float next_num;
        scanf("%f", &next_num);
        return next_num;
    }
    Here's where my program currently sits. Have to run some test cases, but it seems to be functioning! Thanks <3

  5. #5
    Registered User
    Join Date
    May 2012
    Posts
    505
    You need a lexer, to tell you what type of data is coming.
    In you case the lexer is simply + - or "number", but we might as well add * / and ().

    The you typically have factors, terms, and expressions.

    A factor is either a number or ( expression ). So you see how recursion is built in.
    A term is a list of factors joined by * or /
    An expression is a list of terms joined by + or -.

    So the easiest expression to evaluate is simply a number. Get that working first.

    Then try the factor 2*2

    Then try 2*2 + 3

    Then finally (2 + 2) * 3

    At that point, everything should be in place, barring trivial extensions to divide and subtract.

    My book MiniBasic, how to write a script interpreter explains the entire process.

    Mini-Basic by Malcolm McLean on iBooks
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. free() Failing
    By nickman in forum C Programming
    Replies: 5
    Last Post: 09-07-2012, 02:17 AM
  2. Getchar() arithmetic calculator problem.
    By Cowmoogun in forum C Programming
    Replies: 2
    Last Post: 03-28-2012, 04:05 AM
  3. Arithmetic sum calculator
    By fatsrir in forum C Programming
    Replies: 11
    Last Post: 06-13-2011, 01:08 PM
  4. Calculator Recursion Version *HELP*
    By _john_ in forum C++ Programming
    Replies: 3
    Last Post: 04-17-2006, 11:17 PM
  5. Failing to initialize COM
    By andyhunter in forum Windows Programming
    Replies: 8
    Last Post: 12-22-2004, 03:43 PM

Tags for this Thread