Skip to content

Instantly share code, notes, and snippets.

@m-ahmedy
Created May 17, 2017 18:36
Show Gist options
  • Save m-ahmedy/66a22cda51c6413673a1ef1230363db8 to your computer and use it in GitHub Desktop.
Save m-ahmedy/66a22cda51c6413673a1ef1230363db8 to your computer and use it in GitHub Desktop.
A function that returns the sum of all negative elements within an array.
#include <iostream>
using namespace std;
int getSumNeg(int a[],int a_length)
{
int sum=0;
for(int i=0 ; i<a_length ; i++)
{
if(a[i]<0)
sum+=a[i];
}
return sum;
}
int main()
{
//Initialization
int arr_length=0;
cout<<"Enter array length: ";
cin>>arr_length;
int arr[arr_length]= {0};
//Data Entry
for(int i=0 ; i<arr_length ; i++)
{
cout<<"Enter value #"<<i+1<<" : ";
cin>>arr[i];
}
//Output
cout<<"The sum of all negative values in the array is : "<< getSumNeg( arr, arr_length)<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment