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

Monday, March 15, 2010

Write definitions for two versions of an overloaded function. This function's first version sum() takes an argument, int array, and returns the sum of all the elements of the passed array. the 2nd version of sum() takes two arguments, an int array and a character ('E' or 'O'). If the passed character is 'E', it returns the sum of even elements of the passed array and if the passed character is 'O', it returns the sum of odd elements. In case of any other character it returns 0 (zero).


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

int sum( int a[]); // sum of all elements of an array
int sum(int a[], char ch); // sum of odd or even elements of an array, depending on choice

void main()
{
int num[10];

cout<< "\n Enter 10 integers : ";

for(int i = 0;  i < 10 ;  i++ )
cin >> num[i];

/* Sum of all 10 integers */
int s = sum(num);
cout<< "\n The Sum of all 10 integers = " << s;

/* Sum of all the even numbers out of all the 10 integers */
s = sum(num, 'E');
cout<< "\n The Sum of all even numbers out of all 10 integers = " << s;


/* Sum of all the odd numbers out of all the 10 integers */
s = sum(num, 'O');
cout<< "\n The Sum of all odd numbers out of all 10 integers = " << s;


/* No result...for wrong choice */
s = sum(num , 'X');
cout<< "\n No Sum for wrong choice . Hence the result  = " << s;


getch();
}

// Function definition of FIRST sum function

 
int sum(int arr[])
{
int s = 0;
for ( int i = 0; i <10 ; i++ )
s = s+ arr[i];

return s;
}


// Function definition of SECOND sum function
int sum(int arr[], char a)
{
int se = 0, so = 0, s = 0;

switch(a)
{
case 'E':
case 'e':

             for ( int i = 0; i <10 ; i++ )
               {
                     if(arr[i]%2 == 0)
                        se = se+ arr[i];
               }
              s = se;
              break;

case 'O':
case 'o':
             for ( int i = 0; i <10 ; i++ )
             {
              if(arr[i]%2 ! = 0)
                 so = so + arr[i];
             }
            s = so;
            break;
default :
           s = 0;
}

return s;
}

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.