In: Computer Science
Use a while(true) loop to ask the user the following 2 values
“Enter a rate r =” “Enter a nonnegative integer (enter negative
integer to quit):”
If the user enters a negative int for n, the while loop is broken
via the brake statement. Otherwise,
in the remaining part of the while loop, use a for loop to compute
the partial sum for the geometric
series, namely 1 + r + rˆ2 + rˆ3 + . . . +rˆn.
Use the iomanip library in order to print the sum with 50 decimal
digits of precision.
Sample output:
Enter a rate r = 4
Enter a non-negative integer (enter negative integer to quit):
9
1 + 4^1 + 4^2 + 4^3 + 4^4 + 4^5 + 4^6 + 4^7 + 4^8 + 4^9 =
349525
Enter a rate r = 0
Enter a non-negative integer (enter negative integer to quit):
3
1 + 0^1 + 0^2 + 0^3 = 1
Enter a rate r = -4
Enter a non-negative integer (enter negative integer to quit):
-2
C++
Will like if correct,thank you.
CODE -
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
int r;
int n;
int sum;
cout << setprecision(50);
while(true)
{
// Take rate as input from the user
cout << "Enter a rate r = ";
cin >> r;
// Take a non-negative integer as input from the user
cout << "Enter a non-negative integer (enter negative integer to quit): ";
cin >> n;
// Exit the loop if user enters a negative integer
if(n<0)
break;
// Initialize the sum to 1
sum = 1;
cout << sum;
// Loop to compute partial sum for the geometric series and display the equation
for(int i=1; i<=n; i++)
{
sum += pow(r, i);
cout << " + " << r << "^" << i;
}
// Display the sum
cout << " = " << sum << endl;
}
}
SCREENSHOTS -
CODE -
OUTPUT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.