开发者

c program recursive function odd [closed]

开发者 https://www.devze.com 2023-02-19 03:39 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an 开发者_JS百科extraordinarily narrow situation that is not gen
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an 开发者_JS百科extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

I need a recursive function in C, that checks/compare the sum of values(integers) in odd positions, with the sum of values in even positions of an array. Also print(inside the function) the bigger sum!

Like:

printf("\nThe bigger sum is %d. \n evensum = %d , oddsum = %d \n",bigger, evensum, oddsum);

Suppose that array has 8 positions and we fill it from main() with random values.

This is what I have so far:

#include <stdio.h>
#define N 4


int checksum(int matrix[], int position, int sum1, int sum2); 

int main(void)
{
    int mat[N];
    int i,j;

    printf("\nEnter the %d numbers:\n", N); 

      for(i = 0; i < N; i++)
      {
        printf("%2d> ",i);
        scanf("%d", &mat[i]);
      }

      checksum(mat, 0, 0, 0);       


}

int checksum(int m[], int pos, int s1, int s2){

if(pos<N){
    if(pos==0){
            s1 = m[pos];    
            checksum(m, pos+1, s1, s2);         
        }else{
            if(pos%2){
                return s1 + checksum(m, pos+1, s1, s2);     

            }else{
                return s2 + checksum(m, pos+1, s1, s2);                         
            }

        }

    }

}


Besides all the fun they picked at you, I understand you was honest tagging "homework". What I'm about to show you is your solution. To make the most of this, you should understand it. If not, you are just fooling yourself. I really hope this can help you in other ways than just a homework done.

You still need to fulfill the vector with random values, and to print the bigger. But this is piece of cake. The recursion can be made like this:

#include <stdio.h>
#define MAX 10

int sum(int *x, int n, int odd)
{

    if(odd==-1)
    {
        printf("odd = %d, even = %d\n", sum(x, n, 1), sum(x, n, 0));
        return 0;
    }

    if(n%2!=odd)
        return sum(x, n+1, odd);

    if(n>=MAX)
        return 0;

    return x[n]+sum(x, n+1, odd);
}



int main(void)
{
    int x[MAX]={0,1,2,3,4,5,6,7,8,9};

    sum(x, 0, -1);

    return 0;
}

For one thing your question lacks... If you read the definition pausing your mouse cursor at the tag homework, you will read "and show sufficient effort".

So, please, after adapting the code as you need, how about you show the final answer here as a token of your effort to learn c language? ;)

Take care! Beco.

0

精彩评论

暂无评论...
验证码 换一张
取 消