1 |
h06 |
CS16 S17 |
Name: | ||||
---|---|---|---|---|
(as it would appear on official course roster) | ||||
Umail address: | @umail.ucsb.edu | |||
Optional: name you wish to be called if different from name above. | ||||
Optional: name of "homework buddy" (leaving this blank signifies "I worked alone") |
h06: Homework 6: Loops and Functions
ready? | assigned | due | points |
---|---|---|---|
true | Thu 04/20 12:30PM | Thu 04/27 12:30PM |
You may collaborate on this homework with AT MOST one person, an optional "homework buddy".
MAY ONLY BE TURNED IN IN THE LECTURE LISTED ABOVE AS THE DUE DATE. There is NO MAKEUP for missed assignments.
In place of that, we drop the two lowest scores (if you have zeros, those are the two lowest scores.)
PLEASE MARK YOUR HOMEWORK CLEARLY, REGARDLESS OF IF YOU WRITE IT OUT IN INK OR PENCIL!
-
1. (5 pts) The infinite series: s = 1 + (2/3) + (4/9) + (8/27) + .... is a geometric series that converges to a whole rational number (i.e. like 2 or 3 or 4). Below is an unfinished C++ program that will calculate s to the kth position (so, for example, if k = 1, then s = 1 + (2/3) = 1.666...). Fill in the missing code:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double s(0.0);
int k(0);
cout << "Enter k: ";
cin >> k;
for (____________________________________________________) {
s = ____________________________________________________; }
cout << "Series converges to: " << s << endl;
return 0;
}
1 #include <iostream>
2 using namespace std;
3
4 bool isDivisibleBy(int a, int b);
5
6 int main() {
7 cout << "result for (15,5) is " << isDivisibleBy(5,15) << endl;
8 cout << "result for (15,5) is " << isDivisibleBy(5,15) << endl;
9 return 0;
10 }
11
12 bool isDivisibleBy(int a, int b) {
13 return ( a % b == 0 );
14 }
for (int j = 0; j < width; j++)we wrote:
for (int j = 0; j < width; i++)(note the mistake—incrementing i as in Ivan in this loop header instead of j as in Jill.) What would happen, and why? 7. (3 pts) Consider the example of the NEW boxOfStars program as re-written by you to use the lineOfStars function (i.e. in the CHANGED program that you submitted for question #6). Suppose that we changed the loop variable in the lineOfStars function from j (as in "Jill") to i (as in "Ivan"). Would there be any problem with that? If so, what? If not, explain why not, especially in light of what we’ve discussed about the scope of variables.