"The best way to cheer yourself up is to try to cheer somebody else up." Mark Twain

Wednesday, February 10, 2010

Write a program with a function to receive an integer array, its size and a character '+' or '-'. By default, the character should be '+'. For the character '+', the function returns the sum of positive numbers stored in the array and for the character '-', the function returns the sum of the negative numbers in the array.


#include<iostream.h>
#include<conio.h>

int funct(int a[], int n, char s = '+')
{
int sum = 0;
for(int i = 0; i< n ; i++ )
{
if(s == '+')
 {
if(a[i] > 0 )
sum + = a[i];
}
else
{
if(a[i]<0)
sum+=a[i];
}
}
return sum;
}

void main()
{
int arr[20], dn;
cout<<"\n Enter dimension :";
cin>> dn;

for(int i = 0; i< dn ; i++)
{
cout<<"\n Enter any interger (positive / negetive )";
cin>> arr[i];
}

/* ... Sum of all positive integers in the array ... */
int s = funct( arr, dn);

/* .... Sum of all negative integers ..*/
int s2 = funct(arr, dn, '-');

cout<< "\n The sum of the positive integers : " << s;
cout<< "\n The sum of all negative integers : " << s2;

getch();
}

No comments:

Post a Comment

C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.
Now Playing: Ballade Pour Adeline

About Me

My photo
I m an IT lecturer of a college. I love social-work. I want to do something beneficial for society before dying , that can promote our society, to some extent.