Function that returns sum of negative array elements.

So, problem is "Find the sum of the negative elements of the a[n] array."

I can write the function but I don't know how to use it in a program to test if I've done it right or not. Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"


int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}


int negative(int a[10])
{

	int sum = 0, i;
	
	for (i=0; i<10; i++)
	{
                scanf("%d", &a[i]);

		if (a[i] < 0)
		{
			sum = sum+ a[i];
		}
		return sum;
	}
}
Last edited on
Lines 1-3: #include <stdio.h> You don't need stdafx.h or conio.h.

Line 6: If you aren't using compiler-specific extensions, use the standard entry point: int main()

Line 12: The argument's array length is ignored by the compiler; you should add an argument to know the length of the array.

Line 19: Your array is doing something other than summing the negative elements in an array.

Line 25: Don't return from inside the loop. Wait until the loop finishes. (Put the return statement after the loop.)

Stick your main function last, and your other functions first. The main function should declare the array of integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>

int sum_negative_elements( int a[], int length )
{
	/* put your code here. Remember, the length of the
	   array is 'length', not '10'. */
}

int main()
{
	/* here I have an array that is in the program. you might want to
	   make the array and then get the user to enter as many elements
	   (for n <= LEN) as he wants... */
	static int LEN = 11;
	int values[ LEN ] = { 1, 43, -19, 27, 512, -7, -3, 32, 112, -20000, 8 };

	/* you might want to do something like print the array here? */
	/* (but you don't have to) */

	int sum = sum_negative_elements( values, LEN );

	/* print the result */
	printf( "The negative elements sum to %d\n", sum );

	return 0;
}

Hope this helps.
Y, I got it now.
stdatfx is from the compiler, conio is because i want to see the output with printf and getch.

int _tmain..... is also from the compiler but I see it works just as u said as well.

line 19 removed.

line 25 is smth I hadn't seen as I always do what u recommended.

Put the function above the int main as well.

Works great now, tyvm, got an exam tomorrow and seems I hadn't quite understood functions the way I'd want to.
Topic archived. No new replies allowed.