a. Implement an iterative function that takes an array of integers and the size of
the array, and returns the sum of the contents of the array.
b. Modify your function as to be defined in a recursive manner.
c. In order to test your functions, implement a program with a suitable “menu”.

These are my tasks. And i've just complated the first task 'a' .Could you please check if my codes are ok?
And i have another question: How can i modify function to make it recursive.
Thank you for your answers already.

int arraySum (int *a, int size );

int main()
{   
    int i;
    int *x;
    
    printf(" How many numbers do you want to sum: ");      
    scanf("%d",&i);
    
    x=malloc(sizeof(int)*i);
    
    printf("\The Sum is: %d \n\n",arraySum(x,i)); 
        
    system("pause");   
    return 0;
    
    
} 
    
int arraySum (int *a,int size)
{
    int b, Sum=0;
      
    for(b=0;b<size;b++)
    {
        Sum=Sum+ a[b];                
    }
                   
    return Sum;           
}

Edited 6 Years Ago by spookytr: n/a

Added a few things

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

int arrayToplam (int *a, int size );

int main()
{   
	int i, j = 0;
	int *x = (int*)NULL;

	printf(" Kac Sayi Toplamak Istiyorsunuz: ");      
	scanf("%d",&i);

	x = malloc(sizeof(int)*i);
	
	if (!x)
	{
		fputs("could not allocate memory!\n", stderr);
		exit(EXIT_FAILURE);
	}

	for (j = 0; j < i; ++j)/*just some data to play with*/
		x[j] = j + 1;

	printf("\n Sayilarin Toplami: %d \n\n",arrayToplam(x,i)); 
	   
	free(x);
	x = (int*)NULL;

	exit(EXIT_SUCCESS);
} 
    
int arrayToplam (int *a,int size)
{
	int b, Toplam=0;

	for(b=0;b<size;b++)
	{
		Toplam += a[b];                
	}   
	return Toplam;           
}

Edited 6 Years Ago by gerard4143: n/a

thank you very much. now how can i modify the functoin to convert it to a recursive function. this is important .

thank you very much. now how can i modify the functoin to convert it to a recursive function. this is important .

Its really not that hard to convert what you have, just make sure to add a print statement so you can track what your recursive function is doing. When the function works remove the print function.

int arrayToplam (int *a, int size)
{
		fprintf(stdout, "ans->%d\n", a[size - 1]);
	return 0;
}

Note to help you, you have to show some effort...

i am new in c . and i really don't know what

fprintf(stdout, "ans->%d\n", a[size - 1]);

that means

Note to help you, you have to show some effort...

i do, i really do. i wrote those codes and i took long time for me. i'm trying to understand arrays and functions .

This article has been dead for over six months. Start a new discussion instead.