Here's a C program to find sum of positive and negative elements of an array in C using for loops and IF-Else condition.
# include <stdio.h> # include <conio.h> void main() { int a[20], i, n, psum = 0, nsum = 0 ; clrscr() ; printf("Enter the limit : ") ; scanf("%d", &n) ; printf("\nEnter the elements :\n\n") ; for(i = 0 ; i < n ; i++) scanf("%d", &a[i]) ; for(i = 0 ; i < n ; i++) { if(a[i] > 0) psum = psum + a[i] ; if(a[i] < 0) nsum = nsum + a[i] ; } printf("\nSum of positive elements is : %d", psum) ; printf("\n\nSum of negative elements is : %d", nsum) ; getch() ; }
Output of above program is
Enter the limit : 5
Enter the elements :
-10 30 50 -20 40
Sum of positive elements is : 120
Sum of negative elements is : -30
Explanation of above program
Here we have some variables. So let's first take a look at each variable -
- i - is the loop variable.
- n - is the limit or number of elements that user wants to enter in the array.
- a[20] - is an integer array of size 20. That means this array a[20] can have at most 20 integer values at any time.
- psum - is used to store the sum of positive values of the array. It is initialized to zero at the start of the program.
- nsum - is used to store the sum of negative values of the array. It is initialized to zero at the start of the program.
First we ask the user to enter a limit or the number of elements he wants in the array. After that we use a for loop to enter the numbers in the array.
To calculate the sum we have another for loop which loops for the value of i = 0 to n - 1. Inside this for loop we have two IF conditions which check that the value stored in array at a particular position is positive or negative. If the value in the array is positive or greater than zero then the first IF is executed and that value is added to the sum of positive numbers i.e. psum. And If the value in the array is negative or less than zero then the second IF is executed and that value is added to the sum of negative numbers i.e. nsum.
"Hi There,
Your writing shines! There is no room for gibberish here clearly you have explained about Differences between a pointer and reference. Keep writing!
I'd really like to know what type of arguments does this function take, and what happens in the for loop.
void f(unsigned a[],unsigned b[],unsigned n,unsigned *c,unsigned(*t)(unsigned))
{
for(int i = 0; i<n;i++)
b = (*t)(a);
}
I realize that first 2 are arrays, the next one is an unsigned number, what about the last two?
It was cool to see your article pop up in my google search for the process yesterday. Great Guide.
Keep up the good work!
Grazie,
Preethi
"
Really helpful down to the ground, happy to read such a useful post. I got a lot of information through it and I will surely keep it in my mind. Keep sharing. If you are looking for some useful data and information regarding String Interview Questions then visit TutorialCup.