Hello all

I have been learning C for about 3 - 4 weeks now and I'm in need of some help.

I am trying to write a function that will give you the sum of selected integers in an array with a value of 20. I can make it give me a total for all of the intergers but not when i select certain integer positions, ie: say array positions 0 to 4 or array positions 15 to 19.

This is what I have so far
Function Protocol
int sum(int[], int, int);

Function Definition

int sum(int num_array1[], int start, int end)
	{
		int total=0;


		for(int a=start; a<=end; a++)
		{
			total = total + num_array1[a];
			
			return(total);

Thanks for any suggestions

how did that even compile? It is missing two closeing } character. Assuming that is just a posting error the code looks ok to me.

The missing } were just posting error.

When I call the function in main the only answer I get is what the first array position is.

total=sum(num_array1,0,4);
printf("answer = %d \n", total);

ok, this is what i have in main

int main()
{
	int num_array1[] = {7,9,16,2,53,74,31,14,13,8,95,34,17,41,21,29,33,1,11,105} ;
	int answer = 0;
	int i=0;
	int j=0;
	int total;


	for(i=0; i<=end; i++)
	{

		printf("position 0= %d \n", num_array1[0]);
		printf("position 4 = %d \n", num_array1[4]);
		total=sum(num_array1, 0, 4);
		printf("answer = %d \n", total);

		printf("position 5= %d \n", num_array1[5]);
		printf("position 9 = %d \n", num_array1[9]);
		total=sum(num_array1, 5, 9);
		printf("answer = %d \n", total);
		
	}

	for (j=0; j<20; j++ )
	{
		answer += num_array1[j];
	}
	printf("answer = %d \n", answer);


	return(0);

}

the answer i get for the first sum is 7 the second sum is 74 and the grand total is 614

Thanks for an suggestions

I changed the return to outside the for loop in the Function Definition and that did the trick.

Thanks...I didn't notice that before

int sum(int num_array1[], int start, int end) // Function Definition
	{
		int total=0;

		for(int a=start; a<=end; a++)
		{
			total = total + num_array1[a];

		}

		return(total);
		
	}
This question has already been answered. Start a new discussion instead.