1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Write a Function in C programming language to solve the following problem?

Discussion in 'C' started by Flaming_Spirit, Mar 1, 2013.

  1. Flaming_Spirit

    Flaming_Spirit New Member

    Joined:
    Mar 1, 2013
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    FOLLOWING IS THE CODE FOR THE USER DEFINED HEADER FILE
    Code:
    #ifndef HW_3_H
    #define HW_3_H
    
    #include <string.h>
    #include <stdlib.h>
    
    typedef struct node {
    char *str;
    struct node *next;
    } store;
    
    store globalStore;
    
    char *copyString(char *s, int n) {
    store *copy;
    copy = (store *) malloc(sizeof(store));
    copy->str = (char *) malloc((n+1) * sizeof(char));
    copy->next = globalStore.next;
    globalStore.next = copy;
    strncpy(copy->str, s, n);
    copy->str[n] = '\0';
    return copy->str;
    }
    
    void initStore() {
    globalStore.next = NULL;
    }
    
    void freeStore() {
    store *p, *q;
    p = globalStore.next;
    while(p != NULL) {
    q = p->next;
    p->next = NULL;
    free(p->str);
    free(p);
    p = q;
    }
    }
    
    void parseDPlus(char *s, char **x, int *a) {
    *a = (s[strlen(s)-1] - '0');
    if(strlen(s) == 1) {
    *x = NULL;
    }
    else {
    *x = copyString(s, strlen(s)-1);
    }
    }
    
    char parseI(char *s, char **x, char **y) {
    char op;
    unsigned int i;
    op = '\0';
    for(i = 0; i < strlen(s); i++) {
    if(s[i] == '+' || s[i] == '*') {
    op = s[i];
    break;
    }
    }
    if(s[i] == '\0') {
    *x = s;
    *y = NULL;
    }
    else {
    *x = copyString(s, i);
    *y = (s + i + 1);
    }
    return op;
    }
    #endif
    
    ......................................…
    WE HAVE TO Define function c: Integers --> Natural Numbers
    int c(char *s)
    {
    // Step 1 (already done for you): split s into 'x' and 'y' (return value: op)
    // parseI DEFINED IN THE USER DEFINED HEADER FILE does the splitting
    char *x;
    char *y;
    char op;
    op = parseI(s, &x, &y);

    // Step 2: Examine the return-value op to decide what to do:
    // a) If op == '\0', then s == x, and hence c(s) == v(x)
    // b) If op == '+', then s == x.+.y, and hence c(s) == v(x) + c(y)
    // c) If op == '*', then s == x.*.y, and hence c(s) == ?
    ......................................…
    Fill in code for the function int c(char *s) that takes a string s and returns the
    computed value of the expression represented by s. For example, c("45") = 45, c("4+5") = 9,
    c("4*5") = 20, etc.
    Hint: First handle inputs that do not contain the * operation. Then write a mathematical definition
    of function c that correctly handles multiplication as well as addition. You may find it useful to define
    a helper function, which will also have to be coded as part of your solution to this problem.
     

Share This Page