Write a C++ program that prompts the user for a positive integer greater than 1
ID: 3545637 • Letter: W
Question
Write a C++ program that prompts the user for a positive integer greater than 1 and displays the square root, the square and the cube of all numbers from 2 to the entered number in a tabular format similar to the sample output in figure 1. Use the sqrt() and pow() functions. The square root value must be displayed with 4 places after the decimal.
Your program should loop until the user enters 0 to quit. Your program should also check for invalid input from the user ( 1 or a negative number) and keep prompting until a 0 to quit or a value greater than 1 is entered.
Restrictions: Your solution must contain each type of loop at least once (while, do .. while and for loop).
Following is a sample output to illustrate the expected behavior of your program.
Explanation / Answer
#include<iostream.h>
#include<math.h>
#include<iomanip.h>
void calc(int a)
{
float sq=sqrt(a);
cout<<a<<" ";
std::cout<<std::setprecision(4)<<sq<<" ";
cout<<pow(a,2)<<" "<<pow(a,3)<<" ";
}
int main()
{
int n,b=0;
do{
cout<<"Enter a positive number greater than 1(or 0 to quit)";
cin>>n;
if(n==1||n<0)
{
cout<<" -->"<<n<<"is not greater than 1 ";
}
else
{
cout<<"Number "<<"Square root "<<"Sqaure "<<"Cube ";
while(b<60)
{
cout<<"-";
b++;
}
cout<<" ";
for(int i=2;i<=n;i++)
{
calc(i);
}
}
}
while(n!=0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.