Question: 8
C++ program to calculate and print product of 2 numbers, the number may be an integer, float, or double.
Sol:
#include<iostream> using namespace std; int prod(int n1,int n2) { return(n1*n2); } float prod(float n1,float n2) { return(n1*n2); } double prod(double n1,double n2) { return(n1*n2); } int main() { int a1,a2,a3; float b1,b2,b3; double d1,d2,d3; //int cout<<"Enter 2 nos (int) "; cin>>a1>>a2; a3=prod(a1,a2); cout<<"prod = "<<a3<<endl; //float cout<<"Enter 2 nos (float) "; cin>>b1>>b2; b3=prod(b1,b2); cout<<"prod = "<<b3<<endl; //double cout<<"Enter 2 no2 (double) "; cin>>d1>>d2; d3=prod(d1,d2); cout<<"prod = "<<d3<<endl; return(0); }
/* Output */ Enter 2 nos (int) 2 3 prod = 6 Enter 2 nos (float) 3.2 6.32 prod = 20.224 Enter 2 no2 (double) 23.36 5632.325 prod = 131571
Question:9
C++ program to calculate and print average of 2 numbers, the number may be an integer, float, or double.
Sol:
#include<iostream> using namespace std; int avg(int n1,int n2) { return((n1+n2)/2); } float avg(float n1,float n2) { return((n1+n2)/2); } double avg(double n1,double n2) { return((n1+n2)/2); } int main() { int a1,a2,a3; float b1,b2,b3; double d1,d2,d3; //int cout<<"Enter 2 nos (int) "; cin>>a1>>a2; a3=avg(a1,a2); cout<<"avg = "<<a3<<endl; //float cout<<"Enter 2 nos (float) "; cin>>b1>>b2; b3=avg(b1,b2); cout<<"avg = "<<b3<<endl; //double cout<<"Enter 2 no2 (double) "; cin>>d1>>d2; d3=avg(d1,d2); cout<<"avg = "<<d3<<endl; return(0); }
/* Output */ Enter 2 nos (int) 10 20 avg = 15 Enter 2 nos (float) 3.2 2.3 avg = 2.75 Enter 2 no2 (double) 236.32 563.325 avg = 399.822