Issue with interpreting equations containing multiple levels of parentheses

I am working on a C program to interpret chemical formulas that may include multiple levels of parentheses, and I am facing difficulties with correctly interpreting these formulas. The goal is to associate each atom with a variable based on a provided formula.
I am using the code below to process chemical formulas with varying levels of complexity. For example, for the formula {"2F2(SO4)3", 'A'}, the processing is correct; however, for {"Na(H2(SO3)4)5", 'B'}, the interpretation is incorrect. The expected result for {"Na(H2(SO3)4)5", 'B'} should be Na + H10 + S20 + O60, but it is resulting in Na + H10 + S10 + O15, indicating that the processing of nested parentheses is not functioning as expected.
From what I observed, the logic is multiplying the innermost parenthesis by the factor of the outermost parenthesis. For example, in (H2(SO3)4)5, it is multiplying 'O3' by 5 instead of by 4 before then multiplying by 5.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct {
    char symbol[3];  // Atom symbol (e.g., "H", "O")
} Atom;

typedef struct {
    char term[50];    // Formula term (e.g., "2H2O", "3CO2")
    char variable;    // Variable associated with the term
} Association;

void printVariableAtomTable(Atom *atoms, int numAtoms, Association *terms, int numTerms) {
    // Print table header
    printf("nTable of Association between Variables and Elements:n");
    printf("Variable: ");
    for (int i = 0; i < numTerms; i++) {
        printf("%c  ", terms[i].variable);
    }
    printf("n");

    // Create matrix to store the quantity of each atom associated with each variable
    int **table = (int **)malloc(numAtoms * sizeof(int *));
    if (table == NULL) {
        printf("Error: Failed to allocate memory for table.n");
        exit(1);
    }

    for (int i = 0; i < numAtoms; i++) {
        table[i] = (int *)calloc(numTerms, sizeof(int));
        if (table[i] == NULL) {
            printf("Error: Failed to allocate memory for table.n");
            exit(1);
        }
    }

    // Fill the table with the quantity of each atom associated with each variable
    for (int j = 0; j < numTerms; j++) {
        char *term = terms[j].term;
        int termCoefficient = 1;
        int multiplier = 1;

        // Check if there is a numeric coefficient associated with the term (if any)
        char *coeffEnd = strchr(term, '(');
        if (coeffEnd != NULL) {
            sscanf(coeffEnd + 1, "%d", &termCoefficient);
        }

        int k = 0;
        while (term[k] != '') {
            if (isdigit(term[k])) {
                multiplier = term[k] - '0'; // Convert the numeric char to integer
                k++;
                continue;
            }

            if (isupper(term[k])) {
                char symbol[3] = { term[k], '' };
                int m = k + 1;
                while (term[m] != '' && islower(term[m])) {
                    strncat(symbol, &term[m], 1);
                    m++;
                }

                int elementCoefficient = 1;
                if (term[m] != '' && isdigit(term[m])) {
                    elementCoefficient = term[m] - '0';
                    m++;
                }

                int elementIndex = -1;
                for (int n = 0; n < numAtoms; n++) {
                    if (strcmp(atoms[n].symbol, symbol) == 0) {
                        elementIndex = n;
                        break;
                    }
                }

                if (elementIndex != -1) {
                    table[elementIndex][j] += elementCoefficient * multiplier * termCoefficient;
                }

                k = m;
            } else if (term[k] == '(') {
                // Start of a group within parentheses
                int start = k + 1;
                int depth = 1;
                int end = start;

                // Find the end of the group within parentheses
                while (term[end] != '' && depth > 0) {
                    if (term[end] == '(') {
                        depth++;
                    } else if (term[end] == ')') {
                        depth--;
                    }
                    end++;
                }

                // Process the group within parentheses
                int groupCoefficient = 1;
                if (term[end] != '' && isdigit(term[end])) {
                    sscanf(&term[end], "%d", &groupCoefficient);
                }

                int innerCoefficient = 1;
                int n = start;
                while (n < end) {
                    if (isupper(term[n])) {
                        char groupSymbol[3] = { term[n], '' };
                        int m = n + 1;
                        while (term[m] != '' && islower(term[m])) {
                            strncat(groupSymbol, &term[m], 1);
                            m++;
                        }

                        int groupIndex = -1;
                        for (int a = 0; a < numAtoms; a++) {
                            if (strcmp(atoms[a].symbol, groupSymbol) == 0) {
                                groupIndex = a;
                                break;
                            }
                        }

                        if (groupIndex != -1) {
                            if (term[m] != '' && isdigit(term[m])) {
                                sscanf(&term[m], "%d", &innerCoefficient);
                                while (term[m] != '' && isdigit(term[m])) {
                                    m++;
                                }
                            }
                            table[groupIndex][j] += termCoefficient * innerCoefficient * groupCoefficient * multiplier;
                        }

                        n = m;
                    } else {
                        n++;
                    }
                }

                k = end;
            } else {
                k++;
            }
        }
    }

    // Print the table of association between variables and elements
    for (int i = 0; i < numAtoms; i++) {
        printf("%s: ", atoms[i].symbol);
        for (int j = 0; j < numTerms; j++) {
            if (table[i][j] != 0) {
                if (table[i][j] == 1) {
                    printf("%c  ", terms[j].variable);
                } else {
                    printf("%d%c  ", table[i][j], terms[j].variable);
                }
            } else {
                printf("0%c  ", terms[j].variable);
            }
        }
        printf("n");
    }

    // Free allocated memory for the table
    for (int i = 0; i < numAtoms; i++) {
        free(table[i]);
    }
    free(table);
}

int main() {
    // Example input data (atoms and terms)
    Atom atoms[] = { {"F"}, {"O"}, {"S"}, {"H"}, {"Na"} };
    Association terms[] = { {"2F2(SO4)3", 'A'}, {"Na(H2(SO3)4)5", 'B'} };
    int numAtoms = sizeof(atoms) / sizeof(Atom);
    int numTerms = sizeof(terms) / sizeof(Association);

    // Function call
    printVariableAtomTable(atoms, numAtoms, terms, numTerms);

    return 0;
}

Result

Table of Association between Variables and Elements:
Variable: A  B  
F: 4A  0B  
O: 24A  15B  
S: 6A  10B  
H: 0A  10B  
Na: 0A  B  

How can I modify my code to correct the interpretation of formulas with multiple levels of parentheses?
Is there a more efficient way to handle the analysis of chemical formulas with varying complexity, including nested parentheses?
I appreciate any help or suggestions to solve this formula interpretation problem. Thank you!

New contributor

Unsigned Index is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật