1

I need help with my homework. I need to build a function which calculates the sum of members in an array. I have a 4X4 array and i need to calculate the sum of lets say members from the first row. I need to do this for each combination of sums on the row for a given number of members from that row and check if it matches the sum the users has given me. if the row is 1 2 3 4. I need to check (1+2+3+4), (2+3+4), (3+4) , (1), (2), (3), (4) i know how to check (1) (2) (3) (4) the problem is that once I get to the end of the first sum (1+2+3+4) i don't how to return to the index which starts the sum (2+3+4) without using static variables. my code is this:

bool row_sum(int length,int sum, int mat[N][N])
{
int temp_sum=0, i=0, j=0, cnt1=0;
while (i<N)
{
    while(j<N)
    {
        cnt1++;
        temp_sum += mat[i][j];
        if ((temp_sum==sum) && (cnt1==length))
        {
            return 1;
        }
        else if (temp_sum<sum)
        {
            j++;
            continue;
            }
        else if (temp_sum>sum)
        {
            if (j==N-1)
            {
                temp_sum=0;
                cnt1=0;
                j=N;
                break;
            }
            else
            {
            temp_sum=0;
            j=(cnt1-j);
            cnt1=0;
            }
        }
        else if ((temp_sum<sum) && (cnt1=length))
        {
            temp_sum=0;
            j=(cnt1-j);
            cnt1=0;
        }
    }
i++;
}
     return 0;
}

I hope that I am clear.. it's hard to describe the problem. Thank you, Adi.

adi.raib91
  • 11
  • 1

1 Answers1

0

An array is stored as a sequence of elements (char, int,...) in memory, see How is the array stored in memory?

You can either access the elements of an array using pointers (see pointer arithmetics https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html) or by direct addressing using the subscripts, see this http://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm

     0    1    2    3

0    a    b    c    d

1    e    f    g    h

2    i    j    k    l

3    m    n    o    p

So if you want to get the letter 'k' in the char array above use char c = array[2][2]; if you want to get the letter 'i' use char c = array[2][0];

Community
  • 1
  • 1
ralf htp
  • 9,149
  • 4
  • 22
  • 34