Cpp - Write program to create sum() with default parameters

Requirements

Write the function sum() with four parameters that calculates the arguments provided and returns their sum.

  • Parameters: Four variables of type long.
  • Returns: The sum of type long.

Use the default argument 0 to declare the last two parameter of the function sum().

Test the function sum() by calling it by all three possible methods.

Use random integers as arguments.

Hint

Demo

#include <iostream> 
#include <iomanip> 
#include <ctime> 
#include <cstdlib> 
using namespace std; 
long sum( long a1, long a2, long a3=0, long a4=0); 
int main()             // Several calls to function sum() 
{ 
   cout << "  **** Computing sums  ****\n" 
        << endl; /*w  w  w.  j a va 2s. c o  m*/

   srand((unsigned int)time(NULL));  // Initializes the 
                                 // random number generator. 
   long res, a = rand()/10, b = rand()/10, 
             c = rand()/10, d = rand()/10; 

   res = sum(a,b); 
   cout << a << " + " << b << " = " << res << endl; 

   res = sum(a,b,c); 
   cout << a << " + " << b << " + " << c 
        << " = " << res << endl; 

   res = sum(a,b,c,d); 
   cout << a << " + " << b << " + " << c << " + " << d 
        << " = " << res << endl; 

   return 0; 
} 

long sum( long a1, long a2, long a3, long a4) 
{ 
   return (a1 + a2 + a3 + a4); 
}

Result

Related Exercise