Rewrite the following for loop into a while loop. 1 2 3 4 int s = 0; for (int i
ID: 3663292 • Letter: R
Question
Rewrite the following for loop into a whileloop.
1
2
3
4
int s = 0;
for (int i = 1; i <= 10; i++) {
s = s + i;
}
Given variables int n and double pi, write a snippet of code that assigns to pi the approximation of resulting from adding the first nterms in the Gregory-Leibniz series:
both n and m are at least 1, and
n2 < areaBound, and
m2 < areaBound.
n2 < areaBound, and
m2 < areaBound.
Modify the loop to approximate pi with the Gregory-Leibniz series so that, instead of adding a given number of terms, it keeps adding terms until the difference between two consecutive estimates is less than some predefined tolerance, say double epsilon = 0.0001.
1
2
3
4
int s = 0;
for (int i = 1; i <= 10; i++) {
s = s + i;
}
Explanation / Answer
1.
int s = 0;
int i = 1;
while(i <= 10) {
s = s + i;
i++;
}
2.
double pie = 0;
int i = 0;
while(i <= n) {
if(i % 2 == 0){
pie = pie + (1.0/(2*i + 1));
}else{
pie = pie - (1.0/(2*i + 1));
}
}
pie = 4*pie;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.