Function With Default Arguments: Example
Function With Default Arguments: Example
Example:
#include <iostream.h>
void repchar(char='*', int=45); //declaration with
//default arguments
void main()
{
repchar(); //prints 45 asterisks
repchar('='); //prints 45 equal signs
repchar('+', 30); //prints 30 plus signs
}
Note:
• If one argument is missing when the function is called, it is
assumed to be the last argument.
• The missing arguments must be the trailing arguments—those at
the end of the argument list.
Recursive Function
A recursive function is a function that calls itself in order to perform a
task of computation. There are two basic components of a recursive
solution:
Important Notes
• Recursive functions must have a termination step and an inductive
step.
• Recursive function calls in inductive step must signify a reduction
of argument value.
• Be aware of infinite recursion problem.
• Recursion is implicit while iteration is explicit.
• Recursion is slower than iteration.
int countingDigits(long n)
{
if (n / 10 == 0)
return 1;
else
return( countingDigits(n/10) + 1 );
}
Function Overloading
Overloading refers to the use of the same thing for different purposes.
Function overloading means that we can use the same function name to
create functions that perform a variety of different tasks. These
overloaded functions have the same function name but with different
argument lists (i.e. different number and/or different data types of
arguments). An overloaded function appears to perform different
activities depending on the kind of data sent (passed) to it. It performs
one operation on one kind of data but another operation on a different
kind.
Example: Write a C++ program that computes the area of square and the
area of rectangle using the overloaded function area().
#include<iostream.h>
int area(int);
int area(int , int);
void main()
{
int length , width;
cout<<"Enter a length of square: ";
cin>>length;
cout<<"The area of square is " <<area(length)<<endl;
cout<<"Enter a length and width of rectangle: ";
cin>>length>>width;
cout<<"The area of rectangle is "
<<area(length,width)<<endl;
}
int area(int a)
{
return (a * a);
}
int volume(int s)
{
return (s * s * s);
}
Homework:
1. Write a C++ program that computes the power of an entered integer
number using the recursive function power().
2. Write a C++ program that adds two numbers of different numeric data
types (e.g. integers, float, double) using the overloaded function
add().