Function Overloading with different number of arguments
Question:1
C++ program to calculate and print sum of 2 ,3, and 4 numbers?
Sol:
#include <iostream>
using namespace std;
int sum(int n1,int n2)
{
return(n1+n2);
}
int sum(int n1,int n2,int n3)
{
return(n1+n2+n3);
}
int sum(int n1,int n2,int n3,int n4)
{
return(n1+n2+n3+n4);
}
int main()
{
int a1,a2,a3,a4,a5;
cout<<"Enter 4 nos ";
cin>>a1>>a2>>a3>>a4;
a5=sum(a1,a2);
cout<<"Sum of 2 nos "<<a5<<endl;
a5=sum(a1,a2,a3);
cout<<"Sum of 3 nos "<<a5<<endl;
a5=sum(a1,a2,a3,a4);
cout<<"Sum of 4 nos "<<a5<<endl;
return 0;
}
Output:
Enter 4 nos 10
20
30
40
Sum of 2 nos 30
Sum of 3 nos 60
Sum of 4 nos 100
Question:2
Write a C++ program to calculate and print product of 2 ,3, and 4 numbers?
Sol:
#include <iostream>
using namespace std;
int prod(int n1,int n2)
{
return(n1*n2);
}
int prod(int n1,int n2,int n3)
{
return(n1*n2*n3);
}
int prod(int n1,int n2,int n3,int n4)
{
return(n1*n2*n3*n4);
}
int main()
{
int a1,a2,a3,a4,a5;
cout<<"Enter 4 nos ";
cin>>a1>>a2>>a3>>a4;
a5=prod(a1,a2);
cout<<"Prod of 2 nos "<<a5<<endl;
a5=prod(a1,a2,a3);
cout<<"Prod of 3 nos "<<a5<<endl;
a5=prod(a1,a2,a3,a4);
cout<<"Prod of 4 nos "<<a5<<endl;
return 0;
}
Output:
Enter 4 nos 2
3
4
5
Prod of 2 nos 6
Prod of 3 nos 24
Prod of 4 nos 120
Question:3
Write a C++ program to calculate and print average of 2 ,3, and 4 numbers?
Sol:
#include <iostream>
using namespace std;
float avg(float n1,float n2)
{
return((n1+n2)/2);
}
float avg(float n1,float n2,float n3)
{
return((n1+n2+n3)/3);
}
float avg(float n1,float n2,float n3,float n4)
{
return((n1+n2+n3+n4)/4);
}
int main()
{
float a1,a2,a3,a4,a5;
cout<<"Enter 4 nos ";
cin>>a1>>a2>>a3>>a4;
a5=avg(a1,a2);
cout<<"Average of 2 nos "<<a5<<endl;
a5=avg(a1,a2,a3);
cout<<"Average of 3 nos "<<a5<<endl;
a5=avg(a1,a2,a3,a4);
cout<<"Average of 4 nos "<<a5<<endl;
return 0;
}
Question:4
Write a C++ program to check and print maximum of 2 ,3 numbers and minimum of 2 and 3 numbers?
Sol:
#include <iostream>
using namespace std;
int max(int n1,int n2)
{
if(n1>n2)
return(n1);
else
return(n2);
}
int max(int n1,int n2,int n3)
{
if(n1>n2 && n1>n3)
return(n1);
else
if(n2>n3)
return(n2);
else
return(n3);
}
int min(int n1,int n2)
{
if(n1<n2)
return(n1);
else
return(n2);
}
int min(int n1,int n2,int n3)
{
if(n1<n2 && n1<n3)
return(n1);
else
if(n2<n3)
return(n2);
else
return(n3);
}
int main()
{
int a1,a2,a3,a4;
cout<<"Enter 3 nos ";
cin>>a1>>a2>>a3;
a4=max(a1,a2);
cout<<"max of 2 nos "<<a4<<endl;
a4=max(a1,a2,a3);
cout<<"max of 3 nos "<<a4<<endl;
a4=min(a1,a2);
cout<<"min of 2 nos "<<a4<<endl;
a4=min(a1,a2,a3);
cout<<"min of 3 nos "<<a4<<endl;
return 0;
}
Output:
Enter 3 nos 25
6
34
max of 2 nos 25
max of 3 nos 34
min of 2 nos 6
min of 3 nos 6




