Thread: Homework help! C program value of math expression using strings

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    23

    Exclamation Homework help! C program value of math expression using strings

    Hi, I really need some help with this code. I am really stuck on this and have no clue where to go, any help would be much appreciated.

    here is my objective:

    Write a c program thatcalculates the value of a mathematical expression comprised ofpositive numbers and the operations ‘+’ and ‘-’.Specifically, first prompt the user to input an expression, read itin as a string, and then print the value of the expression. You mayassume that the expression does not contain spaces, maximumsize of the expression (including digits and operators) can be 20,and that all numbers are single digit numbers.


    Hints: Note that, thedigits would be read in as characters; you will need to translatethem to numbers (recall the ASCII table).


    Implementation Requirements



    1. Write a function called “evaluate” that takes as input a mathematical expression (as a string) and returns the value of the expression. The prototype of the function is—“int evaluate(char expr[]);”





    Sample Output:


    Input: 4+2-1+7
    Output:12

    here is the code:

    Code:
    int main()
    {
       char expr[21];
       int a,ssum;
    
    
       printf("Input: ");
       scanf("%20s", expr);
    
    
       ssum = evaluate(&a);
    
    
       printf("\nOutput: %d", ssum);
    }
    
    
    int evaluate(char expr[])
    {
        int i, sum=0;
    
    
        for(i=0; i<21; i++)
        {
            sum = sum + expr[i];
        }
    
    
        return sum;
    }
    the program runs, but the output is not coming out correct.
    Thanks for all the help in advance.

  2. #2
    Registered User
    Join Date
    Aug 2013
    Posts
    196
    Hi, it's an easy function you're trying to do let me do a psuedo code for you if that's fine.

    Code:
    You first give the name to the function and then two places inside the function. One should include the expr, and the other should be about the number of elements.
    
    Integer i, and the sum both are equal to 0
    for i is 0, and i is less than the number of elements, add to i
    sum is the solution of adding sum to the expr.
    return sum
    I'm not that good for writing the psuedo code for someone else but this is how it came to my mind blah

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    214
    You do realize that your input expression is not just numbers. Its numbers and operators (+, -,...) You can't just add expr[i] to a sum.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You store a string in your array.
    Your "evaluate()" function expects that array as an argument.
    So why are you passing the address of a random integer called 'a' to that function - especially considering 'a' is not used anywhere in your program?

    DaveH pretty much summed up the big issue with your code. The "for()" loop in your "evaluate()" function goes through each element of your array. Different things are supposed to happen depending on if an element is a number, a '+', or a '-'.

  5. #5
    Registered User
    Join Date
    Aug 2013
    Posts
    196
    I could show you my code on how I made it work, but this would go against of this forum which is let the OP work on his code until he just can't anymore.

  6. #6
    Registered User Suhasa010's Avatar
    Join Date
    Sep 2013
    Posts
    10
    Use a if condition for checking the + and - operators instead of a for loop. and evaluate the values of even indices of the array with values of odd indices in between(as an operator)
    Last edited by Suhasa010; 11-05-2013 at 11:16 AM.

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Use a if condition for checking the + and - operators instead of a for loop
    The "for()" loop will still be needed to cycle through the elements of the array.

  8. #8
    Registered User
    Join Date
    Sep 2013
    Posts
    23
    I am still a little confused. Would it be best to maybe make 2 for loops in the evaluate function, odd indices for the operators and even indices for the numbers. If this is the best case, can anyone give me an idea of how to impliment this because I am extremely lost with this. IM DYING OVER HERE!!!(PLEASE HELP!!!)

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by tshort82392
    Would it be best to maybe make 2 for loops in the evaluate function, odd indices for the operators and even indices for the numbers.
    I think that that may complicate things instead since you then need to figure out which operators are for which pairs of operands. It may be easier to test the loop index to see if it is odd or even.

    Consider parsing and evaluating "4+2-1+7" with a single loop:
    Code:
    Start with result=0.
    Loop character by character starting from index=0:
        index==0: you add 4 to the result.
        index==1: you note that the operator is a '+'.
        index==2: you add 2 to the result since the current operator is a '+'.
        index==3: you note that the operator is a '-'.
        index==4: you subtract 1 from the result since the current operator is a '-'.
        etc
    Return the result
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Sep 2013
    Posts
    23
    Code:
    int main()
    {
       char expr[21];
       int ssum;
       printf("Input: ");
       scanf("%20s", expr);
       ssum = evaluate(expr);
       printf("Output: %d", &ssum);
       return 0;
    }
    
    
    int evaluate(char expr[])
    {
        int i, sum=0;
    
    
        for(i=0; i!='\0'; i++)
        {
            if(expr[i]=='+')
            {
                sum = atoi(expr[i-1] + atoi(expr[i+1]));
            }
    
    
            if(expr[i]=='-')
            {
                sum = atoi(expr[i-1] - atoi(expr[i+1]));
            }
        }
    
    
        return sum;
    }
    This is what I have now and it is compiling, but still not giving a correct output.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by tshort82392
    This is what I have now and it is compiling
    You need to compile at a higher warning level. For example, on my copy of gcc 4.7.3 with -Wall -pedantic options, I get:
    Code:
    test.c: In function ‘main’:
    test.c:5:4: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
    test.c:5:4: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
    test.c:6:4: warning: implicit declaration of function ‘scanf’ [-Wimplicit-function-declaration]
    test.c:6:4: warning: incompatible implicit declaration of built-in function ‘scanf’ [enabled by default]
    test.c:7:4: warning: implicit declaration of function ‘evaluate’ [-Wimplicit-function-declaration]
    test.c:8:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]
    test.c: In function ‘evaluate’:
    test.c:22:13: warning: implicit declaration of function ‘atoi’ [-Wimplicit-function-declaration]
    The "implicit declaration of function" warnings are because you forgot to #include <stdio.h> (EDIT: and <stdlib.h>, but you don't actually need that here). The "format ‘%d’ expects argument of type ‘int’" warning is because you passed &ssum instead of ssum to printf.

    Quote Originally Posted by tshort82392
    still not giving a correct output.
    That is because the algorithm that you're implementing is wrong. Suppose you want to evaluate "1+2+3". Your algorithm will compute 1+2 when it finds the first '+' and then compute 2+3 when it finds the second '+'. The final sum will thus be 5, but in actual fact it should be 6. Furthermore, your use of atoi is incorrect as atoi is to be used with strings, not invidivual characters. You should just subtract '0' from the numeric character instead.
    Last edited by laserlight; 11-06-2013 at 12:29 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Sep 2013
    Posts
    23
    Thanks for all the help everyone! I finally figured it out and am very happy!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Storing Math expression as vector
    By Chucker in forum C++ Programming
    Replies: 1
    Last Post: 04-23-2012, 05:31 PM
  2. C++ homework; using strings and math
    By UWP student in forum C++ Programming
    Replies: 24
    Last Post: 09-28-2010, 04:27 PM
  3. Help! Homework using Strings
    By wco5002 in forum C++ Programming
    Replies: 16
    Last Post: 09-27-2007, 03:53 AM
  4. Help with making a Math Expression DLL
    By MindWorX in forum C Programming
    Replies: 19
    Last Post: 07-19-2007, 11:37 PM
  5. cool math homework assignment
    By BobMcGee123 in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-23-2007, 08:21 PM