Thread: Forming a maths expression that references array elements

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    35

    Forming a maths expression that references array elements

    Hi guys can someone assist me, I'm quite new in C. I'm trying to write a maths expression of sort where the letters A,B,C,D,E are corresponding elements of an array row. I need to extract it as a string eg If I input y=A*B-C+D*E I wish the ouput string to be
    5*3-2+3*4 for the first row. I've trying to do this but it's giving me a tough time.
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #define MAXCOLS 80
    main()
    {
    int num_operand =5;
    int num_operatr = 4;
    int strglen=num_operand+num_operatr;
    char operand;
    int i, j;
    char string[MAXCOLS];
    char a[2][5]={{5,3,2,3,4},{2,5,4,6,8}};
    printf("Enter a command of the sort A+B*C_D*E:\n");
    
    for(j=0; j<strglen; j++){
    operand=getchar();
    if(operand >= 'A' && operand <='Z')
    string[j]=a[0][(int)operand-(int)('A')];
    else{
    string[j]=(char)operand;}}
    
      printf("Expression\n");
      for(i=0; i<strglen; ++i){
      printf("%d \n", string[i]);
      getchar();}
     }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Perhaps some indentation would help, as well as not putting multiple closing braces on the same line.
    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
    Join Date
    Jul 2007
    Posts
    35
    Quote Originally Posted by Salem View Post
    Perhaps some indentation would help, as well as not putting multiple closing braces on the same line.
    Hi, Salem, I've tried it but it's not working, could you help me out by having a go at it?

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    You realize that saying "it's not working" is pointless. If it was working, you wouldn't be here posting about your broken code. Tell us the following in great detail:

    • what you expect the code to do
    • what the code is actually doing
    • what lines are giving you trouble (you did debug where your problem is, right? )
    • whether the code compiles or not and if not, what error messages are being spit out

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > I've tried it but it's not working
    You have to take the pizza out of the box before putting it in the microwave.
    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.

  6. #6
    Registered User
    Join Date
    Jul 2007
    Posts
    35
    Quote Originally Posted by MacGyver View Post
    You realize that saying "it's not working" is pointless. If it was working, you wouldn't be here posting about your broken code. Tell us the following in great detail:

    • what you expect the code to do
    • what the code is actually doing
    • what lines are giving you trouble (you did debug where your problem is, right? )
    • whether the code compiles or not and if not, what error messages are being spit out
    The code compiles, and when I run it if it encounters an operator it takes replaces it with the ASCII value of the operator. Like I said, I want to have the code perform, the following:
    *If I enter A+B-C-D*E as an expression, where A,B,C,D,E references the array columns. This is done by a[j](int)operand-(int)('A')].
    *I want to display the expression above as a string 5+3-2-3*4, where the letters have been replaced by their corresponding array elements. That's all I want to achieve.

    I don't know whether my approach is wrong cos I'm new in C programming, just getting to know it.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    This is what me mean by indentation and layout (red added).
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #define MAXCOLS 80
    
    int main()
    {
        int num_operand = 5;
        int num_operatr = 4;
        int strglen = num_operand + num_operatr;
        char operand;
        int i, j;
        char string[MAXCOLS];
        char a[2][5] = { {5, 3, 2, 3, 4}, {2, 5, 4, 6, 8} };
    
        printf("Enter a command of the sort A+B*C_D*E:\n");
    
        for (j = 0; j < strglen; j++) {
            operand = getchar();
            if (operand >= 'A' && operand <= 'Z')
                string[j] = a[0][(int) operand - (int) ('A')];
            else {
                string[j] = (char) operand;
            }
        }
    
        printf("Expression\n");
        for (i = 0; i < strglen; ++i) {
            printf("%d \n", string[i]);
            getchar();
        }
    
        return 0;
    }
    > I want to display the expression above as a string 5+3-2-3*4
    Well the problem is, you only print using %d, so rather than getting '+' say, you get 43 instead (in this case, it's ASCII equivalent).
    You need some extra code to do something different with the operands, especially when it comes to printing them.
    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.

  8. #8
    Registered User
    Join Date
    Jul 2007
    Posts
    35
    Thanks for the indentation Salem. I've really toiled with this code, I don't know which other approach to adopt, I've tried all I could think of for now but all to no avail. I wish someone could assist.

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Perhaps
    Code:
    char a[2][5] = { {'5', '3', '2', '3', '4'}, {'2', '5', '4', '6', '8'} };
    and replace the final printf format &#37;d with %c
    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.

  10. #10
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    [code]
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    #define MAXCOLS 80
    
    int main()
    {
        int num_operand =5;
        int num_operatr = 4;
        int strglen=num_operand+num_operatr;
        char operand;
        int i, j;
        char string[MAXCOLS];
        char getexp[strglen];
        char a[]={'5','3','2','3','4','2','5','4','6','8'};
                     
    
        printf("Enter a command of the sort A+B*C_D*E:\n");
        fgets(getexp, sizeof getexp, stdin);
    
        for(j=0; getexp[j] != '\0'; j++)
        {
           operand=getexp[j];
           
           if(operand >= 'A' && operand <='Z')
               string[j]=a[operand-(int)('A')];
           else
               string[j]=(char)operand;
        }
        string[j] ='\0';
    
        printf("Expression\n");
        
        //for(i=0; i<strglen; ++i)
            printf("&#37;s", string);
        
        getchar();
        return 0;
     }
     /* my outout
     Enter a command of the sort A+B*C_D*E:
    A+B+C
    Expression
    5+3+2
    */
    ssharish2005

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I would also change this:
    Code:
          if(operand >= 'A' && operand <='Z')
    to
    Code:
          if(operand >= 'A' && operand <='E')
    This is because anything larger than E will index outside the array.

    If you really need to do this properly (with numbers bigger than single digit) you probably need to implement a better method of converting your "variable in the string" into a number - perhaps a structure like this:
    Code:
    enum {
       OP_PLUS,
       OP_MINUS,
       OP_MUL,
       OP_DIV,
       OP_END
    } OPTYPE;
    
    struct operation {
        int operand;
        enum OPTYPE op;
    };  
    
    #define MAXOPERATIONS (some_number)
    struct operation oplist[MAXOPERATIONS];
    
    ...
    This sort of structure will allow you to translate a variable to "any" number (integer - but replace int with double in the struct operation and you would be almost unlimited).

    --
    Mats

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Which post is this referring to? If it's mine, then that's quite clear - it's just a few datatypes, you'd need to modify your code to make it use those data-structures.

    --
    Mats

  13. #13
    Registered User
    Join Date
    Jul 2007
    Posts
    35
    SSharish2005 thanks for your amendment. It's compiling but not giving any out put.

  14. #14
    Registered User
    Join Date
    Jul 2007
    Posts
    35
    Hi Mats thanks but don't really understand how to implement it. To be honest I started learning c last week

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Ok, let's forget about my suggestion at the moment - you'll probably get to "structures" at some future point in your learning.

    I've just tested the code above, and aside from the compiler moaning about some things, I found that your strglen needs to be "one more" to hold the final "nul".

    I get the following output:
    Code:
    Enter a command of the sort A+B*C-D*E:
    A+B+C+D+E
    Expression
    5+3+2+3+4
    from these changes:
    add const on the constants in the beginning of the code (that just makes my compiler compile the code in the first place - you obviously have a different compiler than my Visual Studio VC7).

    Code:
    ...
        const int num_operand = 5;
        const int num_operatr = 4;
        const int strglen=num_operand+num_operatr;
    ...
        char getexp[strglen+1];
    ...
    --
    Mats

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. using realloc for a dynamically growing array
    By broli86 in forum C Programming
    Replies: 10
    Last Post: 06-27-2008, 05:37 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM
  5. A simple question about selecting elements in an array
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 08-30-2001, 10:37 PM