Write a program in C++. You need everything everythihng given You will create a
ID: 3765056 • Letter: W
Question
Write a program in C++. You need everything everythihng given
You will create a function that validates input. It should accept only non-negative integers. If the input is incorrect the function should throw an exception. The exception will not be caught in the function.
You will create a function that reads in 2 integer values. One is a number that will be raised to the power of the second. So if 5 and 6 are entered the result would be 5 to the 6th power. If an invalid input is received take appropriate action in response to the exception.
You will create a second function that reads in a series of numbers and calculates the average and standard deviation of them. Read in numbers until a -1 is entered. Validate all the numbers and generate an appropriate message in response to eh exception.
Your program should call the power function and the averaging function, prompt the user as appropriate, validate the inputs, calculate and display the results.
Explanation / Answer
Please find the code:
#include<iostream>
#include<math.h>
using namespace std;
int validate_input(int p)
{
if(p<0)
{
throw "Negative integers not allowed";
}
}
void power_test()
{
int x, y, power;
cout<<"Enter the first number"<<endl;
cin>>x;
cout<<"Enter the second number"<<endl;
cin>>y;
power=pow(x,y);
cout<<power<<endl;
}
void calc_avg()
{
int list[20],i=0,sum=0,n=20;
float avg=0,std_dev=0;
cout<<"Please enter the list of integers to calculate average"<<endl;
for (i=0;i<n;i++)
{
cout<<" Enter ["<< i+1 << "] Number:",i+1;
cin>>list[i];
validate_input(list[i]);
if(list[i]==-1)
break;
sum=sum+list[i];
}
avg=float(sum)/float(n);
cout<<" Average ="<<avg;
getchar();
}
int main()
{
int choice;
cout<<"Enter your choice"<<endl;
cout<<"1. Calculate average of numbers"<<endl;
cout<<"2. Calculate power "<<endl;
cout<<"3. Exit"<<endl;
cin>>choice;
if(choice==1)
{
calc_avg();
}
else if(choice==2)
{
power_test();
}
else if(choice==3)
{
exit(0);
}
return(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.